This circuit is designed to control a traffic light using an Arduino UNO and a joystick module. The traffic light has three LEDs (red, yellow, and green) that are controlled by the joystick's position. Moving the joystick up turns on the red LED, moving it left turns on the yellow LED, and moving it right turns on the green LED. Moving the joystick down turns on all LEDs. The joystick also has a switch (SW) that is read by the Arduino but not used in the current code.
/*
* This Arduino sketch controls a traffic light using a joystick module.
* When the joystick is moved up, the red LED turns on.
* When the joystick is moved left, the yellow LED turns on.
* When the joystick is moved right, the green LED turns on.
* When the joystick is moved down, all LEDs turn on.
*/
const int redLED = 2; // Red LED connected to digital pin 2
const int yellowLED = 3; // Yellow LED connected to digital pin 3
const int greenLED = 4; // Green LED connected to digital pin 4
const int vrxPin = A0; // Joystick VRX connected to analog pin A0
const int vryPin = A1; // Joystick VRY connected to analog pin A1
const int swPin = 7; // Joystick SW connected to digital pin 7
void setup() {
pinMode(redLED, OUTPUT);
pinMode(yellowLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(swPin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int vrxValue = analogRead(vrxPin); // Read joystick X-axis
int vryValue = analogRead(vryPin); // Read joystick Y-axis
int swValue = digitalRead(swPin); // Read joystick button
// Center values for the joystick
int centerX = 512;
int centerY = 512;
int threshold = 100; // Threshold to detect significant movement
// Turn off all LEDs initially
digitalWrite(redLED, LOW);
digitalWrite(yellowLED, LOW);
digitalWrite(greenLED, LOW);
if (vryValue < centerY - threshold) { // Joystick moved up
digitalWrite(redLED, HIGH);
} else if (vrxValue < centerX - threshold) { // Joystick moved left
digitalWrite(yellowLED, HIGH);
} else if (vrxValue > centerX + threshold) { // Joystick moved right
digitalWrite(greenLED, HIGH);
} else if (vryValue > centerY + threshold) { // Joystick moved down
digitalWrite(redLED, HIGH);
digitalWrite(yellowLED, HIGH);
digitalWrite(greenLED, HIGH);
}
delay(100); // Small delay to avoid flickering
}
This code is designed to be uploaded to the Arduino UNO microcontroller. It initializes the pins connected to the LEDs as outputs and the joystick switch as an input with an internal pull-up resistor. The loop
function reads the joystick's analog values and turns on the corresponding LEDs based on the joystick's position. The switch state is read but not used in the current logic.