2

I'm trying to individually control 3 LEDs with 3 toggle switches. This is the code I'm using

#define LED_PIN1 2  
#define BUTTON_PIN1 14

#define LED_PIN2 3 #define BUTTON_PIN2 15

#define LED_PIN3 4 #define BUTTON_PIN3 16

void setup() { pinMode(LED_PIN1, OUTPUT); pinMode(BUTTON_PIN1, INPUT);

pinMode(LED_PIN2, OUTPUT); pinMode(BUTTON_PIN2, INPUT);

pinMode(LED_PIN3, OUTPUT); pinMode(BUTTON_PIN3, INPUT);

} void loop() { if (digitalRead(BUTTON_PIN1) == HIGH) { digitalWrite(LED_PIN1, HIGH); } if (digitalRead(BUTTON_PIN1) == LOW) { digitalWrite(LED_PIN1, LOW); } if (digitalRead(BUTTON_PIN2) == HIGH) { digitalWrite(LED_PIN2, HIGH); } if (digitalRead(BUTTON_PIN2) == LOW) { digitalWrite(LED_PIN2, LOW); } if (digitalRead(BUTTON_PIN3) == HIGH) { digitalWrite(LED_PIN3, HIGH); } if (digitalRead(BUTTON_PIN3) == LOW) { digitalWrite(LED_PIN3, LOW); } }

The problem is that this code is causing all 3 LEDs to turn on or off together when any one of the three toggle switches is pushed. Can someone explain why this is happening? Also, what do I need to change so that each LED can be individually controlled?

Thanks!

Sam
  • 133
  • 6
mileguy72
  • 31
  • 3

1 Answers1

3

How is your wiring done?

This is a working example of how it can be done:

#define LED_PIN1 5  
#define BUTTON_PIN1 14

#define LED_PIN2 6 #define BUTTON_PIN2 15

#define LED_PIN3 7 #define BUTTON_PIN3 16

void setup() { // set up all the LEDs as OUTPUT pinMode(LED_PIN1, OUTPUT); pinMode(LED_PIN2, OUTPUT); pinMode(LED_PIN3, OUTPUT);

// set up all the buttons as INPUT pinMode(BUTTON_PIN1, INPUT); pinMode(BUTTON_PIN2, INPUT); pinMode(BUTTON_PIN3, INPUT); }

void loop() { // turn the LED on when button is pressed digitalWrite(LED_PIN1, digitalRead(BUTTON_PIN1)); digitalWrite(LED_PIN2, digitalRead(BUTTON_PIN2)); digitalWrite(LED_PIN3, digitalRead(BUTTON_PIN3)); }

When you just want the LED to be on when the button is pressed and off when the button is unpressed you can simplify the code by directly writing the button state to the LED like so: digitalWrite(LED_PIN, digitalRead(BUTTON_PIN)). Because read of the button will return either HIGH or LOW you can directly drive the LED with this.

Also make sure you check the pin's you are using on your device. Pin 3 is the reset pin. I therefore changed the pins to 5, 6, 7 to make sure you're using digital pins. Arduino Nano pinlayout

If you want to see a working example in action, take a look at this tinkercad. Be aware that I'm using an arduino uno here, so make sure that you use correct pins using the previous pin layout when adapting this to your Arduino nano. You can simulate this circuit by clicking on the 'simulate' button and test this working example by clicking on the buttons in the circuit. enter image description here

Sam
  • 133
  • 6