Using a timer with pyb/machine


I can use an interrupt timer with the ‘pyb’ library, but if I understand correctly, it would be obsolete.
I’ve tried to do the same thing with the ‘machine’ library, but I get a ‘Timer does not exist’ error message.
However, it works perfectly with a led and machine.Pin for example.

Could you clarify this for me or provide me with an example that’s supposed to work?

Best regards,


? class Timer – control hardware timers — MicroPython 1.20 documentation (

Yes, I’ve tried to use it but without success.

Here is the simple code that I used :

from machine import Pin, Timer

led = Pin('P7', Pin.OUT_PP)

def blink(timer) :

cadenceur = Timer(2)
#cadenceur.init(mode=Timer.PERIODIC, freq=2, callback=blink)


On launch, I get the error message “ValueError : Timer doesn’t exist”.
Image du presse-papiers (1)

Yeah, sorry, I need to improve that documentation. Only soft timers are supported in the machine module for all micropython boards:

from machine import Pin, Timer

led = Pin('P7', Pin.OUT)

def blink(timer) :

cadenceur = Timer(-1)
cadenceur.init(mode=Timer.PERIODIC, freq=2, callback=blink)


E.g. in the code base:

machine_timer_obj_t *self = m_new_obj(machine_timer_obj_t);
    self->pairheap.base.type = &machine_timer_type;
    self->delta_ms = 1000;
    self->py_callback = mp_const_none;

    // Get timer id (only soft timer (-1) supported at the moment)
    mp_int_t id = -1;
    if (n_args > 0) {
        id = mp_obj_get_int(args[0]);
    if (id != -1) {
        mp_raise_ValueError(MP_ERROR_TEXT("Timer doesn't exist"));

    if (n_args > 0 || n_kw > 0) {
        // Start the timer
        mp_map_t kw_args;
        mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
        machine_timer_init_helper(self, n_args, args, &kw_args);

    return MP_OBJ_FROM_PTR(self);

Anyway, the soft timer should be fine for what you want. That gets dispatched from a hardware timer that’s keeping the whole system time for _ms, _us, etc.

This is different from PYB where you were interfacing directly with hardware timers. In the machine module to make things more abstract this has changed. Hardware timers are still used to control PWM. But, it’s also abstracted so that you’re just asking for PWM versus a timer and all the modes to generate PWM.