问题描述
我想请你帮忙。我正在尝试将距离传感器连接到我的 microbit,但是当我使用命令“time_pulse_us”时,它总是给出 -2 或 -1。我阅读了文档,我了解这些数字的含义,但我认为该命令存在问题,或者我可能使用错误的方式。
在这方面,我写了一个简单的片段来测试命令。你能告诉我它有什么问题吗?
from microbit import * //to import microbit modules
from machine import * //to import the time_pulse_us command
while True:
pin1.write_digital(0)
time = time_pulse_us(pin2,1) //to begin the timing
pin1.write_digital(1) //this pin is connected to an LED
sleep(1000)
value = pin2.read_digital() //gives 1,as this pin is reading the voltage from the led
pin1.write_digital(0) //this will make the time_pulse command to end timing
display.scroll(time) //it should display the duration of the pulse.
//displays -2 instead.
display.scroll(value) //gives 1,as expected
为什么这不起作用?
解决方法
time_pulse_us()
顺序运行,而不是在后台运行,因此在调用时它会等待 1 秒让 pin 达到 1,但它不会这样做,因此 time
将设置为 -2,在程序继续执行下一个命令 write_digital(1)
之前。