Penn State
Robotics Club
MOTORS + PUTTING IT ALL TOGETHER
Based on GitHub Tutorial by Dhruv Sringari
The Goal:
Create a robot that moves forward until it reaches a wall and stop before colliding.
We’ll do this by adding motors to what we’ve built in tutorials 1 and 2.
Motors
DC Motor
2 Wires
Bidirectional if attached backwards
Cannot be supplied with sufficient power from an Arduino or Pi
Watch this to learn how a DC motor works
Motor Driver
Controlled by signals sent from Arduino
Powered by a separate battery source
Can do variable motor speed
Motor Controller (L298N)
Start with our circuit from last week
Available here if you don’t have it:
Add battery and motor controller
5 V Power
9 V Power
Ground
Connect Motor 1
5 V Power
9 V Power
Ground
Speed Signal
Forward Signal
Backward Signal
Define pins for motor 1
Add this before the setup() function:
// Define pins for motor controller
const int MOTOR1_FORWARD = 12; // Input 1
const int MOTOR1_BACKWARD = 11; // Input 2
const int MOTOR1_SPEED = 5; // Enable 1 & 2
Do the same thing for motor 2
5 V Power
9 V Power
Ground
Speed Signal
Forward Signal
Backward Signal
Define pins for motor 2
// Define pins for motor controller
const int MOTOR1_FORWARD = 12; // Input 1
const int MOTOR1_BACKWARD = 11; // Input 2
const int MOTOR1_SPEED = 5; // Enable 1 & 2
const int MOTOR2_FORWARD = 3; // Input 3
const int MOTOR2_BACKWARD = 2; // Input 4
const int MOTOR2_SPEED = 6; // Enable 3 & 4
Final Circuit
5 V Power
9 V Power
Ground
Speed Signal
Forward Signal
Backward Signal
Write the code: Setup Function
Add this to our setup() function:
// Set speed for both motors
digitalWrite(MOTOR1_SPEED, HIGH);
digitalWrite(MOTOR2_SPEED, HIGH);
Write the code: Loop Function
Add the bolded lines to our loop() function:
if (distance < 20) { // If the distance is < 20cm:
// Turn on the LED
digitalWrite(LED_PIN, HIGH);
// Turn off motor 1 by setting both pins to low
digitalWrite(MOTOR1_FORWARD, LOW);
digitalWrite(MOTOR1_BACKWARD, LOW);
// Do the same for motor 2
digitalWrite(MOTOR2_FORWARD, LOW);
digitalWrite(MOTOR2_BACKWARD, LOW);
} else { // If the distance is not < 20cm
// Turn off the LED
digitalWrite(LED_PIN, LOW);
// Setting the forward pin to high and backward to low will make the motors rotate forward.
digitalWrite(MOTOR1_FORWARD, HIGH);
digitalWrite(MOTOR1_BACKWARD, LOW);
// Do the same for the right motor.
digitalWrite(MOTOR2_FORWARD, HIGH);
digitalWrite(MOTOR2_BACKWARD, LOW);
}
Your robot is complete!
PWM Control
PWM Control
PWM Control in Arduino
Slowing down the motors
To slow down the motors, replace the code in setup() where we set the motor speeds with:
// Set speed for both motors
analogWrite(MOTOR1_SPEED, 128);
analogWrite(MOTOR2_SPEED, 128);
Questions?