π Basic Motor Control Programming
π― Lesson Objective
In this lesson, students will learn:
- How to control DC motors using ESP32
- How to write movement logic (Forward, Backward, Left, Right, Stop)
- How digital signals control motor direction
- How to test robot movement without WiFi
By the end of this lesson, students will be able to program and control the robot manually using ESP32.
π§ Concept Introduction
Before adding WiFi or mobile control, we must first understand how to control motors directly using programming.
The ESP32 sends HIGH (1) and LOW (0) signals to the motor driver, which controls motor direction.
βοΈ Motor Control Logic
Each motor is controlled using 2 input pins:
| Motor Action | Logic |
|---|---|
| Forward | IN1 = HIGH, IN2 = LOW |
| Backward | IN1 = LOW, IN2 = HIGH |
| Stop | IN1 = LOW, IN2 = LOW |
π Same logic applies to the second motor.
π Pin Setup (Recap)
- IN1 β 26
- IN2 β 27
- IN3 β 14
- IN4 β 12
π» ESP32 Motor Control Code
int IN1 = 26;
int IN2 = 27;
int IN3 = 14;
int IN4 = 12;
void setup() {
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
}
// Movement Functions
void forward() {
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
}
void backward() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
}
void left() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
digitalWrite(IN3, HIGH);
digitalWrite(IN4, LOW);
}
void right() {
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, HIGH);
}
void stopRobot() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
}
void loop() {
forward();
delay(2000);
left();
delay(2000);
right();
delay(2000);
backward();
delay(2000);
stopRobot();
delay(2000);
}
π Code Explanation
pinMode()β Sets pins as outputdigitalWrite()β Sends HIGH/LOW signals- Functions β Used for modular programming
delay()β Controls timing of movements
π§ͺ Practical Activity
- Upload the code to ESP32
- Power ON the robot
- Observe movement sequence:
- Forward β Left β Right β Backward β Stop
π§ Key Learning Concepts
- Digital Output Control
- Motor Direction Logic
- Function-Based Programming
- Sequential Execution
β οΈ Common Issues & Solutions
| Problem | Solution |
|---|---|
| Motors not moving | Check wiring |
| Only one motor working | Check connections |
| Wrong direction | Swap motor wires |
| No response | Check power supply |
π Lesson Summary
In this lesson, students learned how to control motors using ESP32 by sending digital signals. They also understood how to organize code using functions and tested robot movement without WiFi.
π Practice Task
- Modify delay values and observe changes
- Create your own movement sequence
- Write a function for diagonal movement