/*
Forum:https://forum.arduino.cc/t/joystick-and-led/1201691
Wokwi:https://wokwi.com/projects/384488613015669761
*/
constexpr byte joystick_x = A0;
constexpr byte joystick_y = A1;
constexpr byte noOfLeds {5};
constexpr byte xAxisPins[noOfLeds] = {3, 4, 5, 6, 7};
constexpr byte yAxisPins[noOfLeds] = {8, 9, 5, 10, 11};
constexpr unsigned long INTERVAL {200}; // Every 200 ms (1/5 th of a second) update of the led cross
unsigned long lastUpdate = 0;
int valueX;
int valueY;
int ledX;
int ledY;
void setup()
{
for (int i = 0; i < noOfLeds; i++ ) {
pinMode(xAxisPins[i], OUTPUT);
pinMode(yAxisPins[i], OUTPUT);
}
Serial.begin(9600);
}
void loop() {
if (millis() - lastUpdate > INTERVAL) {
lastUpdate = millis();
valueX = analogRead(A0);
valueY = analogRead(A1);
ledX = map(valueX, 0, 1024, 0, 5);
ledY = map(valueY, 0, 1024, 0, 5);
setLeds(ledX, ledY);
printData();
}
}
void setLeds(byte lx, byte ly) {
for (int i = 0; i < noOfLeds; i++ ) {
digitalWrite(xAxisPins[i], i == lx ? HIGH : LOW);
digitalWrite(yAxisPins[i], i == ly ? HIGH : LOW);
}
if (lx == 2 || ly == 2) {
digitalWrite(xAxisPins[2], HIGH);
}
}
void printData() {
Serial.print("VRx : ");
Serial.print(valueX);
Serial.print(" ");
Serial.print("VRy : ");
Serial.println(valueY);
Serial.print("Led X : ");
Serial.print(ledX);
Serial.print(" ");
Serial.print("Led Y : ");
Serial.println(ledY);
}