Unlock exclusive access to high-quality Engineering, Maths, Physics, and Chemistry past papers, guides, and tutorials.
Hover to preview our restricted resource categories.
Mechanics, Thermodynamics...
Calculus, Algebra, Stats...
Quantum, Electromagnetism...
Organic, Inorganic...
Access our comprehensive revision guides and study materials for Level 2 Engineering.
Get a taste of our premium Engineering & Robotics content.
Learn how to program a basic robot to detect and avoid obstacles using ultrasonic sensors in Python.
import RPi.GPIO as GPIO
import time
# Define GPIO pins
TRIG = 23
ECHO = 24
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
def get_distance():
# Send a 10us pulse to trigger
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
# Wait for echo
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
# Calculate distance in cm
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
return round(distance, 2)
A conceptual block-based approach to programming a robot to follow a black line using two colour sensors.