Hello all. I have a simple toggle switch, on/off. It's either open or closed. I'm trying to get it to turn on the LED on my uno. The code does nothing when I upload it. I can flip the switch on/off and the serial monitor streams 0 or 1 depending on the switch position, so I know it's reading the switch. Here is the code:
/*
Turns on and off an LED
*/
// constants won't change. They're used here to
// set pin numbers:
const int RegSpng = 8; // Regular/Sponge Switch pin
const int ledPin = 13; // LED pin
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output
pinMode(RegSpng, INPUT_PULLUP); // initialize the Regular/Sponge Switch as an input
}
void loop(){
Serial.print("Switch State :");
Serial.println(digitalRead(RegSpng));
if (RegSpng == LOW){
digitalWrite(ledPin, HIGH); // turn LED on
}
else {
digitalWrite(ledPin, LOW); // turn LED off
}
}
RegSpng is always 8, it's a const for the pin itself.
You need a RegSpngVal to read it into.
/*
Turns on and off an LED
*/
// constants won't change. They're used here to
// set pin numbers:
const int RegSpng = 8; // Regular/Sponge Switch pin
const int ledPin = 13; // LED pin
int RegSpngVal;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output
pinMode(RegSpng, INPUT_PULLUP); // initialize the Regular/Sponge Switch as an input
}
void loop(){
RegSpngVal= digitalRead(RegSpng);
Serial.print("Switch State :");
Serial.print(RegSpngVal);
if (RegSpngVal == 1){
digitalWrite(ledPin, HIGH); // turn LED on
Serial.println(" h");
}
else {
digitalWrite(ledPin, LOW); // turn LED off
Serial.println(" l");
}
}
Thanks JimboZA. I know with buttons I have to check the buttons state, didn't put 2 and 2 together. Works perfect. Is there a way to mark this as solved?
To mark as solved go back to top post, select Modify, and add SOLVED to the title. (Has to be the title of the first post, since each post in a thread can have a different title.)