Advertisement
markruff

Arduino analog joystick

Jan 19th, 2016
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. /*
  2.  * Arduino reading analog joystick inputs and lighting
  3.  * LEDs (up, down, left, right)
  4.  *
  5.  * Using duinotech X&Y axis joystick module (xc-4422)
  6.  * (ignoring digital switch for now)
  7.  *
  8.  * LEDs light up with brightness relative to displacement
  9.  * from neutral point. This is achieved with crude PWM
  10.  * (pulse wave modulation), where the LED is turned on and
  11.  * off rapidly. Here the on time is xVal / DELAY_FACTOR, and
  12.  * the off time is however long it takes to process the rest
  13.  * of the loop until the LED is turned back on (hence crude).
  14.  * Keep in mind, having displacement in both axes results in
  15.  * the delay of the on-phase in one axis contributing to the
  16.  * off-phase in the other axis. This can lead to flickering.
  17.  *
  18.  * A DELAY_FACTOR of 50 works well for me. An alternative
  19.  * would be to use true PWM through pins 3, 5, 6, 9, 10 or 11.
  20.  */
  21.  
  22. // Globals
  23. const int yAxis = A0;
  24. const int xAxis = A1;
  25.  
  26. const int upLed = 7;
  27. const int rightLed = 6;
  28. const int downLed = 5;
  29. const int leftLed = 4;
  30.  
  31. // Buffer to ignore around neutral point
  32. const int BUFFER = 20;
  33.  
  34. // delay factor used for crude homebrew pulse wave modulation
  35. const int DELAY_FACTOR = 50;
  36.  
  37. void setup() {
  38.   pinMode(xAxis, INPUT);
  39.   pinMode(yAxis, INPUT);
  40.   pinMode(upLed, OUTPUT);
  41.   pinMode(rightLed, OUTPUT);
  42.   pinMode(downLed, OUTPUT);
  43.   pinMode(leftLed, OUTPUT);
  44. }
  45.  
  46. void loop() {
  47.   int xVal = analogRead(xAxis) - 512;
  48.   int yVal = analogRead(yAxis) - 512;
  49.  
  50.   if ( xVal > BUFFER ) {
  51.     digitalWrite(leftLed,HIGH);
  52.     delay((xVal-BUFFER)/50);
  53.     digitalWrite(leftLed,LOW);
  54.   }
  55.   else if ( xVal < -BUFFER ) {
  56.     digitalWrite(rightLed,HIGH);
  57.     delay((BUFFER-xVal)/50);
  58.     digitalWrite(rightLed,LOW);
  59.   }
  60.   if ( yVal > BUFFER ) {
  61.     digitalWrite(upLed,HIGH);
  62.     delay((yVal-BUFFER)/50);
  63.     digitalWrite(upLed,LOW);
  64.   }
  65.   else if ( yVal < -BUFFER ) {
  66.     digitalWrite(downLed,HIGH);
  67.     delay((BUFFER-yVal)/50);
  68.     digitalWrite(downLed,LOW);
  69.   }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement