I got a SainSmart 4WD Robot Kit, which contains the L298N Motor Controller. There’s not a lot of documentation of how to use this, and much of what exists by users of the board is just plain wrong. I put together a short tutorial (as part of a much more comprehensive robot kit manual I’m writing), on how to use this controller, and make a simple robot that goes forwards, backwards, and turns left or right.
Schematic:
Code:
Become the Maker you were born to be. Try Arduino Academy for FREE!
//declaring the pins for the IN pins on the L298N const int rightForwardPin = 3; const int rightBackwardPin = 5; const int leftBackwardPin = 6; const int leftForwardPin = 9;
int runTime = 5000;
void setup() {
//Stating that the pins are OUTPUT
pinMode(rightForwardPin, OUTPUT);
pinMode(rightBackwardPin, OUTPUT);
pinMode(leftForwardPin, OUTPUT);
pinMode(leftBackwardPin, OUTPUT);
Serial.begin(9600);
}
//Looping to test the wheels of the car
void loop() {
forward();
stopCar();
backward();
stopCar();
left();
stopCar();
right();
stopCar();
}
//Setting the wheels to go forward by setting the forward pins to HIGH
void forward(){
Serial.println(“Forward”);
digitalWrite(rightForwardPin, HIGH);
digitalWrite(rightBackwardPin, LOW);
digitalWrite(leftForwardPin, HIGH);
digitalWrite(leftBackwardPin, LOW);
delay(runTime);
}
//Setting the wheels to go backward by setting the backward pins to HIGH
void backward(){
Serial.println(“Backward”);
digitalWrite(rightForwardPin, LOW);
digitalWrite(rightBackwardPin, HIGH);
digitalWrite(leftForwardPin, LOW);
digitalWrite(leftBackwardPin, HIGH);
delay(runTime);
}
//Setting the wheels to go right by setting the rightBackwardPin and leftForwardPin to HIGH
void right(){
Serial.println(“Right”);
digitalWrite(rightForwardPin, LOW);
digitalWrite(rightBackwardPin, HIGH);
digitalWrite(leftForwardPin, HIGH);
digitalWrite(leftBackwardPin, LOW);
delay(runTime);
}
//Setting the wheels to go left by setting the rightForwardPin and leftBackwardPin to HIGH
void left(){
Serial.println(“Left”);
digitalWrite(rightForwardPin, HIGH);
digitalWrite(rightBackwardPin, LOW);
digitalWrite(leftForwardPin, LOW);
digitalWrite(leftBackwardPin, HIGH);
delay(runTime);
}
//Setting the wheels to go stop by setting all the pins to LOW
void stopCar(){
Serial.println(“Stop”);
digitalWrite(rightForwardPin, LOW);
digitalWrite(rightBackwardPin, LOW);
digitalWrite(leftForwardPin, LOW);
digitalWrite(leftBackwardPin, LOW);
delay(1000);
}
Become the Maker you were born to be. Try Arduino Academy for FREE!
Video: