As the title says... Chat on...

User avatar
By Michael Teeuw
#11860 Hi All! I've just discovered the beautiful ESP8266 and this forum. Loving it already!

I was doing some experiments with the GPIO interrupts, but I'm running into an issue. Maybe one of you can tell me I'm doing something wrong.

When I set an 'both'-interrupt on one of the GPIO pins, and I print out the value on the interrupt, most of the time I get a '1' back, even while I've just released the button:

Code: Select alllocal pin = 3

function onChange ()
    print('The pin value has changed to: '..gpio.read(pin))
end
 
gpio.mode(pin, gpio.INT)
gpio.trig(pin, 'both', onChange)

Result example:
The pin value has changed to: 1
The pin value has changed to: 1
The pin value has changed to: 0
The pin value has changed to: 1
The pin value has changed to: 1
The pin value has changed to: 1
The pin value has changed to: 1
The pin value has changed to: 0
The pin value has changed to: 1
The pin value has changed to: 1


It looks like the the state isn't correctly set your when the interrupt is called.

The problem is solved when I wait 50 milliseconds before I read out the value. So the following code works perfect:

Code: Select alllocal pin = 3

function onChange ()
    tmr.alarm(0,50,0,function()
        print('The pin value has changed to: '..gpio.read(pin))
    end)
end
 
gpio.mode(pin, gpio.INT)
gpio.trig(pin, 'both', onChange)

Result example:
The pin value has changed to: 1
The pin value has changed to: 0
The pin value has changed to: 1
The pin value has changed to: 0
The pin value has changed to: 1
The pin value has changed to: 0
The pin value has changed to: 1
The pin value has changed to: 0
The pin value has changed to: 1
The pin value has changed to: 0


For example sake, I left out a debouncing function. It gave the same results. Although example 2 doesn't need an debouncing function. The tmr.alarm makes this obsolete.

Question: Why do I get back wrong GPIO states when I read out the value in the interrupt function whit out a delay? What's the best way to solve this?

Thanks in advance.
User avatar
By dpwhittaker
#11894 Interrupts are generally very time-sensitive, so it may be calling the interrupt before the registers are set. A delay of even 1 ms would probably pick up the right value. However, an even better solution is to just put level as a parameter on your onChange callback, and print its value there.

Code: Select alllocal pin = 3

function onChange (level)
    print('The pin value has changed to: '..level)
end
 
gpio.mode(pin, gpio.INT)
gpio.trig(pin, 'both', onChange)