Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 7333

MicroPython • MicroPython Interrupt response time, schedule()

$
0
0
Hi & thanks in advance for any pointers. I am not an experienced MicroPython programmer, but was cooking along great until I came upon the following problem: interrupts appears to be queued and it's killing me. The project is a simple closed loop motor controller with an optical encoder that produces interrupts at a maximum rate of about 1,000x/sec. Closing the motor control loop with a PID loop execution rate of 10x/sec results in chaos. During one PID loop there are no optical events and in the next loop all of the events have piled up. I am troubleshooting with an oscilloscope by triggering on the optical encoder signal on channel 1 and expecting to see the the isr response on the second scope channel 2 delayed by a couple of microseconds. Instead the isr appears unrelated (unsynchronized) to the encoder signal. Apparently all of the encoder signals are eventually serviced by the isr because averaging over a long term, the loop settles on the correct value.

I have consolidated the code below using a function generator to simulate the encoder. The result is usually an isr repsonse in about 50 uS, but sometimes delayed a millisecond. I have included "schedule()" , but it seems to have no discernable effect.

Code:

from micropython import schedulefrom machine import Pin, PWM, Timerfrom time import sleepSCOPE_PIN= 1ENCDR_A_PIN = 0# optical encoder 50 slotsSPD_PID_PERIOD= 100.0# speed PID loop execution in millisecsLED_PERIOD= 100# blink period on off periodFWD= TrueREV  = Falsemtr_a_ticks= 0scope = Pin(SCOPE_PIN, mode=Pin.OUT)encoder_a = Pin(ENCDR_A_PIN, Pin.IN, Pin.PULL_UP)led = Pin("LED", Pin.OUT)# LED pindef toggle_led(timer):# Callback function for the timer    led.value(not led.value())  # Toggle the LED state (ON/OFF)def count_mtr_a_dist(pin):    global mtr_a_ticks    scope.on()    mtr_a_ticks = mtr_a_ticks + 1    scope.off()#mtr_a_loop_timer = Timer(mode=Timer.PERIODIC, period=int(SPD_PID_PERIOD), callback=control_mtr_a_spd) # software timerled_toggle_timer  = Timer(mode=Timer.PERIODIC, period=LED_PERIOD, callback=toggle_led) # software timerencoder_a.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=count_mtr_a_dist) # int on changeschedule(count_mtr_a_dist,0)while True:    sleep(1)    print("tiks:", mtr_a_ticks)    mtr_a_ticks = 0

Statistics: Posted by stevensarns — Tue Jul 01, 2025 6:31 pm — Replies 1 — Views 78



Viewing all articles
Browse latest Browse all 7333

Trending Articles