forked from T-Kuhn/StepperRobotArm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
switch.py
54 lines (46 loc) · 1.69 KB
/
switch.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
#!/usr/bin/python3
import os
import time
import RPi.GPIO as GPIO
"""
A class for the use of mechanical switches connected to the Raspberry Pi.
Switches need to be pulled down (via external pull down resistor or
by using the pull down functionality of the microcontroller).
This class provides:
- software debounce (no chattering)
- execution of different functions on ON / OFF
"""
# - - - - - - - - - - - - - - - -
# - - - - SWITCH CLASS - - - - -
# - - - - - - - - - - - - - - - -
class Switch:
def __init__(self, pin, switchOnFun, switchOffFun):
self.pin = pin
self.switchOnFun = switchOnFun
self.switchOffFun = switchOffFun
self.isOn = False
self.lastHighTime = 0
self.SwitchOffTime = 100 # switch turns off after input was low for at least x ms
def update(self):
switchStatus = GPIO.input(self.pin)
if switchStatus and not self.isOn:
# Trigger on positive flank of Input Signal
self.isOn = True
self.switchOn()
elif not switchStatus and self.isOn:
# We get in here when the switch gets switched off
if self.lastHighTime + self.SwitchOffTime < self.getTimeStamp():
self.isOn = False
self.switchOff()
elif switchStatus and self.isOn:
# Reset last hight Time
self.lastHighTime = self.getTimeStamp()
def getTimeStamp(self):
# returns the current TimeStamp in millisecs
return int(time.time()*1000)
def switchOn(self):
print("pin {0} ON".format(self.pin))
self.switchOnFun()
def switchOff(self):
print("pin {0} OFF".format(self.pin))
self.switchOffFun()