Created
November 30, 2024 20:04
-
-
Save jonnor/fc1442a71a79115987ef0c6121f17b5c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import machine | |
from machine import Pin | |
class PinInterruptCounter(): | |
"""Implementation of machine.Counter using standard pin interrupts""" | |
def __init__(self, pin, edge=Pin.IRQ_RISING, callback=None): | |
self._count = 0 | |
self._pin = pin | |
self._callback = callback | |
# Setup interrupt handler | |
self._pin.irq(trigger=edge, handler=self._handle_interrupt) | |
def _handle_interrupt(self, pin): | |
self._count += 1 | |
if self._callback: | |
self._callback(self) | |
def reset(self): | |
irq_state = machine.disable_irq() # Start critical section | |
self._count = 0 | |
machine.enable_irq(irq_state) # End of critical section | |
def value(self): | |
irq_state = machine.disable_irq() # Start critical section | |
out = self._count | |
machine.enable_irq(irq_state) # End of critical section | |
return out | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import machine | |
import time | |
from counter import PinInterruptCounter | |
def on_tacho(c): | |
status_led.value(1) | |
status_led.value(0) | |
tacho_pin = machine.Pin(26, machine.Pin.IN, machine.Pin.PULL_UP) | |
tacho = PinInterruptCounter(pin=tacho_pin, callback=on_tacho) | |
status_led = machine.Pin(19, machine.Pin.OUT) | |
measure_time = 2000 # ms | |
start = time.ticks_ms() | |
print("start") | |
while True: | |
# measure speed | |
tacho.reset() | |
time.sleep_ms(measure_time) | |
count = tacho.value() | |
hz = count / (measure_time/1000.0) | |
t = time.ticks_ms() - start | |
print('rpm-measure', t, count, hz) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment