I'm making a digital clock display on my LCD screen but the only issue I'm having is creating an accurate read on the milliseconds without blowing up my code. I incorporated a count system so I can increase the hours, minutes, and seconds by command to match real world time. Throwing this away and attaching everything to millis() through division seems to remove any way to "set" the time. So I am looking for a way to increase a separate variable that increases exactly along with millis() but is able to subtracted from as millis() nonstop increases.
Attached is the code I wrote:
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 5, 6, 7, 8);
unsigned long time;
unsigned long period = 0;
int rate = 0;
int millisecond = 0;
int second = 0;
int minute = 0;
int hour = 0;
int x = 0;
int buttonA = 10;
bool pressedA = true;
int buttonB = 11;
bool pressedB = true;
int buttonC = 12;
bool pressedC = true;
void setup() {
lcd.begin(16, 2);
pinMode(buttonA, INPUT_PULLUP);
pinMode(buttonB, INPUT_PULLUP);
pinMode(buttonC, INPUT_PULLUP);
}
void loop() {
check();
lcd.setCursor(0, 0);
clock();
}
void clock(){
time = millis();
if (time - period >= rate){
period = time;
millisecond ++;
}
time_check();
clockprint();
}
void time_check(){
if (millisecond > 1000){
millisecond -= 1000;
}
if (second >= 60){
second -= 60;
minute ++;
}
if (minute >= 60){
minute -= 60;
hour ++;
}
if (hour >= 13){
hour -= 12;
x ++;
}
}
void hour_pad(){
if (hour < 10){
lcd.print("0");
}
}
void minute_pad(){
if (minute < 10){
lcd.print("0");
}
}
void second_pad(){
if (second < 10){
lcd.print("0");
}
}
void millisecond_pad(){
if (millisecond < 100){
lcd.print("0");
}
}
void clockprint(){
hour_pad();
lcd.print(hour);
lcd.print(":");
minute_pad();
lcd.print(minute);
lcd.print(":");
second_pad();
lcd.print(second);
lcd.print(":");
millisecond_pad();
lcd.print(millisecond);
if (x % 2 == 0){
lcd.print(" AM");
}
else{
lcd.print(" PM");
}
lcd.print(" ");
}
void check(){
if (digitalRead(buttonA) == LOW && !pressedA){
hour ++;
pressedA = true;
}
else if (digitalRead(buttonA) == HIGH){
pressedA = false;
}
if (digitalRead(buttonB) == LOW && !pressedB){
minute ++;
pressedB = true;
}
else if (digitalRead(buttonB) == HIGH){
pressedB = false;
}
if (digitalRead(buttonC) == LOW && !pressedC){
second ++;
pressedC = true;
}
else if (digitalRead(buttonC) == HIGH){
pressedC = false;
}
}