Advertisement
baldengineer

buttons and motors

Dec 13th, 2015
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.19 KB | None | 0 0
  1. //create 3 global variables
  2. //PWM controls speed
  3. //DIR A and B are the direction logic pins
  4. const int PWM = 3;
  5. const int DIRA = 4;
  6. const int DIRB = 5;
  7.  
  8. const int BUTTON = 6;
  9.  
  10. // names different than the functions
  11. const int FWD = 1;
  12. const int REV = 2;
  13.  
  14.  
  15. int direction = 1;
  16. // 1 = forward
  17. // 2 = reverse
  18.  
  19. // determine if we break or not
  20. bool moving = false;
  21.  
  22. // state variable to track change in button
  23. // prevents multiple "acitons" from happening
  24. // when slow humans press the button
  25. boolean lastButton = true;
  26.  
  27. void setup()
  28. {
  29.   //pinModes for H-Bridge control pins
  30.   pinMode(PWM, OUTPUT);
  31.   pinMode(DIRA, OUTPUT);
  32.   pinMode(DIRB, OUTPUT);
  33.   //set pin 6 to INPUT_PULLUP, no need for a pullup resistor
  34.   pinMode(BUTTON, INPUT_PULLUP);
  35.   Serial.begin(115200);
  36. }
  37.  
  38. void loop()
  39. {
  40.   //create a local varaible thats stores the button state (1 or 0)
  41.   int currentButton = digitalRead(BUTTON);
  42.  
  43.   //if buttonState is 0 (less than 1) toggle the state variable to
  44.   //the opposite of the current state (!state)
  45.   if (currentButton != lastButton) {
  46.     // the button has been pressed.
  47.     if (currentButton == LOW) {
  48.       Serial.println(F("Button"));
  49.       if (moving) {
  50.         // we are moving, stop
  51.         brake();
  52.       } else {
  53.         // we aren't moving, so let's start
  54.         moving = true;
  55.  
  56.         // find the direction
  57.         if (direction == FWD)
  58.           forward(255);
  59.         else
  60.           reverse(255);
  61.       }
  62.       // debounce
  63.       delay(100);
  64.     }
  65.   }
  66.   lastButton = currentButton; // determine when press has stopped
  67. }
  68.  
  69. //custom function for forward
  70. void forward(int Speed)
  71. {
  72.   Serial.println(F("Foward"));
  73.   digitalWrite(DIRA, HIGH);
  74.   digitalWrite(DIRB, LOW);
  75.   analogWrite(PWM, Speed);
  76.  
  77.  // switch directions on next push
  78.   direction = REV;
  79. }
  80.  
  81. //custom function for brake (stop)
  82. void brake()
  83. {
  84.   Serial.println(F("Break"));
  85.   digitalWrite(DIRA, LOW);
  86.   digitalWrite(DIRB, LOW);
  87.   moving = false;
  88. }
  89.  
  90. //custom function for reverse
  91. void reverse(int Speed)
  92. {
  93.   Serial.println(F("Reverse"));
  94.   digitalWrite(DIRA, LOW);
  95.   digitalWrite(DIRB, HIGH);
  96.   analogWrite(PWM, Speed);
  97.  
  98.   // switch directions on next push
  99.   direction = FWD;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement