Button state change help

im trying to understand how to work with a button. i want an led to turn on after one press and remain one untill i press the button again.

here is a button state change code but im having issues understanding parts of it. could someone explain what buttonstate!+lastbuttonstate and

what these mean: buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);

/*
  State change detection (edge detection)
    
 Often, you don't need to know the state of a digital input all the time,
 but you just need to know when the input changes from one state to another.
 For example, you want to know when a button goes from OFF to ON.  This is called
 state change detection, or edge detection.
 
 This example shows how to detect when a button or button changes from off to on
 and on to off.
    
 The circuit:
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground
 * LED attached from pin 13 to ground (or use the built-in LED on
   most Arduino boards)
 
 created  27 Sep 2005
 modified 30 Aug 2011
 by Tom Igoe

This example code is in the public domain.
    
 http://arduino.cc/en/Tutorial/ButtonStateChange
 
 */

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 13;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
}


void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button
      // wend from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    } 
    else {
      // if the current state is LOW then the button
      // wend from on to off:
      Serial.println("off"); 
    }
  }
  // save the current state as the last state, 
  //for next time through the loop
  lastButtonState = buttonState;

  
  // turns on the LED every four button pushes by 
  // checking the modulo of the button push counter.
  // the modulo function gives you the remainder of 
  // the division of two numbers:
  if (buttonPushCounter % 4 == 0) {
    digitalWrite(ledPin, HIGH);
  } else {
   digitalWrite(ledPin, LOW);
  }
  
}

Moderator edit:
</mark> <mark>[code]</mark> <mark>

</mark> <mark>[/code]</mark> <mark>
tags added.

its pretty simple once you grasp it

you read a button using digital read at the start of each looop, which is happening millions of times per second

buttonState = digitalRead(buttonPin);

at the end of the loop (as far as the button is concerned) you set the variable lastButtonState to whatever the button read

so if the button is up at the beginning of the loop and at the end of the loop, nothing has changed right? when you press the button, the reading at the beginning of the loop says down, but last button says it was up, so you now know that the state of the button has changed.

im sorry i wrote that wrong i understand what button state normall means but what does if (buttonState != lastButtonState)

Hi....

!= is a test for "not equal to", so if (buttonState != lastButtonState) is checking to see if the button's state has changed since the last time through loop()

(Read about it here)

Then, if it has changed, it checks to see if it's HIGH, which means it was pressed and so it increments the counter and reports that to the monitor. If it has changed and is LOW though, it means it was released and it reports the fact that it's now off

If it hasn't changed, then nothing happens....

then all this id just taking about the button counter?

buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);

also it explains that this function is the remainer of the division of two numbers, could someone clarify this? if (buttonPushCounter % 4 == 0)

The ++ is how C increments a variable- read about it here, so buttonPushCounter++; just increases the count by one.

Then the lines Serial.println("on"); and Serial.print("number of button pushes:  "); print the text in quotes to the monitor.

Lastly, the line Serial.println(buttonPushCounter); prints the value of the counter (it has no quotes, so it sends the value, not the actual words).

The % function is called the modulo, read about it here. It returns the remainder when the first number is divided by the second. The sketch wants the led to go on every 4 clicks, so it looks for the remainder of when the counter is divided by 4. If the remainder is 0, then the counter is on 4, 8, 12 etc and so there have been 4 clicks and the led goes on. If it was on say 2 clicks, the remainder would be 2, or if it was on say 15 clicks the remainder would be 3 and so is not a multiple of 4 and the led should not be switched on.

One form of button toggle code.

//zoomkat LED button toggle test 11-08-2012

int button = 5; //button pin, connect to ground as button to toggle LED
int press = 0;
boolean toggle = true;

void setup()
{
  pinMode(13, OUTPUT); //LED on pin 13
  pinMode(button, INPUT); //arduino monitor pin state
  digitalWrite(5, HIGH); //enable pullups to make pin 5 high
}

void loop()
{
  press = digitalRead(button);
  if (press == LOW)
  {
    if(toggle)
    {
      digitalWrite(13, HIGH);   // set the LED on
      toggle = !toggle;
    }
    else
    {
      digitalWrite(13, LOW);    // set the LED off
      toggle = !toggle;
    }
  }
  delay(500);  //delay for debounce
}

only the most recent post mentioned switch bounce.

"Bounce" happens on a mechanical switch, as it changes from one state to the other.

As the switch begins to make or break the contact, it's usually not one single transition. That's just the nature of mechanical connections. The switch will alternate between "high" and "low" many times, because the mechanical contact isn't perfect. Eventually, it will "settle" into its new state. Typically, that will take a few milliseconds, or thousandths of a second.

Since the Arduino board may read the switch input millions of times each second, Arduino can read the input many times while the mechanical switch is in the process of changing. Arduino will often read many transitions, maybe hundreds of transitions, for a single press or release.

When you're trying to create a "Push on - push off" function, you only want to read one transition each way. This is called debounce. It can be done in hardware or software. Conceptually, what you do is limit the number of times the switch can change states in a period of time. Obviously, a human cannot press/release a button millions of times per second, because we can't move that fast. Debounce is just waiting a period of time until the switch becomes stable - the same status is read several times in a row, over a reasonable period of time. Then return one result for the new state of the button, after it has "settled" again.

Here's a nice tutorial about debounce. Its about 15 minutes long.

zoomkat's 500ms debounce time may be a little too long, making the button seem sluggish. Most button debounce times are in the 10ms - 50ms range, allowing between 20-100 keypresses/releases per second.

the code above naturally debounces the input

True as long as the "Serial.print" statements remain, but if they're removed there's no debounce provided. Debouce in the example is a lucky side-effect, not properly designed and planned.

JimboZA:
The ++ is how C increments a variable- read about it here, so buttonPushCounter++; just increases the count by one.

Then the lines Serial.println("on"); and Serial.print("number of button pushes:  "); print the text in quotes to the monitor.

Lastly, the line Serial.println(buttonPushCounter); prints the value of the counter (it has no quotes, so it sends the value, not the actual words).

The % function is called the modulo, read about it here. It returns the remainder when the first number is divided by the second. The sketch wants the led to go on every 4 clicks, so it looks for the remainder of when the counter is divided by 4. If the remainder is 0, then the counter is on 4, 8, 12 etc and so there have been 4 clicks and the led goes on. If it was on say 2 clicks, the remainder would be 2, or if it was on say 15 clicks the remainder would be 3 and so is not a multiple of 4 and the led should not be switched on.

so serial.print is just sending data to lets say a 16x2 lcd screen? also if i wanted to make the led turn on every 2 clicks the function would be (buttonPushCounter% 2==0 )??

Serial.print sends the output to the standard serial monitor. Serial.println does the same but adds a carriage return/line feed at the end to move to the next line.

Yes, (buttonPushCounter% 2==0 ) would be true after 2 clicks so would toggle the LED

ok now i got it, for some reason i didnt have a delay at the end of the code and my led was acting up, but with a delay(100) its turning on every two clicks.

how would i make the led blink, where in the code would i add the delay?

turtlesoup2:
so serial.print is just sending data to lets say a 16x2 lcd screen?

No, it sends data to the monitor, which is part of the Arduino IDE- Control+Shift+M - and is explained here.

The "Hello World" example explains how to use an LCD.

Now, may I make a suggestion.... every command you are likely to encounter in the Tutorial examples is explained here in the Reference. (I'm guessing you got the button push counter sketch from the tutorial page in the first place?)

You'll learn far better if you look up each command in the reference and try to understand it before hopping onto the forum asking "What does xyz do?"

Jim

sorry for the confusion, as i am new and yes after reading those articles things are clearing up for me now.