Guest User

DC Motor W/ H Bridge, Potentiometer, 2 Buttons

a guest
Jan 27th, 2020
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. const int controlPin1 =2;
  2. const int controlPin2 =3;
  3. const int enablePin =9;
  4. const int directionPin =4;
  5. const int switchOnOff =5;
  6. const int potPin =A0;
  7. int motorSpeed;
  8. bool oldPressON =false;
  9. bool newPressON = false;
  10. // used to distinguish btw button presses - if the old and the new values are different, it's a new press, if it is the same value, then it is not a new press
  11. //booleans are either true or false, 0 or 1 -- on or off
  12. //need to define two new boolean vars for the direction button too
  13. bool oldDir = false;
  14. bool newDir = false;
  15. bool onoff = false;
  16. // to make motor on or off
  17. bool dir = false;
  18.  
  19. void setup() {
  20. // put your setup code here, to run once:
  21. pinMode (enablePin, OUTPUT);
  22. pinMode (controlPin1, OUTPUT);
  23. pinMode (controlPin2, OUTPUT);
  24. pinMode (directionPin, INPUT);
  25. pinMode (switchOnOff, INPUT);
  26. pinMode (potPin, INPUT);
  27. Serial.begin (9600);
  28.  
  29. }
  30.  
  31. void loop() {
  32.  
  33. newPressON=digitalRead (switchOnOff);
  34. Serial.println (newPressON);
  35. delay (5);
  36. //tested button that controls on or off
  37. if (newPressON ==1 && newPressON=!oldPressON)
  38. //&& means and -- both conditions have to be true
  39. {
  40. onoff = !onoff;
  41. //! means opposite (true to false, and false to true)
  42. //booleans are digital inputs
  43. }
  44.  
  45. newDir = digitalRead (directionPin);
  46. Serial.println (newDir);
  47. delay (5);
  48. //tested button that controls direction
  49.  
  50. motorSpeed = analogRead(potPin);
  51. motorSpeed = map(motorSpeed, 0, 1023, 0, 255);
  52. Serial.println (motorSpeed);
  53. //tested potentiometer
  54.  
  55. if (newDir ==1 && newDir = !oldDir)
  56. {
  57. dir = !dir;
  58. }
  59.  
  60. if (onoff)
  61. //if enable is true -- then turn motor on, map potentiometer, and go at speed of motorSpeed
  62. {
  63. motorSpeed = analogRead(potPin);
  64. motorSpeed = map(motorSpeed, 0, 1023, 0, 255);
  65. if (dir)
  66. //if dir is true, then we move in this direction
  67. {
  68. digitalWrite (controlPin1, HIGH);
  69. digitalWrite (controlPin2, LOW);
  70. //either high, low or low, high -- switches positives and negatives
  71. analogWrite (enablePin, motorSpeed);
  72. }
  73. else {
  74. digitalWrite (controlPin1, LOW);
  75. digitalWrite (controlPin2, HIGH);
  76. //either high, low or low, high -- switches positives and negatives
  77. analogWrite (enablePin, motorSpeed);
  78.  
  79. }
  80.  
  81. }
  82.  
  83. else {
  84. analogWrite (enablePin,0) ;
  85. }
  86.  
  87. newPressON = oldPressON;
  88. newDir = oldDir;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment