Go Down

Topic: Using the if statement with a time delay (Read 793 times) previous topic - next topic


I am am familiar with the StateChangeDetection but I do not think it.

And you would be incorrect. You don't care about the switches state, you just want to know when it is pressed (or released); that's what the StateChangeDetection example shows. Here is a simple example that demonstrates how it can be used to record the time between events:

Code: [Select]
const int switchPin = 8;
int lastSwitchReading = HIGH;
unsigned long lastPressedTime = 0;

void setup()

  pinMode(switchPin, INPUT_PULLUP);

void loop()

  int currentReading = digitalRead(switchPin);

  if (currentReading == LOW && lastSwitchReading == HIGH)
    Serial.print("Time between presses: ");
    Serial.println(millis() - lastPressedTime);
    lastPressedTime = millis();
    lastSwitchReading = currentReading;


Thank you both Henry and  Arrch for your help however I feel like I should have better explained my problem. You see, I need to write a code in which if in the first if statement is high, and the second one is also high, to turn on a LED. If the first statement is high but the second is low, to turn on an other Led. I am am familiar with the StateChangeDetection but I do not think it applies to this case so I tried to do it with the if statement. I apologies for not having well explained the situation but I still haven't figured out what the problem is.

When you can explain precisely (to us and to yourself) what you want your sketch to do, you'll know what the problem is. Until then, we're all just guessing.

Go Up