-1

我正在尝试使用 Raspberry Pi Pico 和超声波距离传感器读取距离。在 Thonny 中运行代码时,出现错误,

TypeError: function missing 1 required positional arguments

代码如下:

from machine import Pin, Timer
import utime

timer = Timer
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
distance = 0

def get_distance(timer):
  global distance
  trigger.high()
  utime.sleep(0.00001)
  trigger.low()

  while echo.value() == 0:
    start = utime.ticks_us()
  while echo.value() == 1:
    stop = utime.ticks_us()
  timepassed = stop - start
  distance = (timepassed * 0.0343) / 2
  print("The distance from object is ",distance,"cm")
  return distance
timer.init(freq=1, mode=Timer.PERIODIC, callback=get_distance)
while True:
 get_distance()
 utime.sleep(1)
4

2 回答 2

0

您最初的问题是您没有将timer其用作get_distance调用的参数,但是您遇到的问题比这更大。您正在使用计时器进行调用get_distance,但您也在get_distance循环调用。最重要的是,您的函数中有 2 个阻塞while循环。get_distance谁知道 的值echo会保持 1 或 0 多长时间。它会比下一次调用 from 更长时间地保持这些值之一Timer吗?如果是这样,您将遇到很大的问题。您要做的是向引脚发送周期性脉冲以检查值。这可以如下完成。此代码未经测试(尽管它可能有效)。这至少是你应该朝着的方向的一个坚实的要点。

import machine, utime

trigger = machine.Pin(3, machine.Pin.OUT)
echo    = machine.Pin(2, machine.Pin.IN)

def get_distance(timer):
    global echo, trigger #you probably don't need this line

    trigger.value(0)
    utime.sleep_us(5)
    trigger.value(1)
    utime.sleep_us(10)
    trigger.value(0)
    
    pt = machine.time_pulse_us(echo, 1, 50000)
    print("The distance from object is {} cm".format((pt/2)/29.1))


timer = machine.Timer(-1)
timer.init(mode=machine.Timer.PERIODIC, period=500, callback=get_distance)

这段代码的一部分是从这里借来的,并重新格式化以适合您的设计。我懒得弄清楚如何有效地摆脱你的while循环,所以我只是让互联网给我答案(machine.time_pulse_us(echo, 1, 50000))。

于 2021-04-12T06:27:53.813 回答
0

许多超声波装置,例如 SRF04 标称工作电压为 5V,因此如果您使用的是这种装置,您可能会遇到问题。

v53l0x 是一种基于激光的飞行时间设备。它只适用于短距离(大约一米左右,但它绝对适用于带有 micropython 和 Thonny 的 Pico 上的 3.3 V

https://www.youtube.com/watch?v=YBu6GKnN4lk https://github.com/kevinmcaleer/vl53l0x

于 2021-04-13T22:32:08.887 回答