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.



void setup() {
pinMode(2, INPUT);
pinMode(8, OUTPUT);

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

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

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

currentState = digitalRead(input);
if(currentState = LOW){
output = LOW;
done = true;
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)

if(currentState = LOW){

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

More information:

Welcome to the forum.

Please read the post at the start of any forum , entitled "How to use this Forum".
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: