Skip to content

Instantly share code, notes, and snippets.

@pastcompute
Created February 28, 2023 09:55
Show Gist options
  • Select an option

  • Save pastcompute/477b3a8308899bc26c7654cbd3769c65 to your computer and use it in GitHub Desktop.

Select an option

Save pastcompute/477b3a8308899bc26c7654cbd3769c65 to your computer and use it in GitHub Desktop.
Arduino L298 H bridge example
#define MOTOR_A_PIN_9 9
#define MOTOR_A_PIN_10 10
#define MOTOR_B_PIN_11 11
#define MOTOR_B_PIN_12 12
void setup() {
Serial.begin(115200);
delay(300);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(MOTOR_A_PIN_9, OUTPUT);
pinMode(MOTOR_A_PIN_10, OUTPUT);
pinMode(MOTOR_B_PIN_11, OUTPUT);
pinMode(MOTOR_B_PIN_12, OUTPUT);
digitalWrite(9, LOW);
digitalWrite(MOTOR_A_PIN_10, LOW);
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(300); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(300); // wait for a second
}
int i = 0;
void off(int motor) {
Serial.print(motor == 0 ? "A" : "B"); Serial.println(" off");
if (motor == 0) {
digitalWrite(MOTOR_A_PIN_9, LOW);
digitalWrite(MOTOR_A_PIN_10, LOW);
} else {
digitalWrite(MOTOR_B_PIN_11, LOW);
digitalWrite(MOTOR_B_PIN_12, LOW);
}
}
void forward(int motor) {
Serial.print(motor == 0 ? "A" : "B"); Serial.println(" fwd");
if (motor == 0) {
digitalWrite(MOTOR_A_PIN_9, LOW);
digitalWrite(MOTOR_A_PIN_10, HIGH);
} else {
digitalWrite(MOTOR_B_PIN_11, LOW);
digitalWrite(MOTOR_B_PIN_12, HIGH);
}
}
void backward(int motor) {
Serial.print(motor == 0 ? "A" : "B"); Serial.println(" bwd");
if (motor == 0) {
digitalWrite(MOTOR_A_PIN_9, HIGH);
digitalWrite(MOTOR_A_PIN_10, LOW);
} else {
digitalWrite(MOTOR_B_PIN_11, HIGH);
digitalWrite(MOTOR_B_PIN_12, LOW);
}
}
void loop() {
i++;
int pattern = i % 6;
Serial.print("pattern"); Serial.println(pattern);
if (pattern == 1) {
forward(0);
} else if (pattern == 2) {
backward(0);
} else if (pattern == 3) {
off(0);
} else if (pattern == 4) {
forward(1);
} else if (pattern == 5) {
backward(1);
} else {
off(1);
}
delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment