Skip to content
Snippets Groups Projects
Commit c705e504 authored by jhierck laptop's avatar jhierck laptop
Browse files

Started on speed sensor module, based on code provided by Joy-It (manufacturer of the sensor)

parent 3108263b
No related branches found
No related tags found
No related merge requests found
# import of libraries
import threading
from threading import Timer, Thread
import RPi.GPIO as GPIO
import time
import sys
from numpy import pi as PI
class SpeedSensor:
WHEEL_HOLES = 20
EDGES_PER_ROTATION = 2 * WHEEL_HOLES # We detect both rising and falling edges
def __init__(self, name, data_pin: int):
self.name = name
self.data_pin = data_pin
self.lock = threading.Lock()
self._count = 0
GPIO.setup(self.data_pin, GPIO.IN)
def start_measurement(self):
"""Start the measurement."""
GPIO.add_event_detect(self.data_pin, GPIO.BOTH, self._increment_counter)
def _increment_counter(self, channel) -> None:
with self.lock:
self._count += 1
def get_count(self) -> int:
"""Return the current encoder count."""
with self.lock:
return self._count
def reset_count(self):
"""Reset counter to zero."""
with self.lock:
self._count = 0
def get_angle(self) -> int:
"""Return the encoder angle in degrees."""
deg_per_hole = int(360 / self.EDGES_PER_ROTATION)
return deg_per_hole * self.get_count()
class ResetTimer(Thread):
def __init__(self, time, callback, daemon=False):
super().__init__(daemon=daemon)
self.time = time
self.callback = callback
self.timer = None
self.running = False
self.killed = False
self.set()
def set(self):
self.timer = Timer(self.time, self.callback)
def stop(self):
self.daemon = True
def run(self):
self.running = True
self.timer.start()
if self.daemon is True:
print("Exiting daemon ResetTimer.")
sys.exit(0)
def cancel(self):
self.running = False
self.timer.cancel()
def reset(self, auto_start: bool = False):
if self.running is True: # First cancel if still running
self.timer.cancel()
self.set()
if self.running is True or auto_start is True: # Start immediately if running before or argument is given
self.start()
def count(channel):
global counter
print("Detected.")
counter = counter + 1
def output():
global counter
timer.cancel()
speed = int(((counter / 2) * calc) / wheel)
print("RPM: %f" % speed)
counter = 0
timer.reset()
timer.run()
counter = 0
data_pin = 4
interval = 5.0
calc = 60 / int(interval)
wheel = 20
if __name__ == '__main__':
GPIO.setmode(GPIO.BCM)
GPIO.setup(data_pin, GPIO.IN)
timer = ResetTimer(interval, output)
try:
GPIO.add_event_detect(data_pin, GPIO.FALLING, count)
timer.start()
while True:
time.sleep(1)
except KeyboardInterrupt:
timer.stop()
timer.join()
finally:
GPIO.cleanup()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment