Page 1 of 1

How to use the TIMER in the PYBOARD

Posted: Thu Dec 24, 2020 9:36 pm
by toor64
Hello and sorry for my english.

I'm trying to know more about using the TIMER in Pyboard if you can help me. I want to turn on and off a led connected to pin X3 with a TIMER set at 5hz.
I wrote this code and this works ,

Code: Select all

import pyb
from pyb import Pin

led=Pin("X3", Pin.OUT)

tim = pyb.Timer(4)
tim.init(freq=5)
tim.callback(lambda t:led.value(not led.value()))
but I don't understand 2 things:

(1) because the frequency that I set in tim.init (freq = 5) is not respected. The actual frequency measured with an oscilloscope is half of that set.

(2) because if I create a function to be launched, this is not executed.
For example :

Code: Select all

import pyb
from pyb import Pin

led=Pin("X3", Pin.OUT)

def toggle_led(led):
    stato_led = led.value()
    if stato_led == 0:
        led.on()
    else:
        led.off()

tim = pyb.Timer(4)
tim.init(freq=5)
tim.callback(toggle_led(led))

The TOGGLE_LED function simply turns the LED on and off but there is no cycle because the program stops immediately, as if the TIMER did not start its cycle.
Maybe because the TIMER callback can't allocate memory?

Thank you for your help and I wish you a Merry Christmas

Re: How to use the TIMER in the PYBOARD

Posted: Thu Dec 24, 2020 10:03 pm
by dhylands
You’re toggling the signal at 5 Hz . This means it takes 200 msec to turn on and 200 msec to turn off. Which men’s that the led is being pulsed once every 400 msec, or 2.5 Hz.

Re: How to use the TIMER in the PYBOARD

Posted: Thu Dec 24, 2020 11:18 pm
by toor64
damn, I'm just stupid :-) Thanks dhylands

Re: How to use the TIMER in the PYBOARD

Posted: Sat Jan 02, 2021 3:08 am
by jamonda
What about the second question? Why doesn't the toggle function work with callback()?

Re: How to use the TIMER in the PYBOARD

Posted: Sat Jan 02, 2021 5:29 am
by pythoncoder
Because of this line:

Code: Select all

tim.callback(toggle_led(led))
Python first runs

Code: Select all

toggle_led(led)
which runs once and returns None: this is standard Python behaviour. So the outer function runs with

Code: Select all

tim.callback(None)
which disables any callback. The correct syntax is

Code: Select all

tim.callback(toggle_led)
which means you must find another way to pass the LED object to the function. Options are to use a global or to make the function a bound method of a class, with the LED as a bound variable. The latter is preferred as being more object oriented. Note that timer callbacks receive one arg, which is the timer instance. You must specify this in the function definition, but typically it is unused in the function body.

Re: How to use the TIMER in the PYBOARD

Posted: Mon Jan 04, 2021 10:10 pm
by jamonda
Thank you, pythoncoder!