Menu Close

robotics™ club™ thing

This week, we’ll be making our robot avoid obstacles (or human hands)! The robot may be going in circles if you just let it go in a place without obstacles, that is due to differences between the two sides of the robot.

open last week’s program:

Python
from machine import Pin
import utime

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

def ultra():
   trigger.low()
   utime.sleep_us(2)
   trigger.high()
   utime.sleep_us(5)
   trigger.off()
   while echo.value() == 0:
       signaloff = utime.ticks_us()
   while echo.value() == 1:
       signalon = utime.ticks_us()   
   timepassed = signalon - signaloff
   distance = (timepassed * 0.0343) / 2
   return(distance)
while True:
    ultra() 
    print(ultra())
    utime.sleep(0.1)



select file>save as and save your file as something else (if you name it drive, utime, time, or machine it won’t work !)

add “, drive” to line 2:

Python
from machine import Pin
import utime, drive

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

def ultra():
   trigger.low()
   utime.sleep_us(2)
   trigger.high()
   utime.sleep_us(5)
   trigger.off()
   while echo.value() == 0:
       signaloff = utime.ticks_us()
   while echo.value() == 1:
       signalon = utime.ticks_us()   
   timepassed = signalon - signaloff
   distance = (timepassed * 0.0343) / 2
   return(distance)
while True:
    ultra() 
    print(ultra())
    utime.sleep(0.1)



Then, remove everything after while True:

Python
from machine import Pin
import utime

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

def ultra():
   trigger.low()
   utime.sleep_us(2)
   trigger.high()
   utime.sleep_us(5)
   trigger.off()
   while echo.value() == 0:
       signaloff = utime.ticks_us()
   while echo.value() == 1:
       signalon = utime.ticks_us()   
   timepassed = signalon - signaloff
   distance = (timepassed * 0.0343) / 2
   return(distance)
while True:



And then add the following to the end (dont forget the indent):

Python
    dist = ultra()
    if dist < 21:
        drive.leftslow(15, 2)
    else:
        drive.forward(10)