Reputation: 1609
I have this code that should display a clock on the first line of an LCD screen, and the text "Hello World" on the second line:
#include <LiquidCrystal.h>
int x=0;
int a=0;
int y=0;
int z=0;
int initialHours = 14;//set this to whatever
int initialMins = 37;
int initialSecs = 45 + 11;
int secspassed()
{
x = initialHours*3600;
x = x+(initialMins*60);
x = x+initialSecs;
x = x+(millis()/1000);
return x;
}
int hours()
{
y = secspassed();
y = y/3600;
y = y%24;
return y;
}
int mins()
{
z = secspassed();
z = z/60;
z = z%60;
return z;
}
int secs()
{
a = secspassed();
a = a%60;
return a;
}
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
void setup(){
lcd.print("load...");
delay(1000);
lcd.begin(16, 2);
lcd.setCursor(0, 1);
lcd.print("Hello world");
}
void loop(){
digitalClockDisplay();
}
void printDigits(byte digits){
if(digits < 10)
lcd.print('0');
lcd.print(digits);
}
char sep()
{
x = millis()/1000;
if(x%2==0)
{
lcd.print(":");
}
else {
lcd.print(" ");
}
}
void digitalClockDisplay(){
lcd.setCursor(0,0);
printDigits(
hours());
sep();
printDigits(mins());
sep();
printDigits(secs());
}
Instead of printing the following
12:35:15
Hello World
it prints this instead:
253:255:243
Hello World
Why?
I don't want to use the Time library, BTW.
Upvotes: 0
Views: 1867
Reputation: 1609
I've just worked out why it would be a bad idea, with rollovers and stuff. Here is the updated code for interested people:
#include <LiquidCrystal.h>
int second=0, minute=0, hour=0;
int x=0;
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
void setup(){
lcd.print("load...");
delay(1000);
lcd.begin(16, 2);
lcd.setCursor(0, 1);
lcd.print("Hello, world ");
}
void loop(){
static unsigned long lastTick = 0;
if (millis() - lastTick >= 1000) {
lastTick = millis();
second++;
}
// Move forward one minute every 60 seconds
if (second >= 60) {
minute++;
second = 0; // Reset seconds to zero
}
// Move forward one hour every 60 minutes
if (minute >=60) {
hour++;
minute = 0; // Reset minutes to zero
}
if (hour >=24) {
hour=0;
minute = 0; // Reset minutes to zero
}
digitalClockDisplay();
}
void printDigits(byte digits){
if(digits < 10)
lcd.print('0');
lcd.print(digits);
}
char sep()
{
x = millis()/500;
if(x%2==0)
{
lcd.print(":");
}
else{
lcd.print(" ");
}
}
void digitalClockDisplay(){
lcd.setCursor(0,0);
printDigits(hour);
sep();
printDigits(minute);
sep();
printDigits(second);
}
Have fun!
P.S.: for the updated code, go to my blog.
Upvotes: 1
Reputation: 1655
The code is overflowing the capacity of an int [for arduino, that value is +/- 32767] here:
int secspassed()
{
x = initialHours*3600;
x = x+(initialMins*60);
At this point x should be:
14 * 3600 * 60 = 3024000
which is much bigger than the +32767 value an int can hold, and the overflow is dropped, leaving bits that represent a number of no relevance.
Should also cleanup calling the print routine with an int and casting it to a byte.
Upvotes: 3