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
[code]
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)
}
})
[/code]
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()
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?
How is an event callback coded
Re: How is an event callback coded
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.
Re: How is an event callback coded
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.