Skip to content

Instantly share code, notes, and snippets.

@peow2373
Created April 15, 2020 05:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peow2373/d17a85a4c27e61249998284165c9ad55 to your computer and use it in GitHub Desktop.
Save peow2373/d17a85a4c27e61249998284165c9ad55 to your computer and use it in GitHub Desktop.
Swaps the direction in which a DC motor is rotating when a switch has a HIGH input
const int switchPin = 2; // switch input
const int motor1Pin = 3; // H-bridge leg 1 (pin 2, 1A)
const int motor2Pin = 4; // H-bridge leg 2 (pin 7, 2A)
const int enablePin = 9; // H-bridge enable pin
void setup() {
// set the switch as an input:
pinMode(switchPin, INPUT);
// set all the other pins you're using as outputs:
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
// set enablePin high so that motor can turn on:
analogWrite(enablePin, 850);
Serial.begin(9600);
}
void loop() {
// if the switch is high, motor will turn on one direction
if (digitalRead(switchPin) == HIGH) {
// set leg 1 of the H-bridge low
digitalWrite(motor1Pin, LOW);
// set leg 2 of the H-bridge high
digitalWrite(motor2Pin, HIGH);
Serial.print("High");
Serial.print("\n");
}
// else (which means the switch is low), motor will turn in the other direction
else {
// set leg 1 of the H-bridge high
digitalWrite(motor1Pin, HIGH);
// set leg 2 of the H-bridge low
digitalWrite(motor2Pin, LOW);
Serial.print("Low");
Serial.print("\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment