How do i get this to only say button pushed once when switch pin is low and only print the tim ewhen it retuns to low?
const int switchPin = 2; // the number of the input pin
long startTime; // store starting time here
long duration; // variable to store how long the timer has been running
float secduration; // variable to store the duration in seconds
void setup() {
// put your setup code here, to run once:
pinMode(switchPin, INPUT_PULLUP);
Serial.begin(9600);
}
const int switchPin = 2; // the number of the input pin
long startTime; // store starting time here
long duration; // variable to store how long the timer has been running
float secduration; // variable to store the duration in seconds
byte butLst;
void setup() {
// put your setup code here, to run once:
pinMode(switchPin, INPUT_PULLUP);
butLst = digitalRead (switchPin);
Serial.begin(9600);
}
void loop() {
unsigned long msec = millis ();
byte but = digitalRead(switchPin);
if (butLst != but) {
if (LOW == but) {
startTime = msec;
}
else {
secduration = (msec - startTime) / 1000.;
Serial.print("Button released after ");
Serial.print(secduration);
Serial.println(" seconds");
}
butLst = but;
delay (10); // debounce
}
}
Read the forum guidelines. Post your test code in code tags. Use the IDE autoformat tool (ctrl-t or Tools, Auto Format) to indent the code for readability before posting code.
const int switchPin = 2; // the number of the input pin
long startTime; // store starting time here
long duration; // variable to store how long the timer has been running
float secduration; // variable to store the duration in seconds
//--------------------------------------------------------
void setup() {
pinMode(switchPin, INPUT_PULLUP);
Serial.begin(9600);
}
//--------------------------------------------------------
void loop() {
if (digitalRead(switchPin) == LOW)
{
Serial.println("Button Pushed");
startTime = millis();
while (digitalRead(switchPin) == LOW){}
duration = (millis() - startTime);
secduration = (float)duration / 1000;
Serial.print("Button released after ");
Serial.print(secduration);
Serial.println(" seconds");
}
}