# which edge?
# false = falling, true = rising
print("Hi!")
DETECT_STATE = False
# measurement time (in seconds)
MEASURE_TIME = 1
from machine import Pin, I2C, Timer
from utime import sleep
from math import pi
import ssd1306
rotations = 0
sensor = Pin(15,Pin.IN)
disp_i2c = I2C(1, sda=Pin(2), scl=Pin(3))
#print(disp_i2c.scan())
display = ssd1306.SSD1306_I2C(128, 64, disp_i2c)
def isr(p):
global rotations
rotations += 1
if DETECT_STATE:
sensor.irq(trigger=Pin.IRQ_RISING,handler=isr)
else:
sensor.irq(trigger=Pin.IRQ_FALLING,handler=isr)
def calcRpm(rotations: float, interval: float) -> float:
return (rotations / interval) * 60
def calcSpeed(rpm: float, diameter: float) -> float:
circumference = pi * diameter
meters_per_minute = circumference * rpm
meters_per_hour = meters_per_minute * 60
km_per_hour = meters_per_hour / 1000
return km_per_hour
def update(p):
global rotations
global display
rpm = calcRpm(rotations,MEASURE_TIME)
speed = calcSpeed(rpm,1)
#print(speed,'km/h')
display.fill(0)
display.text(f"{round(speed,2)} km/h", int(64*.3) , int((12*0) + (128*.2)))
display.text(f"{round(rpm,2)} rpm", int(64*.3), int((12*1) + (128*.2)))
display.show()
#print(rotations,rpm)
rotations = 0
timer = Timer(period = MEASURE_TIME *1000, mode = Timer.PERIODIC, callback = update)
while 1: sleep(9999)