Control A DC Motor With An Arduino
Control A DC Motor With An Arduino
Hardware Required
1 x L298 bridge IC
1
1 x DC motor
1 x Arduino Mega2560
1 x breadboard
10 x jumper wires
The schematic above shows how to connect the L298 IC to control two motors. There are three input
pins for each motor, including Input1 (IN1), Input2 (IN2), and Enable1 (EN1) for Motor1 and Input3,
Input4, and Enable2 for Motor2.
Since we will be controlling only one motor in this tutorial, we will connect the Arduino to IN1 (pin 5),
IN2 (pin 7), and Enable1 (pin 6) of the L298 IC. Pins 5 and 7 are digital, i.e. ON or OFF inputs, while
pin 6 needs a pulse-width modulated (PWM) signal to control the motor speed.
The following table shows which direction the motor will turn based on the digital values of IN1 and
IN2.
2
IN1
IN2
1
1
1
1
MOTOR
BRAKE
FORWARD
BACKWARD
BRAKE
IN1 pin of the L298 IC is connected to pin 8 of the Arduino while IN2 is connected to pin 9. These two
digital pins of Arduino control the direction of the motor. The EN A pin of IC is connected to the PWM
pin 2 of Arduino. This will control the speed of the motor.
To set the values of Arduino pins 8 and 9, we will use the digitalWrite() function, and to set the value of
pin 2, we will use the using analogWrite() function.
Below is a photo of the set up.
Code
3
void loop()
{
//For Clock wise motion , in_1 = High , in_2 = Low
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,LOW) ;
analogWrite(pwm,255) ;
/*setting pwm of the motor to 255
we can change the speed of rotaion
by chaning pwm input but we are only
using arduino so we are using higest
value to driver the motor */
//Clockwise for 3 secs
delay(3000) ;
//For brake
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,HIGH) ;
delay(1000) ;
//For Anti Clock-wise motion - IN_1 = LOW , IN_2 = HIGH
digitalWrite(in_1,LOW) ;
digitalWrite(in_2,HIGH) ;
delay(3000) ;
//For brake
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,HIGH) ;
delay(1000) ;
}
Setup
1. Connect 5V and ground of the IC to 5V and ground of Arduino.
2. Connect the motor to pins 2 and 3 of the IC.
4