gpt4 book ai didi

micropython - BBC MicroPython 中是否有事件回调?

转载 作者:行者123 更新时间:2023-12-01 03:20:07 27 4
gpt4 key购买 nike

我正在尝试将以下内容从 Javascript 转换为 micro:bit 的 MicroPython。这是来自发明者工具包的代码示例 3,从块转换为 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)
}
})

我不知道怎么做 input.onPinPressed 作为回调事件甚至 lambda。我能想到的最好方法是反复轮询 pin0。
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)

我在 MicroPython 文档中看到过开关上的回调,但我没有遇到 micro:bit 引脚的任何事件回调。是否有此功能的示例代码,即使它没有记录?

编辑 :我对代码进行了更正 - 之前的 MicroPython 翻译导致 LED 持续闪烁。

最佳答案

The reply from the micro:bit forum

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.

关于micropython - BBC MicroPython 中是否有事件回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46016885/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com