Hi,
I’m new to Arduino (and C) programming and sure I’m making a basic error, but I’m stuck. I have 2 momentary switches - whichever one was pushed last should change the RED/GREEN LED output (in this cut down example). It reads the buttons correctly (using the onboard LED as a test) but when I try to use a variable to remember the ‘state’ set by the last button pressed the variable is reset to “1” every loop. I have defined the variable as global and also as a static variable (I think) but it makes no difference.
Any suggestions?
Many thanks
Roger
const int P2_Red_LED = 2;
const int P2_Green_LED = 3;
const int ledPin = 13;
const int Give_to_Red = 15; // (A1)
const int Return_to_Green = 16; // (A2)
int Give_to_Red_State;
int Return_to_Green_State;
static int P2_Control = 0;
void setup()
{
pinMode(Give_to_Red, INPUT_PULLUP);
pinMode(Return_to_Green, INPUT_PULLUP);
pinMode(P2_Red_LED, OUTPUT);
pinMode(P2_Green_LED, OUTPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(P2_Red_LED, LOW);
digitalWrite(P2_Green_LED, HIGH);
digitalWrite(ledPin, LOW);
}
void loop()
{
Give_to_Red_State = digitalRead(Give_to_Red);
Return_to_Green_State = digitalRead(Return_to_Green);
if ( Return_to_Green_State == LOW )
{
P2_Control = 0;
digitalWrite(ledPin, LOW); // works correctly
}
if ( Give_to_Red_State == LOW )
{
P2_Control = 1;
digitalWrite(ledPin, HIGH); // works correctly
}
// P2_Control = 0 at this point when "Return_to_Green_State" is LOW
if (P2_Control = 1 ) // code enters the first part of the if statement even when
// P2_Control = 0 as noted above
{
digitalWrite(P2_Red_LED, HIGH);
digitalWrite(P2_Green_LED, LOW);
}
else
{
digitalWrite(P2_Red_LED, LOW);
digitalWrite(P2_Green_LED, HIGH);
}
}