-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08_rotaryEncoder.py
executable file
·71 lines (61 loc) · 1.52 KB
/
08_rotaryEncoder.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
# Set up pins
# Rotary A Pin
RoAPin = 17
# Rotary B Pin
RoBPin = 18
# Rotary Switch Pin
RoSPin = 27
def setup():
global counter
global Last_RoB_Status, Current_RoB_Status
GPIO.setmode(GPIO.BCM)
GPIO.setup(RoAPin, GPIO.IN)
GPIO.setup(RoBPin, GPIO.IN)
GPIO.setup(RoSPin,GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Set up a falling edge detect to callback clear
GPIO.add_event_detect(RoSPin, GPIO.FALLING, callback=clear)
# Set up a counter as a global variable
counter = 0
Last_RoB_Status = 0
Current_RoB_Status = 0
# Define a function to deal with rotary encoder
def rotaryDeal():
global counter
global Last_RoB_Status, Current_RoB_Status
flag = 0
Last_RoB_Status = GPIO.input(RoBPin)
# When RoAPin level changes
while(not GPIO.input(RoAPin)):
Current_RoB_Status = GPIO.input(RoBPin)
flag = 1
if flag == 1:
# Reset flag
flag = 0
if (Last_RoB_Status == 0) and (Current_RoB_Status == 1):
counter = counter + 1
if (Last_RoB_Status == 1) and (Current_RoB_Status == 0):
counter = counter - 1
print ("counter = %d" % counter)
# Define a callback function on switch, to clean "counter"
def clear(ev=None):
global counter
counter = 0
print ("counter = %d" % counter)
def main():
while True:
rotaryDeal()
def destroy():
# Release resource
GPIO.cleanup()
# If run this script directly, do:
if __name__ == '__main__':
setup()
try:
main()
# When 'Ctrl+C' is pressed, the child program
# destroy() will be executed.
except KeyboardInterrupt:
destroy()