Advertisement
FahmiG

Joystick control dc motor

Jul 7th, 2015
8,832
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. /*+++++++++++++++++++++++++++++++++++++++++++++++++++
  2. Author      : Fahmi Ghani
  3. Date        : 4 July 2015
  4. Project     : Joystick control dc motor
  5. Component   : Analog Joystick
  6.               2Amp motor driver shield
  7.               DC Motor
  8. Description : Control DC motor direction using Joystick
  9. Video link  : http://youtu.be/fUo7tBSh9LE
  10. +++++++++++++++++++++++++++++++++++++++++++++++++++*/
  11.  
  12. //Set pin numbers:
  13. const byte joyStickPin = A1;
  14. const byte motorSpeedPin = 5;
  15. const byte motorDirPin = 4;
  16.  
  17. //variables
  18. //Joystick input variables
  19. int joyValue = 0;
  20. int joyValueMax = 1023;
  21. int joyValueMin = 0;
  22. int joyValueMid = 512;
  23. int joyValueMidUpper = joyValueMid + 20;
  24. int joyValueMidLower = joyValueMid - 20;
  25.  
  26. //DC motor variables
  27. byte motorSpeed = 0;
  28. byte motorSpeedMax = 255;
  29. byte motorSpeedMin = 90; //set to smallest value that make motor move (default 0)
  30.                          // DC motor that I use start to move at 90 pwm value
  31.  
  32. void setup()
  33. {
  34.     pinMode(joyStickPin, INPUT);
  35.     pinMode(motorSpeedPin, OUTPUT);
  36.     pinMode(motorDirPin, OUTPUT);
  37. }
  38.  
  39. void loop()
  40. {
  41.     joyValue = analogRead(joyStickPin);
  42.    
  43.     if(joyValue > joyValueMidUpper) //Forward
  44.     {
  45.         motorSpeed = map(joyValue, joyValueMidUpper, joyValueMax, motorSpeedMin, motorSpeedMax);
  46.         MotorForward(motorSpeed);
  47.     }
  48.     else if(joyValue < joyValueMidLower) //Backward
  49.     {
  50.         motorSpeed = map(joyValue, joyValueMidLower, joyValueMin, motorSpeedMin, motorSpeedMax);
  51.         MotorBackward(motorSpeed);
  52.     }
  53.     //joyValue Between joyValueMidLower - joyValueMidUpper.
  54.     //Need some range here, because joystick sometime not in  exact center.
  55.     else
  56.     {
  57.        MotorStop();
  58.     }
  59.    
  60.  
  61. }
  62. void MotorForward( byte Spd)
  63. {
  64.     digitalWrite(motorDirPin, HIGH);
  65.     analogWrite(motorSpeedPin, Spd);
  66. }
  67.  
  68. void MotorBackward( byte Spd)
  69. {
  70.     digitalWrite(motorDirPin, LOW);
  71.     analogWrite(motorSpeedPin, Spd);
  72. }
  73.  
  74. void MotorStop()
  75. {
  76.     analogWrite(motorSpeedPin, 0);  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement