Lesson 3: H-Bridge and Motor Control
Components:
- 1x DC motor
- 1x L298N H-Bridge motor driver
- 1x 9V battery or external power supply for the motors
- Jumper wires
- 1x ESP32
Code:
This code will control the motor using an H-Bridge motor driver. You will control the motor’s direction by toggling the GPIO pins connected to the H-Bridge.
from machine import Pin import time # Define pins connected to the H-Bridge IN1 = Pin(5, Pin.OUT) IN2 = Pin(18, Pin.OUT) def motor_forward(): IN1.on() IN2.off() def motor_backward(): IN1.off() IN2.on() def motor_stop(): IN1.off() IN2.off() # Run the motor in both directions for 2 seconds motor_forward() time.sleep(2) motor_stop() time.sleep(1) motor_backward() time.sleep(2) motor_stop()
Explanation:
- IN1 and IN2 control the motor’s direction.
- The motor_forward() and motor_backward() functions control which way the motor spins.