I'm still new to arduino and have run into a problem I'm stuck on. When trying to run the following code, it isn't recognizing the int val, and seems to just be using the if statement regardless of how I write the code. What have I missed?
int redPin = 13; // choose the pin for the Red LED
int yellowPin = 12; //Yellow LED
int greenPin = 8; //Green LED
int inPin = 7; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
void setup() {
pinMode(redPin, OUTPUT); // declare LED as output
pinMode(greenPin, OUTPUT);
pinMode(inPin, INPUT); // declare pushbutton as input
}
void loop(){
val = digitalRead(inPin); // read input value
if (val == HIGH) { // check if the input is HIGH (button released)
digitalWrite(redPin, LOW); // turn LED OFF
digitalWrite(greenPin, HIGH);
} else {
digitalWrite(redPin, HIGH); // turn LED ON
digitalWrite(greenPin, LOW);
}
}
If it's an issue with my setup, here is an image of it from tinkercad
Although the code can use some tips (I will post a "corrected" version alter) I don't see anything "wrong". But then again, you didn't really explain what does happen either.
//Pin definitions
////Call it what it is :) If the variable name explains it all ou need less comments
////Use smallest possible variable type, for pins => byte
////const for variables that will not change on runtime
const byte RedLedPin = 13;
const byte YellowLedPin = 12;
const byte GreenLedPin = 8;
const byte ButtonPin = 7; //connected to GND
void setup(){
pinMode(RedLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
////this way you don't need an external resistor :)
pinMode(ButtonPin, INPUT_PULLUP);
}
void loop(){
////Declare the variable only where you need it (aka local)
////Bonus: const because it will not change during a single loop
const bool Val = digitalRead(inPin);
// check if the button is released
if (Val == HIGH) {
digitalWrite(RedLedPin, LOW);
digitalWrite(GreenLedPin, HIGH);
}
//or button pressed
else {
digitalWrite(RedLedPin, HIGH);
digitalWrite(GreenledPin, LOW);
}
}
////Indicate comments for leaning now but I would not add normally
// for normal comments
Check your LEDs are the right way round: maybe their pins are going high but if they're back to front they wont turn on.
Put a Serial.begin(9600); in setup() and then do some debug printing to the monitor:
if (Val == HIGH) { //or val if you don't change it to Val ;)
Serial.println("in the if");
digitalWrite(RedLedPin, LOW);
digitalWrite(GreenLedPin, HIGH);
}
//or button pressed
else {
Serial.println("in the else");
digitalWrite(RedLedPin, HIGH);
digitalWrite(GreenledPin, LOW);
}