我有这个代码应该在LCD屏幕的第一行显示一个时钟,以及文本" Hello World"在第二行:
#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 :(得分:3)
代码溢出capacity of an int [对于arduino,该值为+/- 32767]:
int secspassed()
{
x = initialHours*3600;
x = x+(initialMins*60);
此时x应为:
14 * 3600 * 60 = 3024000
比int可以容纳的+32767值大得多,并且溢出被丢弃,留下代表一些无关的位。
还应该用int清理调用print例程并将其转换为字节。
答案 1 :(得分: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。