anisameri
Published © GPL3+

Real Time Clock module + Set through pushbutton and server

A simple project to set date and time to RTC module using pushbutton and get and set time from server connected through ESP 01 wifi module

BeginnerProtip1,122
Real Time Clock module + Set through pushbutton and server

Things used in this project

Hardware components

Arduino Nano R3
Arduino Nano R3
×1
Real Time Clock (RTC)
Real Time Clock (RTC)
×1
ESP8266 ESP-01
Espressif ESP8266 ESP-01
×1
Speaker, Piezo
Speaker, Piezo
×1
Pushbutton Switch, Push-Pull
Pushbutton Switch, Push-Pull
×1
Jumper wires (generic)
Jumper wires (generic)
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

ClockController.java

Java
import java.net.*;
import java.io.*;
class ClockController
{
String request;
Socket socket;
char c;
String response;
public void start() throws Exception
{
while(true)
{
System.out.print("iot-clock>");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
request  = br.readLine().toUpperCase();
if(request.equals("EXIT")) break;
if(request.equals("HELP")) 
{
System.out.println("RESET : For reset time to factory mode");
System.out.println("GETTIME : To get time");
System.out.println("SETTIME dd MM yy HH mm ss : To set time");
System.out.println("TODAY : To set current time\n");
continue;
}
socket = new Socket("localhost",8090);
OutputStreamWriter osr = new OutputStreamWriter(socket.getOutputStream());

if(request.contains("SETALARM FOR "))
{
request = "SETALARM,"+request.substring(13,request.indexOf("SEC"));
System.out.println(request);
}else{
request = request.replaceAll(" ",",");
}
osr.write(request+"#");
osr.flush();
isr = new InputStreamReader(socket.getInputStream());
response = "";
while(true)
{
c= (char)isr.read();
if(c=='#') break;
response += c;
}
socket.close();
System.out.println(response);
}
}
public static void main(String a[])
{
try
{
new ClockController().start();
}catch(Exception e){System.out.println(e);}
}
}

Arduino nano code

C/C++
/*
 * USE OF WIFI MODULE, RTC MODULE, PUSHBUTTON, SPEAKER 
 * D3  for blink when time is not set
*/
#include<SoftwareSerial.h>
#include<DS3231.h>
SoftwareSerial wifi(6,9);
DS3231 clock;
RTClib realTimeClock;
DateTime currTime ;
int i=0;
int x=0;
char request[50];

char response[51];
int interval =0;
byte isDateTimeSetMode = 0;
byte isDateTimeUpdated = 0;
byte isYearSetMode = 0;
byte isMonthSetMode = 0;
byte isDateSetMode= 0;
byte isHourSetMode = 0;
byte isMinuteSetMode = 0;
byte isSecondSetMode=0;
int date = 0, currDate = 0;
int month = 0, currMonth = 0;
int year = 0, currYear = 0;
int hour = 0, currHour = 0;
int minute =0, currMinute = 0;
int second = 0, currSecond = 0;
boolean isKeyReleased = true;
byte isToneEnabled = 0;
int minInterval =150;
void setup() {
delay(4000);
pinMode(5,OUTPUT);
pinMode(3,OUTPUT);
pinMode(13,INPUT);

wifi.begin(9600);
Serial.begin(9600);
Wire.begin();
//clock.setYear((byte)00);
setupWifi();
}

void setupWifi()
{
wifi.begin(9600);
while(!wifi);
Serial.println("Wifi Module is initialized");
Serial.print("Doing Reset");
wifi.print("AT+RST\r\n");
//while(!wifi.available()) Serial.print(".");
delay(2000);
while(wifi.available()) wifi.read();
Serial.println();
Serial.println("Reset Done");
Serial.println("\n");
Serial.print("AT Testing");
wifi.print("AT\r\n");//OK
delay(3000);
while(wifi.available()) wifi.read();
Serial.println();
Serial.println("Testing Done");
Serial.println();
Serial.print("Change mode to station");
wifi.print("AT+CWMODE=1\r\n");//OK
delay(3000);
//while(wifi.available()) wifi.read();
Serial.println();
Serial.println("Mode to Station mode Done");
Serial.println();
Serial.print("Let wifi connected to any AP if want");
i=10;
while(i>=0)
{
delay(1000);
Serial.print(" ");
Serial.print(i); 
i--; 
}
Serial.println("\n");
Serial.print("Disconnecting to all APs");
wifi.print("AT+CWQAP\r\n");

delay(3000);
Serial.println();
Serial.println("Wifi module not connected to any AP");
Serial.println();
Serial.print("Wifi module connecting to Anis");
wifi.print("AT+CWJAP_CUR=\"Anis\",\"******\"\r\n");//Set actual SSID and password
i = 0;
while(i<=10)
{
delay(1000);
Serial.print(".");
if(wifi.find((char *)"OK"))
{
  Serial.println("Connected");
  break;
}
i++;
}
if(i==11) 
{
  Serial.println("Unable to connect to Poco X3");
  return;
}
Serial.println("----------------------------Setup complete.............................");
  
  }



void loop()
{

  clockModuleManual();//TO SET CLOCK MODULE MANUALLY
  if(!isDateTimeSetMode)
   wifiOperations();//TO SET CLOCK MODULE REMOTELY
  }



void clockModuleManual() {
digitalWrite(3,0);
// RFDriver.send(0,1);
if(!isDateTimeSetMode && isRTCInDefaultMode())
  {
//    while(i<1000){  
  
    digitalWrite(3,HIGH);
 //   RFDriver.send(1,1);
    
    //delay(100);
    //analogWrite(3,0);
    //delay(100);
    interval = 0;
    while(digitalRead(13)) 
    {
      // analogWrite(3,100);
      if(interval >= minInterval)
      { 
        isDateTimeSetMode = 1;
        isDateSetMode = 1;
        digitalWrite(3,LOW);
        digitalWrite(5,HIGH);
       // RFDriver.send(0,1);
      }
      interval ++;
      delay(10);
    }
    
    //analogWrite(3,0);
    digitalWrite(5,LOW);
    if(isDateTimeSetMode)
    {
//      break;
    }
 //   i++;
  //}
  }

 if(isDateTimeSetMode)
 {
  if(isDateSetMode)
  {
      interval = 0;
      while(digitalRead(13))
      {
         if(interval >= minInterval)
         {
          digitalWrite(5,HIGH);
          isDateSetMode = 0;
          isMonthSetMode = 1;
         }
        
        if(!isToneEnabled){tone(11,100); isToneEnabled = 1;}
        if(isKeyReleased)
        {
        date++;          
        isKeyReleased =false;
        } 
        interval ++;
        delay(10);
      }
      digitalWrite(5,LOW);
      noTone(11);
      isToneEnabled = 0;
      isKeyReleased = true;
  }else if(isMonthSetMode)
  {
       interval = 0;
      while(digitalRead(13))
      {
         if(interval >= minInterval)
         {
          digitalWrite(5,HIGH);
          isMonthSetMode = 0;
          isYearSetMode = 1;
         }
        
        if(!isToneEnabled){tone(11,100); isToneEnabled = 1;}
        if(isKeyReleased)
        {
        month++;          
        isKeyReleased =false;
        } 
        interval ++;
        delay(10);
      }
      digitalWrite(5,LOW);
      noTone(11);
      isToneEnabled = 0;
      isKeyReleased = true;
  }else if(isYearSetMode){
       interval = 0;
      while(digitalRead(13))
      {
         if(interval >= minInterval)
         {
          digitalWrite(5,HIGH);
          isYearSetMode = 0;
          isHourSetMode = 1;
         }
        
        if(!isToneEnabled){tone(11,100); isToneEnabled = 1;}
        if(isKeyReleased)
        {
        year++;          
        isKeyReleased =false;
        } 
        interval ++;
        delay(10);
      }
      digitalWrite(5,LOW);
      noTone(11);
      isToneEnabled = 0;
      isKeyReleased = true;  
  }else if(isHourSetMode){
       interval = 0;
      while(digitalRead(13))
      {
         if(interval >= minInterval)
         {
          digitalWrite(5,HIGH);
          isHourSetMode = 0;
          isMinuteSetMode = 1;         
         }
        
        if(!isToneEnabled){tone(11,100); isToneEnabled = 1;}
        if(isKeyReleased)
        {
        hour++;          
        isKeyReleased =false;
        } 
        interval ++;
        delay(10);
      }
      digitalWrite(5,LOW);
      noTone(11);
      isToneEnabled = 0;
      isKeyReleased = true;  
  }else if(isMinuteSetMode){
       interval = 0;
      while(digitalRead(13))
      {
         if(interval >= minInterval)
         {
          digitalWrite(5,HIGH);
          isMinuteSetMode = 0;
          isSecondSetMode = 1;
         }
        
        if(!isToneEnabled){tone(11,100); isToneEnabled = 1;}
        if(isKeyReleased)
        {
        minute++;          
        isKeyReleased =false;
        } 
        interval ++;
        delay(10);
      }
      digitalWrite(5,LOW);
      noTone(11);
      isToneEnabled = 0;
      isKeyReleased = true;  
  }else if(isSecondSetMode){
       interval = 0;
      while(digitalRead(13))
      {
         if(interval >= minInterval)
         {
          digitalWrite(5,HIGH);
          isSecondSetMode = 0;
         }
        
        if(!isToneEnabled){tone(11,100); isToneEnabled = 1;}
        if(isKeyReleased)
        {
        second++;          
        isKeyReleased =false;
        } 
        interval ++;
        delay(10);
      }
      digitalWrite(5,LOW);
      noTone(11);
      isToneEnabled = 0;
      isKeyReleased = true;  
  }else if(!isDateTimeUpdated){
    date--;
    month--;
    year--;
    hour--;
    minute--;
    second--;
    updateDateTime();
    isDateTimeSetMode = 0;
  }
  }else if(!isDateTimeUpdated){
    
  }

delay(10);
}

void wifiOperations()
{
Serial.println("Wifi Operations");
wifi.print("AT+CIPSTART=\"TCP\",\"192.168.0.104\",8090\r\n");
delay(2000);
while(!wifi.available());
//while(wifi.available())Serial.print((char)wifi.read());
if(!wifi.find((char *)"OK")) 
{
  Serial.println("ERROR: AT+CIPSTART=\"TCP\",\"192.168.43.222\",8090 response is not OK");
  return;
}

while(wifi.available())(char)wifi.read();
getCurrTimeRTC();
sprintf(request,"BR,AC,%d,%d,%d,%d,%d,%d#",currDate,currMonth,currYear,currHour,currMinute,currSecond);//WHEN EVER ASKING COMMAND IT SEND CURRENT RTC TIME TO SERVER
char request2[50];
sprintf(request2,"AT+CIPSEND=%d\r\n",strlen(request));
wifi.print(request2);
delay(1000);
while(!wifi.available());

if(!wifi.find((char *)"OK")) 
{
  Serial.println("ERROR: AT+CIPSEND=25 response is not OK");
  //return;
}
//while(wifi.available())(char)wifi.read();

Serial.println(request);
wifi.print(request) ;
while(!wifi.available());
delay(1000);
if(!wifi.find((char *)"+IPD,"))
{
  while(wifi.available())wifi.read();
  Serial.println("IPD not found");
  return;
}
char c;
while(wifi.available() && wifi.read()!=':');
i=0;
int a;
while(true)
{
  a = wifi.available();
  Serial.print(" ");
  Serial.print(a);
  if(!a || i>=199)
  {
    //break;
  }else{
  x = (char)wifi.read();
  if(x=='#')
  {
    Serial.println("Breaking from loop");
    break;
  }
  response[i]=x;
   i++;
  }
}
response[i]='\0';
Serial.println();
Serial.print("Response::: ");
Serial.println(response);
while(wifi.available())wifi.read();
if(x!='#')
{Serial.println("Response does not contains terminator");
  return;
}
if(i==0)
{
 Serial.println("No command to execute"); 
}else{
  Serial.print("Command: "); 
  Serial.println(response);

//HARDCODE FOR NOW WILL CHANGE LATER ON
//FOR BELOW CODE, REQUEST WILL ALAWAYS BE LIKE - 15,09,20,11,12,34#    <- less then 21 chars
  Serial.println(response[0]);
  Serial.println(response[1]);
      date = (response[0]-48)*10+(response[1]-48);
      month = (response[3]-48)*10+(response[4]-48);
      year = (response[6]-48)*10+(response[7]-48);  
      hour = (response[9]-48)*10+(response[10]-48);
      minute=(response[12]-48)*10+(response[13]-48);
      second =(response[15]-48) *10+(response[16]-48);
     updateDateTime();

//FOR BELOW CODE, REQUEST WILL ALAWAYS BE LIKE - SETTIME,15,09,20,11,12,34#    
//COMMENTTED BELOW CODE SINCE ANABLE TO READ FROM WIFI IF STRING HAVING MORE THAN 21 CHARS
    /* 
 int i1=0;
 int i2=0;
 while(response[i2]!='\0')
 {
  if(response[i2]=='!') i1=i2+1;
  if(response[i2]==',')
  {
    response[i2]='\0';
    i2++;
    //x = response[i2]; 
      date = response[0]*10+response[1];
      month = response[3]*10+response[4];
      year = response[6]*10+response[7];
      hour = response[9]*10+response[10];
      minute=response[12]*10+response[13];
      second =response[15]*10+response[16];
     updateDateTime();
    
  }
  i2++;
 } 
 */
 }
  
  }


boolean isRTCInDefaultMode()
{
  getCurrTimeRTC();

if(currTime.year()==2000)
{
 return true;
  }
  return false;
}

void getCurrTimeRTC()
{
currTime = realTimeClock.now();  
currDate = currTime.day();
currMonth = currTime.month();
currYear = currTime.year();
currHour = currTime.hour();
currMinute = currTime.minute();
currSecond = currTime.second();
  
}

void updateDateTime()
{

    Serial.print(date);Serial.print("/");Serial.print(month);Serial.print("/");Serial.print(year);Serial.print("  ");
    Serial.print(hour);Serial.print(":");Serial.print(minute);Serial.print(":");Serial.println(second);
    clock.setClockMode(false);
    clock.setDate((byte)date);
    clock.setMonth((byte)month);
    clock.setYear((byte)year);
    clock.setHour((byte)hour);
    clock.setMinute((byte)minute);
    clock.setSecond((byte)second);
    isDateTimeUpdated = 1;
    //analogWrite(3,100);
    digitalWrite(5,HIGH);
    
}

ClockServer.java

Java
/*
BR,AC
RESET
GETTIME
SETTIME,TODAY
SETTIME,15,13,20,04,23,12
SETALARM,2    //Set alarm for 2 second
*/

import java.net.*;
import java.io.*;
import java.util.*;
import java.time.*;
import java.time.format.*;
public class ClockServer
{
ServerSocket serverSocket;
Socket socket;
int i=0;
char c;
String request,response;
String nanoClockTime="Loading..";
List<String> commands;
ClockServer() 
{
commands = new ArrayList<>();
}

public void start() throws Exception
{
serverSocket = new ServerSocket(8090);
while(true)
{
System.out.println("Clock server is ready at 8090");
socket = serverSocket.accept();
InputStreamReader isr = new InputStreamReader(socket.getInputStream());
StringBuffer sb = new StringBuffer();
System.out.println("Request received..");
while(true)
{
c= (char)isr.read();
if(c=='#') break;
sb.append(c);
}
request = sb.toString().toUpperCase();
System.out.println("Request: "+request);
String split[] = request.split(",");
if(split[0].equals("BR"))
{
if(split[1].equals("RD"))
{
System.out.println("Thanks for Registering Board...");
OutputStreamWriter osr = new OutputStreamWriter(socket.getOutputStream());
osr.write("Board Registered#");
osr.flush();
}else if(split[1].equals("AC"))
{
nanoClockTime = split[2]+"/"+split[3]+"/"+split[4]+" "+split[5]+":"+split[6]+":"+split[7];
response="";
i=0;
for(String cmd:commands)
{
if(i>0) response = response +"!";
response = response + cmd;//TODO
i++;
}
commands.clear();
response = response +"#";
OutputStreamWriter osr = new OutputStreamWriter(socket.getOutputStream());
osr.write(response);
osr.flush();
System.out.println("Sending response:"+response );
}
}else if(split[0].equals("RESET"))
{
commands.add("01,01,00,00,00,00");//SETTIME,01,01,00,00,00,00
OutputStreamWriter osr = new OutputStreamWriter(socket.getOutputStream());
osr.write("Command registered#");
osr.flush();
}else if(split[0].equals("GETTIME"))
{
OutputStreamWriter osr = new OutputStreamWriter(socket.getOutputStream());
osr.write(nanoClockTime+"#");
osr.flush();
}else if(split[0].equals("SETTIME"))
{
OutputStreamWriter osr = new OutputStreamWriter(socket.getOutputStream());
try
{
if(split[1].equals("TODAY"))
{
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd,MM,yy,HH,mm,ss");
LocalDateTime today = LocalDateTime.now();
System.out.println(dtf.format(today));
commands.add(dtf.format(today));
osr.write("Command registered#");
}else
{
commands.add(split[1]+","+split[2]+","+split[3]+","+split[4]+","+split[5]+","+split[6]);//SETTIME,01,01,00,00,00,00
osr.write("Command registered#");
}
}catch(Exception e)
{
System.out.println(e);
osr.write("Invalid command#");
}
osr.flush();
}else if(split[0].equals("SETALARM"))
{
commands.add("SETALARM,"+split[1]);
OutputStreamWriter osr = new OutputStreamWriter(socket.getOutputStream());
osr.write("Command registered#");
osr.flush();
}
socket.close();
}
}
public static void main(String aerp[])
{
try
{
new ClockServer().start();
}catch(Exception e)
{
System.out.println(e);
}
}
}

Credits

anisameri
0 projects • 0 followers

Comments