Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //create 3 global variables
- //PWM controls speed
- //DIR A and B are the direction logic pins
- const int PWM = 3;
- const int DIRA = 4;
- const int DIRB = 5;
- const int BUTTON = 6;
- // names different than the functions
- const int FWD = 1;
- const int REV = 2;
- int direction = 1;
- // 1 = forward
- // 2 = reverse
- // determine if we break or not
- bool moving = false;
- // state variable to track change in button
- // prevents multiple "acitons" from happening
- // when slow humans press the button
- boolean lastButton = true;
- void setup()
- {
- //pinModes for H-Bridge control pins
- pinMode(PWM, OUTPUT);
- pinMode(DIRA, OUTPUT);
- pinMode(DIRB, OUTPUT);
- //set pin 6 to INPUT_PULLUP, no need for a pullup resistor
- pinMode(BUTTON, INPUT_PULLUP);
- Serial.begin(115200);
- }
- void loop()
- {
- //create a local varaible thats stores the button state (1 or 0)
- int currentButton = digitalRead(BUTTON);
- //if buttonState is 0 (less than 1) toggle the state variable to
- //the opposite of the current state (!state)
- if (currentButton != lastButton) {
- // the button has been pressed.
- if (currentButton == LOW) {
- Serial.println(F("Button"));
- if (moving) {
- // we are moving, stop
- brake();
- } else {
- // we aren't moving, so let's start
- moving = true;
- // find the direction
- if (direction == FWD)
- forward(255);
- else
- reverse(255);
- }
- // debounce
- delay(100);
- }
- }
- lastButton = currentButton; // determine when press has stopped
- }
- //custom function for forward
- void forward(int Speed)
- {
- Serial.println(F("Foward"));
- digitalWrite(DIRA, HIGH);
- digitalWrite(DIRB, LOW);
- analogWrite(PWM, Speed);
- // switch directions on next push
- direction = REV;
- }
- //custom function for brake (stop)
- void brake()
- {
- Serial.println(F("Break"));
- digitalWrite(DIRA, LOW);
- digitalWrite(DIRB, LOW);
- moving = false;
- }
- //custom function for reverse
- void reverse(int Speed)
- {
- Serial.println(F("Reverse"));
- digitalWrite(DIRA, LOW);
- digitalWrite(DIRB, HIGH);
- analogWrite(PWM, Speed);
- // switch directions on next push
- direction = FWD;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement