Python Forum
Sonar Code in Thonny for Pi Pico
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sonar Code in Thonny for Pi Pico
#1
Question 
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)
buran write Nov-22-2023, 08:47 AM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#2
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.
iansmiler likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  hardware timer raspberry pico trix 4 307 Jun-27-2024, 09:29 AM
Last Post: Larz60+
  raspberry pico second core ? trix 3 201 Jun-24-2024, 04:11 PM
Last Post: trix
  Minimal python install for thonny ide DanielRossinsky 0 1,582 Jun-11-2020, 02:31 PM
Last Post: DanielRossinsky
  Does "import xlrd" work in Thonny? cnutakor 3 3,160 Apr-30-2020, 12:41 AM
Last Post: Larz60+
  Values into system calls (RPi 4 Raspbian Buster Thonny) hitsware 1 2,400 Aug-27-2019, 07:29 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020