Page 1 of 1

Why cant I escape this function?

Posted: Sat Dec 18, 2021 6:58 pm
by GEOFOR
This function is called from an interrupt on a rising edge of a toggle switch. When the function is called, it confirms it has been called by printing "accept".
It then waits for another input to go high for a few seconds (from a push button). If this happens, a traincoming led goes high.

The problem is that regardless of the state of the pushbutton, it constantly loops and I cant stop it. It should call the function, check if the pushbutton has been pushed in time, make sure it has been pushed for long enough and react either way and dont repeat until the toggle switch has another rising edge.

I am running this on a Pico.

Can anyone suggest why it is doing this?

Code: Select all

def acceptance(Pin):
    utime.sleep_ms(200)
    timeoutflag = 0
    print("accept")
    start = time.ticks_ms()
    while adjblockbell.value() == 0 and timeoutflag == 0:
        if time.ticks_diff(time.ticks_ms(), start) > 5500:
            print("TOO LONG")
            timeoutflag = 1
    if timeoutflag == 1:
        return

    else:
        start = time.ticks_ms()
        while adjblockbell.value() == 1 and commutator.value() ==1:
            if time.ticks_diff(time.ticks_ms(), start) > 4500:
                led_traincoming.high()
                led_normal.low()
    return
    
Moderator note: Added code tags

Re: Why cant I escape this function?

Posted: Sat Dec 18, 2021 8:01 pm
by nedkonz
Printing from an interrupt handler is problematic. Try removing your print statements or moving them to your main loop.

Re: Why cant I escape this function?

Posted: Sat Dec 18, 2021 9:18 pm
by Roberthh
Interrupt handler should be finished as fast as possible. Depending on the implementation, other interrupts are blocked as long as the handler is running. I did not check that in detail for the Pico, but it may be possible that the ticks_ms() timer is based on an interrupt and does not proceed as long as this interrupt is not finished.
So better use the interrupt handler just to set a flag, that it has happened.
@pythoncoder will anyhow recommend to use uasyncio for your task.

Re: Why cant I escape this function?

Posted: Sun Dec 19, 2021 10:45 am
by pythoncoder
Roberthh wrote:
Sat Dec 18, 2021 9:18 pm
...
@pythoncoder will anyhow recommend to use uasyncio for your task.
He will indeed ;) He'll also point the OP to this article on contact bounce. My
uasyncio tutorial shows how to interface switches and pushbuttons.