pynput with Phidgets

In this project, you will learn how to use pynput with Phidgets. You will use your Getting Started Kit to control the dinosaur in Chrome's dinogame!

Prerequisites

This project assumes you are familiar with the following

Setup

All you need for this project is the Getting Started Kit.

Getting Started Kit

What is pynput?

pynput is a Python library that makes it incredibly easy to control and monitor input devices such as your mouse and keyboard. With pynput, you can press keys on your keyboard, or move your mouse, all from your Python program!

Install pynput

In order to use pynput, you first have to install it. You do this in the same way you previously installed the Phidget22 library. Simply navigate to your package manager, search for pynput and press install!

Thonny

If you're using Thonny, select Tools > Manage Packages and search for pynput.

PyCharm

If you're using PyCharm, select File > Settings > Python Interpreter and use the + symbol to install pynput.

PyScripter

If you're using PyScripter, select Tools > Tools > Install Packages with pip and enter pynput.

Write code (Python)

Copy the code below into a new Python project. If you need a reminder of how to do this, revisit the Getting Started Course.

  
#Add Phidgets Library
from Phidget22.Phidget import *
from Phidget22.Devices.DigitalInput import *
from pynput.keyboard import Key, Controller
import time
 
#Event
def onRedButton_StateChange(self, state):
    #If the button is pushed, simulate a spacebar press to make the dino jump!
    if(state):
        keyboard.press(Key.space)
        keyboard.release(Key.space)
  
#Create
keyboard = Controller() #this is from the pynput library
redButton = DigitalInput()
 
#Address
redButton.setIsHubPortDevice(True)
redButton.setHubPort(0)
 
#Subscribe to Events
redButton.setOnStateChangeHandler(onRedButton_StateChange)
 
#Open
redButton.openWaitForAttachment(1000)
 
#Keep program running
while(True):
    time.sleep(0.15)
  

Run Your Program

Navigate to the dinogame, you can do this in a few ways:

Click on the dinosaur and then use your red button to start playing!

Practice

  1. Try using a different Phidget to control the game. For example, you could use a distance sensing Phidget and jump when your hand is hovering over the sensor at a certain height.
  2. Try controlling your mouse with pynput and Phidgets. Get started here

What are Phidgets?

Phidgets are programmable USB sensors. Simply plug in your sensor, write code in your favorite language and go!

Phidgets have been used by STEM professionals for over 20 years and are now available to students.

Learn more

Set your preferences

Windows

Mac OS

Raspberry Pi

Java

Python

C#

Swift

NetBeans

Processing

Eclipse

Thonny

PyCharm

PyScripter

Visual Studio

Xcode

Setting your preferred operating system, programming language and environment lets us display relevant code samples for the Getting Started Tutorial, Device Tutorials and Projects

Done