Raspberry pie basic experiment 14: PS2 joystick experiment

1, Introduction

   a joystick is an input device consisting of a joystick that can rotate on a base and report its angle or direction to the device it controls. Joysticks are commonly used to control video games and robots. The joystick PS2 is used here.

2, Components

★ Raspberry Pi 3 motherboard *1

★ raspberry pie power supply *1

★ 40P flexible cable *1

★ PCF8591 ADC module *1

★ PS2 control lever module *1

★ dual color LED module *1

★ bread board *1

★ several jumpers

3, Experimental principle

   the module has two analog outputs (corresponding to x and y coordinates) and one digital output, indicating whether to press on the Z axis.
   in this experiment, we connect pins VRx and VRy to the analog input port of the A/D converter to convert analog quantities to digital quantities. The raspberry pie is then programmed to detect the direction of movement of the joystick.

   for the two axis key rocker controller used in the experiment, the cross rocker is a two-way 10K resistor, and the resistance value of the tap changes with the direction of the rocker. This module uses 5V power supply. In the original state, the readout voltage of X and Y is about 2.5V. When it is pressed in the direction of the arrow, the readout voltage increases to 5V at most; Press the arrow in the opposite direction, and the readout voltage value will decrease to a minimum of 0V, that is, the module has two analog outputs and one digital output interface, and the output values correspond to the (x, y) biaxial offset respectively, and the type is analog; The key indicates whether the user is ž Press on the axis, the type is numeric. The switch coordinate identifier is clear, concise and accurate; It can easily control the movement of objects (such as 2-DOF servo pan tilt) in two-dimensional space.

4, Experimental steps

   step 1: connect the circuit.

Raspberry pie T-type adapter plate PCF8591 module
PS2 joystick module T-type adapter plate PCF8591 module
VRx * AIN1
VRy * AIN0
SW (button) * AIN2

   step 2: the PCF8591 module uses the I2C (IIC) bus for communication, but it is off by default in the raspberry pie image. When using the sensor, we must first allow the IIC bus communication.

   step 3: start programming. Here, write a pcf8591 Py library file, and then write a python program to introduce this library file.
  PCF8591 Py library file is the program of PCF8591 module. It is written separately to facilitate reuse. In this script, we use an amplifier for analog input and an LED lamp for analog output. The analog input cannot exceed 3.3V!
   the program can also be run separately to test the functions of three resistance modules. Connect AIN0 and INPUT0 (potentiometer module), AIN1 and INPUT1 (photoresistor module), and AIN2 and INPUT2 (thermistor module) with a short-circuit cap.
   connect the LED lamp, the AIN0 (analog input 0) port is used to receive the analog signal from the potentiometer module, and the AOUT (analog output) is used to output the analog signal to the two-color LED module, so as to change the brightness of the LED.
  for details of PCF8591, please see Raspberry pie basic experiment 12: PCF8591 analog-to-digital converter experiment.

#!/usr/bin/env python
#		You can import this script into another script using the following statement:
#	        "import PCF8591 as ADC"                
#	ADC.Setup(Address)  # Query the address of PCF8591: "sudo i2cdetect -y 1"
# i2cdetect  is  a  userspace  program to scan an I2C bus for devices.
# It outputs a table with the list of detected devices on the specified bus.
#	ADC.read(channal)	# Channel ranges from 0 to 3 
#	ADC.write(Value)	# Value ranges from 0 to 255
#SMBus (System Management Bus) 
import smbus   #Importing the "smbus" module into the program
import time

# for RPI version 1, use "bus = smbus.SMBus(1)"
# 0 stands for /dev/i2c-0, and 1 stands for /dev/i2c-1. It depends on the I2C used for raspberry pie
bus = smbus.SMBus(1)         #Create an smbus instance

#Query the address of PCF8591 on raspberry Pie: "sudo i2cdetect -y 1"
def setup(Addr):
	global address
	address = Addr

def read(chn): #channel
	if chn == 0:
		bus.write_byte(address,0x40)   #Send a control byte to the device
	if chn == 1:
	if chn == 2:
	if chn == 3:
	bus.read_byte(address)         # Reads a single byte from a device without specifying a device register.
	return bus.read_byte(address)  #Returns the A/D converted digital value of the analog value of a channel input

def write(val):
	temp = val  # Move string value to temp
	temp = int(temp) # Change string to integer type
	# print temp to see on terminal else comment out
	bus.write_byte_data(address, 0x40, temp) 
    #Write byte data, convert digital value to analog value and output from AOUT

if __name__ == "__main__":
 #Use the command "sudo i2cdetect -y 1" on the raspberry pie terminal to query that the address of PCF8591 is 0x48
	while True:
		print 'Potentiometer   AIN0 = ', read(0)   #Digital value of potentiometer analog signal conversion
		print 'Photoresistor AIN1 = ', read(1)   #Digital conversion of analog signal of photoresistor
        print 'Thermistor AIN2 = ', read(2)   #Digital value of analog signal conversion of thermistor
		tmp = read(0)
		tmp = tmp*(255-125)/255+125 
# The LED below 125 will not be on, so "0-255" will be converted to "125-255", and the lamp will not go out when the brightness is adjusted

   if you want to further study analog / digital conversion and other analog electrical knowledge, the following books are highly recommended. The most classic analog electrical tutorials in foreign universities are more vivid, interesting and easy to understand than those in China. Scan the code to buy or click the link below.

Basics of analog electronics Click to buy: https://u.dangdang.com/OIVk

   step 4: write PS2 joystick control program. Push the rocker upward, and a "up" message will be printed on the screen; Push down and print "down". If you push to the left, "left" will be printed; If you push to the right, it will print "right". If the cover is pressed, "Button Pressed" will be printed on the screen.

#!/usr/bin/env python
import PCF8591 as ADC 
import time

def setup():
	ADC.setup(0x48)					# Setup PCF8591
	global state

def direction():  	#Get joystick direction results
	state = ['home', 'up', 'down', 'left', 'right', 'Button pressed']
	i = 0

	if ADC.read(0) <= 5:
		i = 1		#up
	if ADC.read(0) >= 250:
		i = 2		#down

	if ADC.read(1) <= 5:
		i = 3		#left
	if ADC.read(1) >= 250:
		i = 4		#right

	if ADC.read(1) >= 6 \  #For unknown reasons, shaking the joystick to the left will automatically trigger the key press signal
    and ADC.read(2) == 0:  #So add adc Read (1) >= 6,
		i = 5		# Button pressed

	if  ADC.read(0) - 125 < 15   \
    and ADC.read(0) - 125 > -15	 \
    and ADC.read(1) - 125 < 15   \
    and ADC.read(1) - 125 > -15  \
    and ADC.read(2) == 255:
		i = 0         #home
	return state[i]

def loop():
	status = ''
	while True:
		tmp = direction()
		if tmp != None and tmp != status:
			print tmp     #Print when not empty and tmp value changes
			status = tmp

def destroy():
	pass      #The pass statement is an empty statement

if __name__ == '__main__':		# Program start from here
	except KeyboardInterrupt:  	# When 'Ctrl+C' is pressed, the child program destroy() will be  executed.


Tags: IoT Sensor

Posted by ShaKeD on Mon, 30 May 2022 20:21:12 +0530