How is an event callback coded

Questions and discussion about running MicroPython on a micro:bit board.
Target audience: MicroPython users with a micro:bit.
Posts: 1
Joined: Mon Sep 04, 2017 10:52 am

How is an event callback coded

Postby cup » Mon Sep 04, 2017 11:36 am

I previously asked this question on Stackoverflow. 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 [b]input.onPinPressed[/b] 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()

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?

User avatar
Posts: 1149
Joined: Thu May 28, 2015 5:54 pm

Re: How is an event callback coded

Postby deshipu » Mon Sep 04, 2017 7:30 pm

As far as I know, there is no way to attach interrupts to pins in MicroPython on the micro:bit. I suppose nobody thought such an advanced feature would be needed.

Site Admin
Posts: 534
Joined: Mon Dec 09, 2013 5:02 pm

Re: How is an event callback coded

Postby Damien » Tue Sep 05, 2017 4:43 am

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.

Return to “The micro:bit”

Who is online

Users browsing this forum: No registered users and 1 guest