Solomon Oche Ogonye
Published

Controlling DC Motors with Arduino and L298n Motor Driver

This project gives an introduction to Arduino and Robotics. it involves how to interface Arduino, DC Motors and L298n motor driver.

BeginnerProtip794
Controlling DC Motors with Arduino and L298n Motor Driver

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
Jumper wires (generic)
Jumper wires (generic)
×1
9V battery (generic)
9V battery (generic)
×1
L298N-Dual-H-bridge-Motor-Driver-Board
×1
DC motor
×2
PC laptop
×1
Amazon Web Services Arduino power cable
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

Circuit Diagram

follow the diagram to connect all components together.

Code

CODE

Arduino
Copy and paste the code on your Arduino IDE AND Upload.
// Motor A
 
int enA = 10;
int in1 = 8;
int in2 = 8;
 
// Motor B
 
int enB = 2;
int in3 = 4;
int in4 = 3;
 
void setup()
 
{
 
  // Set all the motor control pins to outputs
 
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
 
}
 
void demoOne()
 
{
 
  // This function will run the motors in both directions at a fixed speed
 
  // Turn on motor A
 
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
 
  // Set speed to 200 out of possible range 0~255
 
  analogWrite(enA, 200);
 
  // Turn on motor B
 
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
 
  // Set speed to 200 out of possible range 0~255
 
  analogWrite(enB, 200);
 
  delay(2000);
 
  // Now change motor directions
 
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH); 
 
  delay(2000);
 
  // Now turn off motors
 
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
 
}
 
void demoTwo()
 
{
 
  // This function will run the motors across the range of possible speeds
  // Note that maximum speed is determined by the motor itself and the operating voltage
 
  // Turn on motors
 
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH); 
 
  // Accelerate from zero to maximum speed
 
  for (int i = 0; i < 256; i++)
 
  {
 
    analogWrite(enA, i);
    analogWrite(enB, i);
 
    delay(20);
 
  } 
 
  // Decelerate from maximum speed to zero
 
  for (int i = 255; i >= 0; --i)
 
  {
 
    analogWrite(enA, i);
    analogWrite(enB, i);
 
    delay(20);
 
  } 
 
  // Now turn off motors
 
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);  
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);  
 
}
 
void loop()
 
{
 
  demoOne();
 
  delay(1000);
 
  demoTwo();
 
  delay(1000);
 
}

Credits

Solomon Oche Ogonye

Solomon Oche Ogonye

3 projects • 2 followers

Comments