Pages: [1]   Go Down
Author Topic: Program initializing a variable with 1 even when 0 is mentoned  (Read 219 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 1
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
const int switchPin = 26;
const int ledPin = 10;

int state;
int lastState;
int ledState;
int pressCounter = 0;

void setup()
{
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  state = digitalRead(switchPin);
  
  if(state != lastState)
  {
    if(state == HIGH)
    {
      pressCounter += 1;
      Serial.println(pressCounter);
    }
    else
    {//Do nothing
    }
    lastState = state;
  }
  
  if(pressCounter % 5 == 0)
  {
    ledState = HIGH;
    Serial.println("Hurray! You've pressed 5 times");
  }
  else
  {
    ledState = LOW;
  }

digitalWrite(ledPin, ledState);
delay(20);
}
 
        


The pressCounter variable is always getting initialized with 1 even when I have specified the initial value to be 0. Where am I going wrong?
This program turns on an led when the switch is pressed five times.
Logged

Johannesburg. UTC+2
Offline Offline
Faraday Member
**
Karma: 105
Posts: 4672
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Well the first time you print pressCounter is after you increment it.... why not put a print in setup() so you can verify that it starts out as 0?
Logged

The Elders of the Internet know who I am
I'm on LinkedIn: http://www.linkedin.com/in/jimbrownza

Pages: [1]   Go Up
Jump to: