-1

I am trying to read distance using Raspberry Pi Pico and ultrasonic distance sensor. While running the code in Thonny, I am getting the error,

TypeError: function missing 1 required positional arguments

The code is as below:

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)
  • 1
    If you read the error message it tells you that your missing an argument in a function. When you call get_distance() you should probably be passing timer like this: get_distance(timer). – JoshieWahWah Apr 11 '21 at 22:54

2 Answers2

0

Your initial problem is that you aren't using timer as an argument to your get_distance call, but you have bigger problems than that. You are using a timer to call get_distance but you are also calling get_distance in a loop. To top it off you have 2 blocking while loops in your get_distance function. Who knows how long the value of echo will stay 1 or 0. Will it stay one of those values longer than the next invocation from Timer? If so, you are going to have big problems. What you want to do is send periodic pulses to the pin to check the values. This can be done as below. This code isn't tested (although, it probably works). It is at least a solid gist of the direction you should be moving toward.

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)

Parts of this code were borrowed from here and reformatted to fit your design. I was too lazy to figure out how to effectively get rid of your while loops so, I just let the internet give me that answer (machine.time_pulse_us(echo, 1, 50000)).

OneMadGypsy
  • 4,640
  • 3
  • 10
  • 26
0

Many of the ultrasonic units, such as the SRF04 nominally operate at 5V, so you could have problems if that's what you are using.

The v53l0x is a laser-based time-of flight device. It only works over short ranges (about a metre or so, but it definitely works with 3.3 V on a Pico with micropython and Thonny

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