Sonar Code in Thonny for Pi Pico - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Sonar Code in Thonny for Pi Pico (/thread-41171.html) |
Sonar Code in Thonny for Pi Pico - iansmiler - Nov-22-2023 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 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) RE: Sonar Code in Thonny for Pi Pico - deanhystad - Nov-22-2023 At the end of the ultra() function add: return distanceWhen calling the function: distance = ultra()This will make the distance available as a global variable in the module. |