-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathldr_button.py
81 lines (59 loc) · 2.27 KB
/
ldr_button.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
72
73
74
75
76
77
78
79
80
81
# -*- coding: utf-8 -*-
import terrariumLogging
logger = terrariumLogging.logging.getLogger(__name__)
import RPi.GPIO as GPIO
from gevent import sleep
import threading
from . import terrariumButton
class terrariumLDRSensor(terrariumButton):
HARDWARE = "ldr"
NAME = "Light sensor"
__CAPACITOR = 1 # in uF
def __run(self):
self._checker["running"] = 1
while self._checker["running"]:
count = 0
# Output on the pin for
GPIO.setup(self._device["device"], GPIO.OUT)
GPIO.output(self._device["device"], False)
sleep(0.1)
# Change the pin back to input
GPIO.setup(self._device["device"], GPIO.IN)
# Count until the pin goes high
# We found out that a value of capacitor value * 10000 is pretty correct for detecting if there is light
try:
while (
self._checker["running"]
and count <= (self.__CAPACITOR * 10000) + 1
and GPIO.input(self._device["device"]) == 0
):
count += 1
self._device["internal_state"] = self.PRESSED if count <= (self.__CAPACITOR * 10000) else self.RELEASED
sleep(0.1)
except KeyboardInterrupt:
self.stop()
# print(f"Fetch CTRL-c... and now what..? For now.. press again Ctrl-C .. ({ex})")
def _get_state(self):
return self._device["internal_state"]
def _load_hardware(self):
self._device["internal_state"] = self.RELEASED
self.__thread = threading.Thread(target=self.__run)
self.__thread.start()
# For the first reading, wait a bit....
sleep(0.25)
def calibrate(self, calibration_data):
super().calibrate(calibration_data)
self.__CAPACITOR = int(calibration_data.get("ldr_capacitor", self.__CAPACITOR))
def stop(self):
self._checker["running"] = 0
try:
self.__thread.join()
except Exception as ex:
logger.debug(f"Could not join thread to wait for: {ex}")
super().stop()
@property
def is_light(self):
return self.pressed
@property
def is_dark(self):
return not self.is_light