#include <virtuabotixRTC.h> #include <SD.h>virtuabotixRTC myRTC(7, 6, 5); int tempPin = A0; File dataFile;
void setup() Serial.begin(9600); if (!SD.begin(10)) Serial.println("SD Card failed!"); return;
void loop() myRTC.updateTime();
// Check if we are within working hours (9 AM to 5 PM) if (myRTC.hours >= 9 && myRTC.hours < 17) virtuabotixrtc.h arduino library
int tempReading = analogRead(tempPin); float voltage = tempReading * (5.0 / 1023.0); float temperatureC = voltage * 100.0; // Open file and log dataFile = SD.open("datalog.txt", FILE_WRITE); if (dataFile) dataFile.print(myRTC.getDateStr()); dataFile.print(","); dataFile.print(myRTC.getTimeStr()); dataFile.print(","); dataFile.println(temperatureC); dataFile.close(); Serial.print("Logged: "); Serial.println(temperatureC);else // Outside working hours: do nothing (or deep sleep) Serial.println("Outside logging hours. Sleeping...");
delay(60000); // Wait 1 minute between readings
If your DS1302 is running slow, check the voltage on pin 3.3V. Some modules have a diode that drops voltage. Powering the VCC pin with 5V and the backup battery with 3V can cause issues. Ensure the main power matches the chip's spec sheet.
Even a great library has pitfalls. Here is your debugging checklist.
The VirtuabotixRTC.h library is a lightweight Arduino library for interfacing with common real-time clock (RTC) modules based on the DS1307 and similar I²C RTC chips. It provides simple functions to set and read the current time and date, and to convert between raw RTC register values and human-readable formats suitable for embedded projects. #include <virtuabotixRTC
Unlike the more common DS3231 or PCF8523 modules which use I2C, the DS1302 chip relies on a proprietary 3-pin serial interface. The VirtuabotixRTC.h library (originally created by Virtuabotix) abstracts this communication into simple, readable C++ commands.
Key Features:
A minimal example to set and print time: void loop() myRTC
#include <Wire.h>
#include "VirtuabotixRTC.h"
VirtuabotixRTC myRTC(0x68); // typical I2C address for DS1307
void setup()
Serial.begin(9600);
Wire.begin();
myRTC.setTime(14, 30, 0); // 14:30:00
myRTC.setDate(3, 15, 4, 26); // Tuesday, 15 April 2026 (example format)
void loop()
Time t = myRTC.getTime();
Date d = myRTC.getDate();
Serial.print(d.day); Serial.print('/');
Serial.print(d.month); Serial.print('/');
Serial.print(d.year); Serial.print(' ');
Serial.print(t.hour); Serial.print(':');
Serial.print(t.minute); Serial.print(':');
Serial.println(t.second);
delay(1000);
(Adjust struct names and function signatures to match the library version you installed.)