# DC Motor Robot Control
# Introduction to DC Motors
Meet our DC motor robot. This robot uses standard DC motors controlled by an H-bridge (L298N motor driver). DC motors are the most common type of motor used in robotics and provide continuous rotation with speed and direction control.
# Wiring Configuration
Our robot uses the following pin configuration (standard L298N setup):
# Left Motor
- IN1 (Direction) → Pin 4
- IN2 (Direction) → Pin 5
- ENA (Enable/Speed) → Pin 6 (PWM)
# Right Motor
- IN3 (Direction) → Pin 7
- IN4 (Direction) → Pin 8
- ENB (Enable/Speed) → Pin 9 (PWM)
# Ultrasonic Sensor (optional)
- Trigger → Pin 2
- Echo → Pin 3
# Basic Control
# Speed Control (PWM)
Speed is controlled using analogWrite()
with values from 0 to 255:
0
= stopped128
= half speed255
= full speed
# Direction Control
Direction is set using two pins (IN1/IN2 for left, IN3/IN4 for right):
IN1=HIGH, IN2=LOW
→ ForwardIN1=LOW, IN2=HIGH
→ BackwardBoth LOW
→ Stop
# Forward Movement
Let's start with the simplest possible motor control - using digitalWrite()
and analogWrite()
directly.
Exercise
Can you get all the coins??
# Using Helper Functions
As you can see, controlling motors directly takes a lot of code. Let's use helper functions as methods to make our code cleaner, easier to understand and more versatile.
Exercise
Can you get all the coins in the environment?
# Movement Patterns
# Basic Movements
// Forward
drive(180, 180);
// Backward
drive(-180, -180);
// Turn left (spin in place - left backward, right forward)
drive(-180, 180);
// Turn right (spin in place - left forward, right backward)
drive(180, -180);
// Curve left (slow down left wheel)
drive(90, 180);
// Curve right (slow down right wheel)
drive(180, 90);
// Stop
drive(0, 0);
# Key Concepts
# PWM (Pulse Width Modulation)
- Controls motor speed by rapidly switching power on/off
- Value 0-255 represents duty cycle (0% to 100%)
- Arduino's
analogWrite()
generates PWM automatically
# H-Bridge
- Electronic circuit that allows bidirectional motor control
- The L298N chip contains two H-bridges (one per motor)
- Handles high currents that Arduino pins cannot provide
# Differential Drive
- Two independently controlled wheels
- Turn by running wheels at different speeds
- Most common configuration for small robots
# Tips
- Start with low speeds (~100-150) to test your code
- Motors may not be perfectly matched - you might need different speeds for straight movement
- Use delays carefully - timing is critical for distance traveled
- The
drive()
function makes code much more readable - Negative speeds reverse direction - very intuitive! Make sure you wire up your physical robots correctly.
# Try these challenges
- Make the robot drive in a square
- Create a function to turn exactly 90 degrees
- Make the robot drive in a figure-8 pattern
Next we will learn about the ultrasonic sensor for detecting obstacles and use the feedback we get as logic for navigation.