Function Variable Scope

I’m trying to create a function which is similar to PLC block function TON. The issue I’m having is that the local variables declared in the function do not transfer all the way through the body of the function.

For example:

If I put Serial.println(CurrentState); directly after currentState = digitalRead(input); I can see the value of current state change to high when I press the input button.

However if I put Serial.println(CurrentState); on any line of the function further down than that, it always reads “0” and causes the prevTime value to never update and the return of the function is always “1”.

I’m still troubleshooting this but meanwhile anyone with useful input will be much appreciated.

Thanks,

Nick

void setup() {
pinMode(2, INPUT);
pinMode(8, OUTPUT);
Serial.begin(9600);

for(int i =0; i < 3; i++) {
digitalWrite(8, HIGH);
delay(100);
digitalWrite(8, LOW);
delay(100);
}
}

void loop() {
digitalWrite(8, TON(2, 1000));
}

int TON(int input, unsigned long timer){
bool done;
int currentState, prevState, output;
unsigned long prevTime;

do{
currentState = digitalRead(input);
if(currentState = LOW){
output = LOW;
done = true;
}
Serial.println(currentState);
if(currentState != prevState){
prevTime = millis();
}
if((millis()-prevTime) > timer){
output = HIGH;
done = true;
}
prevState = currentState;
} while(done != true);
return output;
}

TON_Function.ino (846 Bytes)

NRobinson2:
if(currentState = LOW){

You used the assignment operator (=) instead of the comparison operator (==) here.

More information:

Hi,
Welcome to the forum.

Please read the post at the start of any forum , entitled "How to use this Forum".
OR
http://forum.arduino.cc/index.php/topic,148850.0.html.
Then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Thanks.. Tom.. :slight_smile: