777躺养离
Published

Iot Base clock using bolt iot module restful api

This project demonstrates how to create a real-time clock with an LCD display that shows the current time, date, and day using an Arduino, a

BeginnerProtip3 hours67
Iot Base clock using bolt iot module restful api

Things used in this project

Story

Read more

Code

Arduino codr

C/C++
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>

#define BUZZER_PIN 8

byte fan1[] = {
 B00000,
  B00000,
  B01010,
  B00000,
  B10001,
  B01110,
  B00000,
  B00000
};

byte fan2[] = {
  B00000,
  B00000,
  B01010,
  B11111,
  B11111,
  B01110,
  B00100,
  B00000
};


SoftwareSerial bolt(2, 3); // RX, TX pins for Bolt
LiquidCrystal_I2C lcd(0x27, 16, 2); // Adjust the address based on your LCD

String lastReceivedTime = "";
unsigned long lastUpdateTime = 0;
unsigned long previousMillis = 0;
const long interval = 1000; // Interval to update time (1 second)

void setup() {
  lcd.init();
  lcd.backlight();
  bolt.begin(9600);

  lcd.createChar(1, fan1);
  lcd.createChar(2, fan2);
  


  Serial.begin(9600); // For debugging
  pinMode(BUZZER_PIN, OUTPUT);
}

void loop() {
  unsigned long currentMillis = millis();
  
  if (bolt.available()) {
    String command = bolt.readStringUntil('\n');
    command.trim(); // Clean up any extra whitespace
    
    // Check if the command is "RD" and ignore it
    if (command == "RD") {
      Serial.println("Received RD command. Ignoring...");
      return; // Skip processing if "RD" command is received
    }
    
    // Update last received time
    lastReceivedTime = command;
    lastUpdateTime = currentMillis; // Store the time of the last update
    Serial.println("Received Time: " + lastReceivedTime); // Debugging line
  }
  
  // Check if it's time to update the display
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    
    // Calculate and display live time
    if (lastReceivedTime.length() > 0) {
      String currentTime = calculateLiveTime(lastReceivedTime);
      String currentDate = calculateDate(lastReceivedTime); // Calculate the date
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print( currentTime);
      lcd.setCursor(0, 1);
      lcd.print(currentDate);
      
      // Buzzer control for ticking sound
      digitalWrite(BUZZER_PIN, HIGH);
      lcd.setCursor(14, 0);
      lcd.write(1);
      lcd.setCursor(15, 0);
      lcd.write(2);
      
      delay(100); // Buzzer ON duration
      digitalWrite(BUZZER_PIN, LOW);
    }
  }
}

// Function to calculate live time
String calculateLiveTime(String lastTime) {
  int lastHour = lastTime.substring(0, 2).toInt();
  int lastMinute = lastTime.substring(3, 5).toInt();
  int lastSecond = lastTime.substring(6, 8).toInt();
  
  // Calculate elapsed time
  unsigned long elapsedMillis = millis() - lastUpdateTime;
  int elapsedSeconds = elapsedMillis / 1000;
  
  int totalSeconds = lastSecond + elapsedSeconds;
  int currentSecond = totalSeconds % 60;
  int totalMinutes = lastMinute + (totalSeconds / 60);
  int currentMinute = totalMinutes % 60;
  int currentHour = (lastHour + (totalMinutes / 60)) % 24;
  
  String timeString = String(currentHour) + ":" + String(currentMinute) + ":" + String(currentSecond);
  return timeString;
}

// Function to calculate the current date and day
String calculateDate(String lastTime) {
  int lastYear = 2024; // Set to the current year or derive it if available
  int lastMonth = 7;   // Set to the current month or derive it if available
  int lastDay = 19;    // Set to the current day or derive it if available

  // Calculate elapsed time in days
  unsigned long elapsedMillis = millis() - lastUpdateTime;
  int elapsedSeconds = elapsedMillis / 1000;
  int elapsedDays = elapsedSeconds / (24 * 3600);
  
  int currentDay = lastDay + elapsedDays;
  
  // Simple day adjustment, assuming month length for simplification
  int daysInMonth = 30; // Simplified; adjust according to month
  int daysInYear = 365; // Simplified; adjust for leap years
  
  if (currentDay > daysInMonth) {
    currentDay -= daysInMonth;
    lastMonth++;
  }
  if (lastMonth > 12) {
    lastMonth -= 12;
    lastYear++;
  }
  
  // Get the day of the week
  String dayOfWeek = getDayOfWeek(lastYear, lastMonth, currentDay);
  
  String dateString = String(currentDay) + "-" + String(lastMonth) + "-" + String(lastYear) + " " + dayOfWeek;
  return dateString;
}

// Function to get the day of the week
String getDayOfWeek(int year, int month, int day) {
  int dayOfWeek = (day + ((153 * (month + 12 * ((14 - month) / 12) - 3) + 2) / 5) + (365 * (year + 4800 - ((14 - month) / 12))) / 4 - (3 * ((year + 4900 - ((14 - month) / 12)) / 100)) / 4) % 7;
  String days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  return days[dayOfWeek];
}

html and js

HTML
<!DOCTYPE html>
<html>
<head>
  <title>Live Time on LCD</title>
  <script src="https://cloud.boltiot.com/static/js/boltCommands.js"></script>
</head>
<body>
  <h1>Live Time Display</h1>
  <button onclick="fetchAndSendTime()">Update Time</button>
  
  <script>
    setAuthToken('ac025582-20c3-4afc-a38d-6363b03a7db6');

    function fetchAndSendTime() {
      fetch('https://api.timezonedb.com/v2.1/get-time-zone?key=QSLLVCCFJ63O&format=json&by=zone&zone=Asia/Kolkata')
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          return response.json();
        })
        .then(data => {
          if (data.formatted) {
            let time = data.formatted.split(' ')[1]; // Extract time in HH:MM:SS format
            sendTimeToBolt(time);
          } else {
            throw new Error('Time data is not available');
          }
        })
        .catch(error => {
          console.error('Error fetching time:', error);
          alert('Error fetching time. Please check the console for more details.');
        });
    }

    function sendTimeToBolt(time) {
      var request = new XMLHttpRequest();
      request.open('GET', 'https://cloud.boltiot.com/remote/ac025582-20c3-4afc-a38d-6363b03a7db6/serialWrite?deviceName=BOLT13169131&data=' + encodeURIComponent(time) + '\n', true);
      request.send();
    }
  </script>
</body>
</html>

Credits

777躺养离
1 project • 0 followers

Comments