micropythonbbc-microbit

Are there event callbacks in BBC MicroPython?


I am trying to translate the following from Javascript to MicroPython for the micro:bit. This is code example 3 from the inventor's kit translated from block to Javascript.

let light_state = 0
# how do you do this bit?
input.onPinPressed(TouchPin.P0, () => {
    if (light_state == 0) {
        light_state = 1
    } else {
        light_state = 0
    }
})
basic.forever(() => {
    if (light_state == 1) {
        pins.analogWritePin(AnalogPin.P2, pins.analogReadPin(AnalogPin.P1))
    } else {
        pins.digitalWritePin(DigitalPin.P2, 0)
    }
})

I can't figure out how to do the input.onPinPressed as a callback event or even a lambda. The best I can come up with is to poll pin0 repeatedly.

from microbit import *

light_on = False
while True:
    if pin0.is_touched():
        light_on = not light_on        
        if light_on:
            aval = pin1.read_analog()
            pin2.write_analog(aval)
        else:
            pin2.write_digital(0)

I have seen callbacks on switches in the MicroPython documentation but I haven't come across any event callbacks for the micro:bit pins. Is there any example code for this feature, even if it is undocumented?

Edit: I made corrections to the code - the previous MicroPython translation caused the LED to flicker continuously.


Solution

  • The reply from the micro:bit forum is

    The MicroPython micro:bit API was designed primarily for teaching and use by school children, and it was decided not to include callbacks in the API because they can lead to complicated bugs. Instead you will need to poll the pin.