Exercise 29 - Push button
1. INTRODUCTION
On this project, you will learn how to configure a LCD screen to show how many
times is a button pressed. It is necessary to know that buttons have a little rebound
when they are pressed. This rebound makes a bad counting. You will have to
eliminate it.
Materials:
· Arduino UNO board
· Protoboard
· LCD screen (I2C)
· Button
· 10k ohms Resistor.
· Some jumpers
2. HOW TO CONNECT?
Materials:
· Arduino UNO board
· Protoboard
· Some wire Jumpers
· LCD (I2C) screen
· Button
· 10K ohms resistor
The difficulty of this project is on programming, the
connections are very simple you only have to connect the button like in
CONNECTING_A_BUTTON exercise. On the other hand, the LCD screen go connected to
5V and ground and also it go connected to I2C pins pin A4 and pin A5.
EXERCISE_A |
3. PROGRAMMING
On this exercise, it is necessary to include LiquidCrystal_I2C library.
EXERCISE_A
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Set the LCD address to 0x27 for a 16 chars and 2 line display
First, you have to declare LCD screen (see CONNECTING_A_LCD exercise), pins and variables antiReboundTime is a variable for the antiRebound function.
LiquidCrystal_I2C lcd(0x27, 16, 2);
int button = 6;
int i = 0;
int pressed = 0;
int antiReboundTime = 80;
On setup, button is set as INPUT, LCD is begun and its backlight is turned-on. On the other hand, a message is printed at the beginning of the LCD.
void setup()
{
pinMode(button, INPUT);
// initialize the LCD
lcd.begin();
// Turn on the blacklight and print a message.
lcd.backlight();
lcd.print("HELLO!");
}
On loop, antiRebound function is implemented and its Boolean value is saved on pressed variable. If this value equals to TRUE “i” is incremented one by one. Secondly, the number of times that the button is pressed, is printed in LCD screen.
void loop()
{
pressed = antiRebound(button);
if (pressed == HIGH) {
i = i + 1;
}
lcd.setCursor(0, 1);
lcd.print(" ");//Print 16 spaces to Erase row
lcd.setCursor(0, 1);
lcd.print(i);
lcd.print("==>TIMES");
}
The antiRebound function returns a Boolean value and need to receive a number of pin. Inside it, variables are declared and the button is read. If the state == lastState the counter is incremented one by one then while compare counter value with antiReboundTime and if it is smaller returns state.
boolean antiRebound( int pin) {
int counter = 0;
boolean state;
boolean lastState;
do {
state = digitalRead(pin);
if (state != lastState) {
counter = 0;
lastState = state;
}
else {
counter = counter + 1;
}
delay(1);
}
while (counter < antiReboundTime);
return state;}