SHARE
TWEET

Programming the Continuous Motor Circuit with a Potentiomete

jmyean Apr 29th, 2019 92 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  /*
  2.   *  Jung Min Yean
  3.   *  Learning HBridge Motor Control
  4.   *  04/23/2019
  5.   */
  6.  
  7. const int MotorPin = 9;
  8. const int MC1 = 3; //Motor Control 1 direction
  9. const int MC2 = 2; //Motor Control other direction
  10. const int PotPin = A0;
  11.  
  12. int val = 0; // for storing the reading from the Pot.
  13. int velocity = 0; //For stroing the desired velocity (from 0 - 255)
  14.  
  15. void setup()
  16. {
  17.   pinMode(MotorPin, OUTPUT);
  18.   pinMode(MC1, OUTPUT);
  19.   pinMode(MC2, OUTPUT);
  20.   pinMode(PotPin, INPUT);
  21.   brake(); // Initialize w/ motor stopped
  22. }
  23.  
  24. void loop()
  25. {
  26.   val = analogRead(PotPin);
  27.  
  28.   // go forward
  29.   if (val > 550)
  30.   {
  31.     velocity = map(val, 550, 1023, 0, 255);
  32.     forward(velocity);
  33.   }
  34.  
  35.   // go backward
  36.   else if (val < 500)
  37.   {
  38.     velocity = map(val, 500, 0, 0, 255);
  39.     backward(velocity);
  40.   }
  41.   // brake is needed between 500 - 550 to change direction
  42.   else
  43.   {
  44.     brake();
  45.   }
  46. }
  47.  
  48. // Motor goes forward at given Motor rate (from 0 - 255)
  49. void forward(int rate)
  50. {
  51.   digitalWrite(MotorPin, LOW);
  52.   digitalWrite(MC1, HIGH);
  53.   digitalWrite(MC2, LOW);
  54.   analogWrite(MotorPin, rate);
  55. }
  56.  
  57. // Motor goes backward at given Motor rate (from 0 - 255)
  58. void backward(int rate)
  59. {
  60.   digitalWrite(MotorPin, LOW);
  61.   digitalWrite(MC1, LOW);
  62.   digitalWrite(MC2, HIGH);
  63.   analogWrite(MotorPin, rate);
  64. }
  65.  
  66. void brake()
  67. {
  68.   digitalWrite(MotorPin, LOW);
  69.   digitalWrite(MC1, LOW);
  70.   digitalWrite(MC2, LOW);
  71.   analogWrite(MotorPin, HIGH);
  72. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top