2012-08-31 98 views
0

我有這樣的代碼,應該在LCD屏幕的第一行顯示一個時鐘,並在第二行文本「Hello World」:Arduino的LCD時鐘不工作

#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()); 
} 

而不是打印以下

12:35:15 
Hello World 

它打印此相反:

253:255:243 
Hello World 

爲什麼?

我不想使用時間庫,BTW。

+0

如果你打電話給millis()會打印出什麼? – CBredlow

+0

代碼上傳以來的毫秒數。 – Cinder

回答

3

的代碼溢出capacity of an int [用於Arduino的,該值是+/- 32767]這裏:

int secspassed() 
{ 
    x = initialHours*3600; 
    x = x+(initialMins*60); 

在這點x應該是:

14 * 3600 * 60 = 3024000 

其比int可以保持的+32767值大得多,並且溢出被丟棄,留下代表許多不相關的位。

還應該清理使用int調用打印例程並將其轉換爲字節。

1

我剛剛解決了爲什麼這將是一個壞主意,與rollovers和東西。以下是感興趣的人的更新代碼:

#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); 
} 

玩得開心!

P.S .:有關更新的代碼,請轉至my blog