Go Down

Topic: Program initializing a variable with 1 even when 0 is mentoned (Read 338 times) previous topic - next topic



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);

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

digitalWrite(ledPin, ledState);

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.


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?
Johannesburg hams call me: ZS6JMB on Highveld rep 145.7875 (-600 & 88.5 tone)
Dr Perry Cox: "Help me to help you, help me to help you...."
Your answer may already be here: https://forum.arduino.cc/index.php?topic=384198.0

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131