#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
const int pinInicio = 2;
const int pinFim = 3;
const int pinMelhor = 10;
unsigned long tempoInicio = 0;
unsigned long tempoAtual = 0;
unsigned long tempoAnterior = 0;
unsigned long melhorTempo = 0;
bool cronometrando = false;
bool mostrandoMelhor = false;
bool estadoBotaoMelhorAnt = HIGH;
unsigned long ultimoTempoExibido = 999999;
bool ultimoEstadoCron = false;
bool ultimaTelaMelhor = !mostrandoMelhor;
void setup() {
pinMode(pinInicio, INPUT_PULLUP);
pinMode(pinFim, INPUT_PULLUP);
pinMode(pinMelhor, INPUT_PULLUP);
lcd.begin(16, 2);
lcd.clear();
}
void formatarTempo(unsigned long milissegundos, char* buffer) {
unsigned long totalDecimos = milissegundos / 100;
unsigned int decimos = totalDecimos % 10;
unsigned int segundos = (totalDecimos / 10) % 60;
unsigned int minutos = (totalDecimos / 600) % 100;
sprintf(buffer, "%02u:%02u:%1u", minutos, segundos, decimos);
}
void loop() {
bool btnInicioApertado = (digitalRead(pinInicio) == LOW);
bool btnFimApertado = (digitalRead(pinFim) == LOW);
bool btnMelhorAtual = digitalRead(pinMelhor);
if (estadoBotaoMelhorAnt == HIGH && btnMelhorAtual == LOW) {
mostrandoMelhor = !mostrandoMelhor;
delay(200);
}
estadoBotaoMelhorAnt = btnMelhorAtual;
if (btnInicioApertado && !cronometrando) {
cronometrando = true;
tempoInicio = millis();
}
if (cronometrando) {
tempoAtual = millis() - tempoInicio;
}
if (btnFimApertado && cronometrando) {
cronometrando = false;
tempoAnterior = tempoAtual;
if (melhorTempo == 0 || tempoAnterior < melhorTempo) {
melhorTempo = tempoAnterior;
}
}
if (mostrandoMelhor != ultimaTelaMelhor ||
(mostrandoMelhor && melhorTempo != ultimoTempoExibido) ||
(!mostrandoMelhor && (cronometrando != ultimoEstadoCron || (cronometrando && tempoAtual / 100 != ultimoTempoExibido)))) {
ultimaTelaMelhor = mostrandoMelhor;
ultimoEstadoCron = cronometrando;
if (mostrandoMelhor) {
ultimoTempoExibido = melhorTempo;
lcd.setCursor(0, 0);
lcd.print("Melhor volta ");
lcd.setCursor(0, 1);
char bufMelhor[10];
formatarTempo(melhorTempo, bufMelhor);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print(bufMelhor);
} else {
lcd.setCursor(0, 0);
if (cronometrando) {
ultimoTempoExibido = tempoAtual / 100;
char bufAtual[10];
formatarTempo(tempoAtual, bufAtual);
lcd.print(" ");
lcd.setCursor(0, 0);
lcd.print(bufAtual);
} else {
lcd.print(" ");
}
lcd.setCursor(0, 1);
char bufAnterior[10];
formatarTempo(tempoAnterior, bufAnterior);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print(bufAnterior);
}
}
}Menor Tempo
Inicia
Fim