Are there event callbacks in BBC MicroPython?

389 views Asked by At

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.

2

There are 2 answers

0
cup On BEST ANSWER

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.

1
Oppy On

Event handling can be used with Python on the micro:bit with the online MakeCode editor now.

MakeCode editor

Open a work area. In the middle of the bar along the top of the work area you can select the environment that you want to work in. On the left is the option to work with Blocks. On the right you will probably see JavaScript with a drop down arrow next to it. Click on this arrow and select Python.

This is a separate implementation of Python from the MicroPython discussed in the original question. This MakeCode implementation has events.

Boilerplate code can be generated by either typing a stub and selecting from the drop down text that pops up or by selecting a function from the menu on the left and dragging it to the work area.

The boilerplate code for a button press is:

def on_pin_pressed_p0():
    pass
input.on_pin_pressed(TouchPin.P0, on_pin_pressed_p0)