EasyManua.ls Logo

Freenove Ultimate Starter Kit - Page 139

Freenove Ultimate Starter Kit
286 pages
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
139
Chapter 12 Joystick
ā–ˆ www.freenove.com
support@freenove.com ā–ˆ
Python Code 12.1.1 Joystick
First observe the project result, and then analyze the code.
1. Use cd command to enter 12.1.1_Joystick directory of Python code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/Python_Code/12.1.1_ Joystick
2. Use python command to execute python code "Joystick.py".
python Joystick.py
After Program is executed, the terminal window will print out the data of 3 axes X, Y, Z. And shifting the
Joystick or pressing it will make those data change.
The following is the program code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
im port RPi. GPIO as GPIO
im port smbus
im port time
address = 0x48
bus=smbus.SMBus(1)
cmd=0x40
Z_Pin = 12 #define pin for Z_Pin
def analogRead(chn): #read ADC value
bus. write_byte(address,cmd+chn)
value = bus.read_byte(address)
value = bus.read_byte(address)
#value = bus.read_byte_data(address,cmd+chn)
r eturn value
def analogWrite(value):
bus. write_byte_data(address,cmd,value)
def setup():
GPIO. setmode(GPIO.BOARD)
GPIO. setup(Z_Pin,GPIO.IN,GPIO.PUD_UP) #set Z_Pin to pull-up mode
def loop():
w hile Tr ue:
val_Z = GPIO. input(Z_Pin) #read digital quality of axis Z
val_Y = analogRead(0) #read analog quality of axis X and Y
val_X = analogRead(1)
print ('value_X: %d ,\tvlue_Y: %d ,\tvalue_Z: %d'%(val_X,val_Y,val_Z))

Table of Contents