/* * Arduino reading analog joystick inputs and lighting * LEDs (up, down, left, right) * * Using duinotech X&Y axis joystick module (xc-4422) * (ignoring digital switch for now) * * LEDs light up with brightness relative to displacement * from neutral point. This is achieved with crude PWM * (pulse wave modulation), where the LED is turned on and * off rapidly. Here the on time is xVal / DELAY_FACTOR, and * the off time is however long it takes to process the rest * of the loop until the LED is turned back on (hence crude). * Keep in mind, having displacement in both axes results in * the delay of the on-phase in one axis contributing to the * off-phase in the other axis. This can lead to flickering. * * A DELAY_FACTOR of 50 works well for me. An alternative * would be to use true PWM through pins 3, 5, 6, 9, 10 or 11. */ // Globals const int yAxis = A0; const int xAxis = A1; const int upLed = 7; const int rightLed = 6; const int downLed = 5; const int leftLed = 4; // Buffer to ignore around neutral point const int BUFFER = 20; // delay factor used for crude homebrew pulse wave modulation const int DELAY_FACTOR = 50; void setup() { pinMode(xAxis, INPUT); pinMode(yAxis, INPUT); pinMode(upLed, OUTPUT); pinMode(rightLed, OUTPUT); pinMode(downLed, OUTPUT); pinMode(leftLed, OUTPUT); } void loop() { int xVal = analogRead(xAxis) - 512; int yVal = analogRead(yAxis) - 512; if ( xVal > BUFFER ) { digitalWrite(leftLed,HIGH); delay((xVal-BUFFER)/50); digitalWrite(leftLed,LOW); } else if ( xVal < -BUFFER ) { digitalWrite(rightLed,HIGH); delay((BUFFER-xVal)/50); digitalWrite(rightLed,LOW); } if ( yVal > BUFFER ) { digitalWrite(upLed,HIGH); delay((yVal-BUFFER)/50); digitalWrite(upLed,LOW); } else if ( yVal < -BUFFER ) { digitalWrite(downLed,HIGH); delay((BUFFER-yVal)/50); digitalWrite(downLed,LOW); } }