Skip to content

Instantly share code, notes, and snippets.

@CodeNextAdmin
Created March 13, 2023 23:10
Show Gist options
  • Save CodeNextAdmin/56e882d444b4e4a63276f37ea323c1b8 to your computer and use it in GitHub Desktop.
Save CodeNextAdmin/56e882d444b4e4a63276f37ea323c1b8 to your computer and use it in GitHub Desktop.
A sketch to drive an Arduino car with an L298N and 2 DC motors (with drive functions)
/* 2 MOTOR L298N and Potentiometer
* with functions (forward, reverse, turnRight, turnLeft)
* motor rotation will vary depending on the DC motor wiring
* and the orientation of the motor relative to the car/surface.
*
*/
//motor 2
#define enA 9
#define in1 6
#define in2 7
////motor 2
#define in3 5
#define in4 4
#define enB 3 //pwm for motor 2
//potentiometer
#define pot A0
int potVal = 0;
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);
pinMode(pot, INPUT);
Serial.begin(9600);
//initialize off
// digitalWrite(in1, LOW);
// digitalWrite(in2, LOW);
// digitalWrite(in3, LOW);
// digitalWrite(in4, LOW);
}
void loop() {
potVal = analogRead(pot);
Serial.println(potVal);
potVal = map(potVal, 0, 1023, 0, 255);
analogWrite(enA, potVal);
analogWrite(enB, potVal);
forward();
delay(3000); //go forward 3 seconds
reverse();
delay(3000); //go reverse 3 seconds
turnRight();
delay(3000);
turnLeft();
delay(3000);
}
void forward(){
//motor 1
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
//motor 2
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
}
void reverse(){
//motor 1
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
//motor 2
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
}
void turnLeft(){
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
}
void turnRight(){
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment