Lesson 4: Controlling Two Motors with an H-Bridge
Components:
- 2x DC motors
- 1x L298N H-Bridge motor driver
- 1x 9V battery or external power supply for the motors
- Jumper wires
- 1x ESP32
Code:
Now we control two motors, one for each side of the car. The motors will run simultaneously to move the car forward, backward, or turn.
from machine import Pin import time # Define pins connected to the H-Bridge for two motors IN1 = Pin(5, Pin.OUT) IN2 = Pin(18, Pin.OUT) IN3 = Pin(19, Pin.OUT) IN4 = Pin(21, Pin.OUT) def forward(): IN1.on() IN2.off() IN3.on() IN4.off() def backward(): IN1.off() IN2.on() IN3.off() IN4.on() def stop(): IN1.off() IN2.off() IN3.off() IN4.off() def turn_left(): IN1.off() IN2.on() IN3.on() IN4.off() def turn_right(): IN1.on() IN2.off() IN3.off() IN4.on() # Move forward for 2 seconds, then stop forward() time.sleep(2) stop()
Explanation:
- IN1, IN2 control one motor, and IN3, IN4 control the second motor.
- forward() moves both motors in the same direction, making the car go straight, while turn_left() and turn_right() turn the car.