Search code examples
if-statementarduinocounterarduino-unolcd

Restart a pushbutton counter


I have to do two counters with Arduino and show it on an LCD. But counters have to restart when they reach 99.

I've done this:

#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

int boton_user = 0;
int boton_admin = 1;

int user_actual = 0;
int user_antes = 1;
int admin_actual = 0;
int admin_antes = 1;

int num_actual = 0;
int num_ultimo = 0;

void setup() {
  lcd.begin(16, 2);
  pinMode(boton_user, INPUT);
  pinMode(boton_admin, INPUT);
}

void loop() {
  user_actual = digitalRead(boton_user);

  if(user_actual != user_antes) {
    if(user_actual == HIGH) {

      if(num_ultimo == 99) {
        num_ultimo = 1;
      }else{
        num_ultimo = num_ultimo + 1;
      }
    }
    user_antes = user_actual;
  }

  admin_actual = digitalRead(boton_admin);

  if(admin_actual != admin_antes) {
    if(admin_actual == HIGH && num_actual < num_ultimo) {

      if(num_actual == 99) {
        num_actual = 1;
      }else{
        num_actual = num_actual + 1;
      }
    }
    admin_antes = admin_actual;
  }

  lcd.setCursor(0, 0);
  lcd.print("Siguiente: ");
  lcd.print(num_actual);
  lcd.setCursor(0, 1);
  lcd.print("Ultimo: ");
  lcd.print(num_ultimo);
}

But when any number reaches 99, it will only change the first 9 (97, 98, 99, 19, 29, 39, 49, 59, 69, 79, 89, 99...) and the second time it reaches 99 it will change to 10 and start again (...10, 11, 12...97, 98, 99, 19, 29...).

I'm not sure what I'm doing wrong.


Solution

  • You overwrite Siguiente: 99 with Siguiente: 1 and you get Siguiente: 19, because the last character is kept.

    Call lcd.clear(), before you update the LCD.