Hi,
I am a novice programmer and am having an issue with a variable being reinitialized each time through the loop in the code below. The code is supposed to take a temperature measurement from a temperature sensor and enter 1 of the 4 IF statements based on certain conditions being met. It would then spin a small fan motor for a certain period of time. The problem I am having is with the RS variable. I declared it as a global variable (i.e. outside of the loop) and it should start with a value of 0. The code runs through the IF statement conditions and always enters the 3rd IF statement. After spinning the motor in the 3rd IF statement it is supposed to change the value of RS to 1. I then print the value of RS on the screen, and indeed it has changed to 1. However, upon the next run through the loop the code enters the 3rd IF statement again even though the condition to enter that IF statement is that RS needs to be 0. Somehow, the RS variable is being reinitialized to 0 each time the loop runs. Please take a look below and provide any guidance. Thanks for your help.
int ST = 30;
int Mode = 1;
int RS;
void setup()
{
Serial.begin(9600);
#define CW 0
#define CCW 1
pinMode(3, OUTPUT);
pinMode(12, OUTPUT);
digitalWrite(3, LOW);
digitalWrite(12, LOW);
}
void loop()
{
int reading = analogRead(0);
float voltage = reading * 5.0;
voltage /= 1024.0;
float tC = (voltage - 0.5) * 100;
Serial.print(RS);
if ((tC > (ST + 0.5)) && Mode == 1 && RS == 1)
{
//DO SOMETHING
Serial.println(" If Statement A ")
}
else if ((tC > (ST + 0.5)) && Mode == 0 && RS == 0)
{
//DO SOMETHING ELSE
Serial.println(" If Statement B ")
}
else if ((tC < (ST - 0.5)) && Mode == 1 && RS == 0)
{
digitalWrite(12, CW);
analogWrite(3, 250);
delay(1000);
analogWrite(3, 0);
int RS = 1;
Serial.print(RS);
Serial.println(" If Statement C ");
}
else if((tC < (ST - 0.5)) && Mode == 0 && RS == 1)
{
//DO SOMETHING ELSE
Serial.println(" If Statement D ")
}
}