0
votes

i'm making a digital clock project on Arduino Uno. The thing i'm asked to do is making a digital clock that is being displayed on a LCD without using the RTC module. But i wanted to add some things such as a DHT11 temperature and humidity sensor as well. I wanted to display TIME:HH:MM:SS on the first line, and on the second line i wanted to display TEMP(*C):XX.YY, waiting for a moment, clearing the second line (i did it using blank space), then to display HUM(%):XX.YY. And on and on. I just wanted to delay the second line 2 seconds while changing from temperature to humidity to see temperature and humidity values clearly. But it delays the whole system and time value is disappering for the amount of delay time too. I just want the clock being displayed for the whole time and display temperature and humidity separately. This is my code below:

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

Thanks!

1
Look up how to use a timer. Every time you call the delay function you're blocking everything else, hence the time gets halted.DigitalNinja

1 Answers

0
votes

As DigitalNinja said, delay is blocking everything. If you want to keep things running you must use interrupt.

Interrupt stop the execution of code to jump to a specific function outside the loop. It does'nt block the clock like delay. Everything is running, but you just basically insert your function WHEN it is needed, based on external event (rise on a pin, time elapsed...)

You can use the Timer1 library to execute an action every X seconds. Or create your own system using attachInterrupt.

I took this example in TimerOne reference pages and commented it

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
}