I'm new to Arduino and my question is rather theoretical. I have an Arduino Nano board (Atmega168 processor), a button, a display. I have written a button handler that does not stop code execution. My idea is: poll the button in "loop" cycle, and if it is pressed, perform k++. When k exceeds a specified value, perform cnt++ and print it on the display.
Code example №1 works correctly. I get 1 -> 2 -> 3 -> ...:
void loop() {
if (digitalRead(button_pd) == LOW) {
k = k + 1;
if (k >= 20) {
k = 0;
cnt = cnt + 1;
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(cnt);
}
}
Code example №2 is incorrect. I get 16 -> 27 -> 40 -> ... Seems like not cnt is printed, but k.
void loop() {
if (digitalRead(button_pd) == LOW) {
k = k + 1;
if (k >= 20) {
k = 0;
cnt = cnt + 1;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(cnt);
}
}
}
Here's my program:
#include <LiquidCrystal_I2C.h>
#define button_pd 6
LiquidCrystal_I2C lcd(0x27, 16, 2);
int k = 0;
int cnt = 0;
void setup() {
pinMode(button_pd, INPUT_PULLUP);
lcd.init();
lcd.backlight();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(cnt);
}
void loop() {
// button handler
}
My question is. Why examples №1 and №2 work differently?