【问题标题】:Arduino, displaying time, temperature and the humidityArduino,显示时间、温度和湿度
【发布时间】:2018-05-02 20:11:56
【问题描述】:

我正在 Arduino Uno 上制作一个数字时钟项目。我被要求做的事情是在不使用 RTC 模块的情况下制作一个显示在 LCD 上的数字时钟。但我还想添加一些东西,例如 DHT11 温度和湿度传感器。我想在第一行显示 TIME:HH:MM:SS,在第二行我想显示 TEMP(*C):XX.YY,稍等片刻,清除第二行(我使用空白空格),然后显示 HUM(%):XX.YY。不断地。我只是想将第二行延迟 2 秒,同时从温度更改为湿度,以便清楚地查看温度和湿度值。但它会延迟整个系统,并且时间值也随着延迟时间而消失。我只希望时钟一直显示并分别显示温度和湿度。这是我下面的代码:

#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
#include <dht.h>
#define dht_apin   2
LiquidCrystal_I2C lcd(0x27, 16, 2);
dht DHT;  
int h=14; //hour
int m=50; //minute
int s=20; //second
int flag; 
int TIME; 
const int hs=8; 
const int ms=9; 
void setup()
{
lcd.begin();
lcd.backlight();
}

void loop() 
{ 
delay(1000);
lcd.setCursor(0,0); 
s=s+1;  
lcd.print("TIME:");
lcd.print(h); 
lcd.print(":"); 
lcd.print(m); 
lcd.print(":"); 
lcd.print(s);     
delay(400);
if(flag==24)flag=0; 
delay(1000); 
lcd.clear(); 
if(s==60){ 
 s=0; 
 m=m+1; 
} 
if(m==60) 
{ 
 m=0; 
 h=h+1; 
 flag=flag+1; 
}        

//Temperature and humidity
DHT.read11(dht_apin);
lcd.setCursor(0,1);
lcd.print("TEMP(*C):");  
lcd.print(DHT.temperature);
delay(2000);
lcd.setCursor(0,1);
lcd.print(' '); 
lcd.setCursor(0,1);
lcd.print("HUM(%):"); 
lcd.print(DHT.humidity); 
delay(1000); 
} 

谢谢!

【问题讨论】:

  • 查看如何使用计时器。每次调用 delay 函数时,您都会阻塞其他所有内容,因此时间会停止。

标签: arduino arduino-uno


【解决方案1】:

正如 DigitalNinja 所说,delay 正在阻止一切。如果你想保持运行,你必须使用中断。

中断停止执行代码以跳转到循环外的特定函数。它不会像delay 那样阻塞时钟。一切都在运行,但你基本上只是在需要时插入你的函数,基于外部事件(引脚上升,时间流逝......)

您可以使用Timer1 库每 X 秒执行一次操作。或者使用attachInterrupt 创建您自己的系统。

我在 TimerOne 参考页面中拿了这个例子并评论了它

void setup()
{
  // Your variables here
  // ...

  Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
  Timer1.attachInterrupt(callback);  // attaches callback() as the function to call when Timer is done
}

void callback()
{
  // Do your thing when Timer is elapsed
  // The timer goes automatically to zero. You don't need to reset it.
}

void loop()
{
  // your program here...
  // You never need to call callback() function, it is called WHEN Timer is done
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    相关资源
    最近更新 更多