Python Forum

Full Version: Sonar Code in Thonny for Pi Pico
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello - I have written the code below which works well with my hardware. I want to use the 'distance' variable that I have set in 'def Ultra', outside of the 'def Ultra' routine. Right now, the code indicates when my robot is too near to an object - I want to use this indication to expand my program, putting my motors into slow and super slow speeds.

Any help will be greatly appreciated Cool

from machine import Pin
import utime

# Set up Ultrasonic Trigger and Echo
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)

# Set up the LED pins
red = Pin(20, Pin.OUT)
amber = Pin(19, Pin.OUT)
green = Pin(18, Pin.OUT)

def ultra():
   trigger.low()
   utime.sleep_us(2)
   trigger.high()
   utime.sleep_us(5)
   trigger.low()
   while echo.value() == 0:
       signaloff = utime.ticks_us()
   while echo.value() == 1:
       signalon = utime.ticks_us()
   timepassed = signalon - signaloff
   distance = (timepassed * 0.0343) / 2
   if distance <= 10: # If reading is less than or equal to 20
         
        red.value(1) # Red ON
        amber.value(0)
        green.value(0)
   elif 10 < distance < 20: # If reading is between 20 and 40
    
        red.value(0) 
        amber.value(1) # Amber ON
        green.value(0)
   elif distance >= 20: # If reading is greater than or equal to 40
            
        red.value(0) 
        amber.value(0)
        green.value(1) # Green ON
        
   print("The distance from object is ",distance,"cm")
   
while True:
   ultra()
   utime.sleep(1)
At the end of the ultra() function add:
return distance
When calling the function:
distance = ultra()
This will make the distance available as a global variable in the module.