-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcar_interface.py
More file actions
executable file
·91 lines (67 loc) · 2.02 KB
/
car_interface.py
File metadata and controls
executable file
·91 lines (67 loc) · 2.02 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
import threading
import timer
import atexit
HEADLIGHT_OUT_PIN = 11
SWITCH_PIN = 13
HEADLIGHT_IN_PIN = 15
class CarInterface():
def __init__(self):
self.loopThread = threading.Thread(target=self.loop)
self.loopThread.daemon = True
self.highbeam_out = False
self.highbeam_in = False
self.switch = False
self.shutdown = False
def __enter__(self):
#set mode to board which means use the pysical pin numbering
GPIO.setmode(GPIO.BOARD)
#highbeam output. 1 turn on high beams
GPIO.setup(HEADLIGHT_OUT_PIN,GPIO.OUT)
# switch state
GPIO.setup(SWITCH_PIN,GPIO.IN, pull_up_down=GPIO.PUD_UP)
# high beam state. 0 high beams on. 1 high beams off
GPIO.setup(HEADLIGHT_IN_PIN,GPIO.IN, pull_up_down=GPIO.PUD_UP)
self.loopThread.start()
return self
def getHighbeamInput(self):
return self.highbeam_in
def getSwitchInput(self):
return self.switch
def getShutdownInput(self):
return self.shutdown
def setHighbeamOutput(self,state):
self.highbeam_out = state
def loop(self):
shutdown_toggle_count = 0
last_switch = False
shutdown_count_timer = timer.Timer()
while True:
#read and write to IO
try:
GPIO.output(HEADLIGHT_OUT_PIN,self.highbeam_out)
self.switch = GPIO.input(SWITCH_PIN)
self.highbeam_in = not GPIO.input(HEADLIGHT_IN_PIN)
except Exception as e:
print(e)
#If the switch is toggled multiple times in a short period
#turn on the shutdown output
if self.switch != last_switch:
last_switch = self.switch
shutdown_count_timer.reset()
shutdown_toggle_count += 1
if shutdown_count_timer() > 1.0:
shutdown_toggle_count = 0
self.shutdown = shutdown_toggle_count > 6
#loop at about 30 hz
time.sleep(0.03)
def __exit__(self,*args):
GPIO.cleanup()
print("Clean Up")
if __name__ == "__main__":
with CarInterface() as car:
while True:
time.sleep(0.1)
print("headlight in: %i, switch: %i, shutdown %i" % (car.getHighbeamInput(), car.getSwitchInput(), car.getShutdownInput()))