I was debugging my inductive proximity sensor code because the counter registers more revolutions than expected.
My device is a Wemos D1 mini with the latest Micropython on it: "esp8266-20210418-v1.15", and the sensor is the DFRobot FIT0658, connected via a 4N35 optocoupler.
I read that it is very wise to disable the irq at entry of the callback function saving its state and enabling it after finishing with the saved state.
But somehow it still registers multiple callbacks with just one pass over the sensor.
Below my code (please don't mind all the 'uart' stuff, that is inthere for debugging and will be removed afterwards):
Code: Select all
class ProxSensor():
pin = Pin(13, Pin.IN) # D7 = GPIO13 on Wemos D1 mini
counter = 0
state = 0
uart = None
def __init__(self, uart):
"""Initialize the class."""
self.uart = uart
self.uart.write('\n\ninit\n')
self.pin.irq(trigger=Pin.IRQ_FALLING, handler=self.callback)
def callback(self, pin):
"""The IRQ trigger callback function for input 'pin'."""
self.state = machine.disable_irq()
self.uart.write('IRQ callback\n')
self.uart.write('state: %s\n' % self.state)
# debounce wait
time.sleep_ms(50)
# wait for the pin to rise again
while True:
debounce = 0
for i in range(20):
pin_state = self.pin.value()
self.uart.write(str(pin_state)+'\n')
debounce = debounce + pin_state
time.sleep_ms(10)
self.uart.write('D: ' + str(debounce)+'\n\n')
if debounce > 15:
self.uart.write('-!-\n\n')
break
# increment the counter
self.counter += 1
machine.enable_irq(self.state)
Code: Select all
IRQ callback
state: 32
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
D: 0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1
1
D: 4
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
D: 20
-!-
IRQ callback
state: 32
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
D: 20
-!-
Why is the callback function called multiple times, even when the 'disbale_irq' is the first line in the callback function?
I tried enabling the pull-up resistor on the pin but didn't show a difference. I also tried passing a 0, 1, or nothing into the 'enable_irq()'. But most of the time this causes a reset of the device.
Best regards,
lvx