counter reset problem

im writing a sketch to monitor an appliance in my house. i want to count how often it turns on during the day and how long it runs for. im slowly trying to figure out the programming side of things. my current issue is that i have a counter that increments by 1 every time a button is pushed. i aslo tried to program a reset feature for the counter, but it doesn't seem to work? when i push the reset button it prints 0 (for debugging) but then the counter continues where it left off never reseting back to zero?

const int switchPin = 2;                 // number of input pin
const int resetPin = 3;                  // increment reset

long startTime;        //value returned from millis when switch is pressed
long duration;        //variable to store duration
long seconds;       // variable to store seconds
long minutes;        // variable to store minutes
long counter;       // variable to store number of times switch is pressed
void setup()
{
  pinMode(switchPin, INPUT);
  digitalWrite(switchPin, HIGH);    //turn on pull up resistor
  pinMode(resetPin, INPUT);
  digitalWrite(resetPin, HIGH);     //turn on pull up resistor
  Serial.begin(9600);
  long counter = 0;
}

void loop()
{
  if(digitalRead(resetPin)==LOW)
  {
    long counter = 0;
    Serial.println(counter);
  }

  if(digitalRead(switchPin) == LOW)
 
{ 
  startTime = millis();
  while(digitalRead(switchPin) == LOW);
  long duration = millis() - startTime;
  long seconds = (duration / 1000) % 60;  // convert milliseconds to seconds
  Serial.print("s ");
  Serial.println(seconds);
  long minutes = (duration / 60000) % 60;  //convert milliseconds to minutes
  Serial.print("m ");
  Serial.println(minutes);
  counter++;
  Serial.println(counter);
}
}
  /code]

but it doesn't seem to work?

in that way - look in the playground for de-bouncing.

Mark

Your counter is resetting, consider how fast things are happening.
while(digitalRead(switchPin) == LOW); <<<< do you really want this ; here?

Look at the Bounce library also to make your switches more functional.

i will try debouncing, but my counter goes 1,2,3,4 then i hit reset it prints 0 then the next increment is 5 when it should be back to one. i dont see how switch bounce would cause this?

  if(digitalRead(resetPin)==LOW)
  {
    long counter = 0;
    Serial.println(counter);
  }

You are declaring a new variable called counter inside the if statement. Get rid of the bit that says "long "


In fact you are doing the same thing in the setup() function:

void setup()
{
...
  long counter = 0;
}

In both cases you are creating new local variables instead of using your global one.

Tom,
that was the problem! thanks for the help. i was starting to pull my hair out :fearful: