Hello everyone, let’s implement algorithms to falling and rising edge input detector with microPython. They are used to detect when a button or signal went for high to low and vice versa.
As the hardware we will be using a Raspberry Pi Pico programmed with microPython. There will be a single button and LED in hardware side.
The theory is illustrated in the picture above. We are interested in knowing when the signal goes from high to low (in this case from 3.3V to 0V) or low to high (in this case from 0V to 3.3V).
This code is written in microPython but the idea serves well for any microcontroller, really. Every 10ms I registed the current state of the input.
An if() conditional verifies wether the state of 10ms ago is equal, bigger or smaller (in voltage) than the current one. If it is equal the code does nothing, just feeds the current state in the “old state” variable.
The code below is for the rising edge.
from machine import Pin
import time
onboard = machine.Pin(25, machine.Pin.OUT)
button = Pin(19, Pin.IN, Pin.PULL_DOWN)
oldTime = 0
currentTime = 0
onboard.off()
previousState = False
while True:
currentTime = time.ticks_us()
if(currentTime - oldTime > 10000):
if(button.value()):
if(previousState == False):
onboard.toggle()
previousState = True
else:
pass
else:
pass
previousState = False
And a video of the system working. Notice that the onboard LED light as soon as I press the button.
Now the opposite, I am detecting the falling edge. The code is below.
from machine import Pin
import time
led = machine.Pin(18, machine.Pin.OUT)
button = Pin(19, Pin.IN, Pin.PULL_DOWN)
oldTime = 0
currentTime = 0
led.off()
previousState = False
while True:
currentTime = time.ticks_us()
if(currentTime - oldTime > 10000):
if(not button.value()):
if(previousState == True):
led.toggle()
previousState = False
else:
pass
else:
pass
previousState = True
Notice in the video below that the LED changes state only when I release the button.
Note that if you want to use this code to other cases than toggling an LED, you may insert your code in the place of
led.toggle()
That is where the magic happens.
There are applications where you need either of the techniques, for example in those TV shows that you have to press a button to answer some question. The edge detected is the rising one, which happens as soon as you press the button.
Here is a bit more theory on the subject. Do not know how to start with Raspberry Pi and microPython? check here.
Leave a Reply