This project guides students through building a simple robot that avoids obstacles using an ultrasonic sensor and two DC motors controlled by an L298N motor driver. The ESP32 microcontroller acts as the robot’s brain, detecting obstacles and adjusting movement accordingly.
from machine import Pin, PWM, time_pulse_us
from time import sleep
# Motor pins
in1 = Pin(26, Pin.OUT)
in2 = Pin(25, Pin.OUT)
in3 = Pin(33, Pin.OUT)
in4 = Pin(32, Pin.OUT)
ena = PWM(Pin(14), freq=1000)
enb = PWM(Pin(12), freq=1000)
# Ultrasonic sensor pins
trig = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)
# Movement functions
def stop():
in1.off(); in2.off(); in3.off(); in4.off()
ena.duty(0); enb.duty(0)
def forward(speed=800):
in1.on(); in2.off(); in3.on(); in4.off()
ena.duty(speed); enb.duty(speed)
def backward(speed=800):
in1.off(); in2.on(); in3.off(); in4.on()
ena.duty(speed); enb.duty(speed)
def turn_left(speed=800):
in1.off(); in2.on(); in3.on(); in4.off()
ena.duty(speed); enb.duty(speed)
def turn_right(speed=800):
in1.on(); in2.off(); in3.off(); in4.on()
ena.duty(speed); enb.duty(speed)
# Distance measurement
def get_distance():
trig.off()
sleep(0.002)
trig.on()
sleep(0.00001)
trig.off()
duration = time_pulse_us(echo, 1, 30000)
distance = (duration * 0.0343) / 2
return round(distance, 2)
# Main loop
while True:
dist = get_distance()
print("Distance:", dist, "cm")
if dist > 20:
forward()
else:
stop()
sleep(0.5)
turn_left()
sleep(0.5)
stop()
sleep(0.1)
You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.
You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.
You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.
You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.