RP2040 Blink Continued

2 minute read

Where I use the Labrador to test a different way of implementing Blink on the RP2040 using timer().

Sources

Background

I started reading the Python SDK above and noticed this example on page 12.

Its a method of blinking the LED in the background, which allows the processor to do other work. Let’s try it and see how well it works using the Labrador.

Code

from machine import Pin, Timer

led = Pin(13, Pin.OUT)
tim = Timer()
def tick(timer):
    global led
    led.toggle()

tim.init(freq=50, mode=Timer.PERIODIC, callback=tick)
Labrador app showing Blink using Timer

Labrador app showing Blink using Timer

Serial app showing Blink using Timer

Serial app showing Blink using Timer

Nice! Note the frequency is 2.5Hz, as we are getting a toggle at every tick. The width of the tick 200ms (5Hz requested). As you can see in the serial monitor we get the prompt back as compared to losing the terminal.

Wait, there’s more! Take a look at the next couple of steps. You can end the blinking by tim.init(), in other words, empty the parameters for tim.init. And you can simply change the frequency by changing the tim.init() parameters! I change the freq=50 and saw the corresponding change on the Labrador screen.

The point is that this allows you to quickly test the changes in parameters or commands and understand the impact. Yes, an LED will blink faster, however, its really difficult to measure.

After more testing, it appears that frequency can’t exceed about 11-15kHz or 70-90msecs. Whether freq=15000 or freq=20000, the image was similar:

Labrador app showing Blink using Timer at Max Frequency

Labrador app showing Blink using Timer at Max Frequency

Multiple Pins

Multiple pins mean multiple threads so our new program looks like this:

# blink 2 pins using Timer, which allows for multi-tasking
from machine import Pin, Timer


led = Pin(13, Pin.OUT)
p12 = Pin(12, Pin.OUT)
tim1 = Timer()
tim2 = Timer()


def tick1(timer):
    global led
    led.toggle()


def tick2(timer):
    global p12
    p12.toggle()


tim1.init(freq=500, mode=Timer.PERIODIC, callback=tick1)
tim2.init(freq=333, mode=Timer.PERIODIC, callback=tick2)

Very nice! Two pins at different frequencies! The cursor is measuring CH2 at 333Hz for the pulse (not the period) and measuring CH1 shows it at 500Hz.

Labrador app showing Blink using Timer at Multiple Frequencies

Labrador app showing Blink using Timer at Multiple Frequencies

Comments powered by Talkyard.