TringaliLuca

Moving a 2-motors robot with Arduino and a Joystick

Oct 12th, 2017
104
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Moving a two motors robot forward with Arduino and a joystick (https://www.sparkfun.com/products/9032)
  2. // by Luca Tringali
  3. //
  4.  
  5. int dirbpin = 13;
  6. int dirapin = 12;
  7. int speedbpin = 11;
  8. int speedapin = 10;
  9. int hpin = 2; //joystick horizontal axis
  10. int vpin = 3; //joystick vertical axis
  11. int speeda = 0;
  12. int speedb = 0;
  13. int dir = 0;
  14.  
  15. void setup()
  16. {
  17. pinMode(dirbpin, OUTPUT);
  18. pinMode(dirapin, OUTPUT);
  19. pinMode(speedbpin, OUTPUT);
  20. pinMode(speedapin, OUTPUT);
  21. }
  22.  
  23. void loop()
  24. {
  25.   // forward, backward
  26.   int vval = analogRead(vpin);
  27.   if (vval > 549) {
  28.     dir = 1;
  29.     vval = map(vval, 550, 1023, 0, 250);
  30.   } else if (vval > 470) {
  31.       vval = 0;
  32.   } else {
  33.     dir = 0;
  34.     vval = map(vval, 470, 0, 0, 250);
  35.   }
  36.  
  37.   // right, left
  38.   int hval = analogRead(hpin);
  39.   if (hval > 600) {
  40.     speeda = vval;
  41.     speedb = 0;
  42.   } else if (hval > 400) {
  43.     speeda = vval;
  44.     speedb = vval;  
  45.   } else {
  46.     speeda = 0;
  47.     speedb = vval;
  48.   }
  49.  
  50.   digitalWrite(dirapin, dir); // set direction
  51.   analogWrite(speedapin, speeda); // set speed
  52.   digitalWrite(dirbpin, dir); // set direction
  53.   analogWrite(speedbpin, speedb); // set speed
  54.   delay(10);
  55. }
  56.  
  57.  
  58. // if you are looking for RC http://abottravel.blogspot.it/2011/12/how-to-read-rc-radio-signals-with.html
RAW Paste Data