Skip to content

Instantly share code, notes, and snippets.

@natendaben
Created November 16, 2018 00:18
Show Gist options
  • Save natendaben/88c749f9069f7408826cf6449df6074e to your computer and use it in GitHub Desktop.
Save natendaben/88c749f9069f7408826cf6449df6074e to your computer and use it in GitHub Desktop.
DC Motor Code
const int switchPin = 2; // switch input
const int motor1Pin = 3; // H-bridge leg 1 (pin 2, 1A)
const int motor2Pin = 5; // 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);
pinMode(enablePin, OUTPUT);
// set enablePin high so that motor can turn on:
digitalWrite(enablePin, HIGH);
Serial.begin(9600);
}
void loop() {
//check if switch works
//Serial.println(digitalRead(switchPin));
// if the switch is high, motor will turn on one direction
// set leg 1 of the H-bridge low
// set leg 2 of the H-bridge high
if(digitalRead(switchPin)==HIGH)
{
digitalWrite(motor1Pin, HIGH);
analogWrite(motor2Pin, 0);
}
// else (which means the switch is low), motor will turn in the other direction
// set leg 1 of the H-bridge high
// set leg 2 of the H-bridge low
else{
digitalWrite(motor1Pin, LOW);
analogWrite(motor2Pin, 90);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment