Large wall clock with auto-brightness on Arduino.


Real time clock - a module that stores current date and does not reset it when the power is turned off thanks to the built-in battery. You may have heard about watches based on the DS1307 chip. This chip has extremely low clock accuracy. A delay of one hour per day is too much. I recommend using a module based on a high-precision DS3231 chip, which is equipped with a thermometer to adjust the clock rate depending on the temperature. The clock accuracy of this chip is at a good level wristwatch and is 2ppm at temperature environment 0°-40°. At the same time, the module is compatible with all libraries written for the module based on the DS1307 chip. The article talks about connecting the module to Arduino and interacting with them using the Time library. You can buy such a module from a seller I have verified.

Real time clock connection

The clock is connected using the I2C protocol with just two wires. It is necessary to additionally tighten the terminals to which the clock is connected to the power rail using 2 KΩ resistors. The clock outputs look like this:

The 32K and SQW pins can be ignored. Their purpose is not discussed in this article. SCL and SDA are the I2C interface pins. They need to be connected to the controller. VCC and GND are +5V and ground respectively.

SCL and SDA on different boards located on different pins:

Uno, Nano A4 (SDA), A5 (SCL)
Mega2560 20 (SDA), 21 (SCL)
Leonardo 2 (SDA), 3 (SCL)

The SDA pin of the clock is connected to the SDA pin of the controller. SDL clock, respectively, to SDL controller. After connecting the wires, you should get the following picture:

The most convenient way to work with the real-time clock module is using the library. The most convenient one in this regard is called: Time ( English time).
The library is a “wrapper” for another popular library for working with the clock module: DS1307RTC. Despite the fact that the library was developed for the DS1307 chip, it works perfectly with the DS3231, since the communication protocols are compatible.

Download both libraries.

After downloading, place the contents of the archives in the libraries folder, which is located in the environment folder Arduino development. Launch the Arduino IDE and open the standard example library: Examples->Time->TimeRTC
Or just copy this code:

#include #include #include void setup() ( Serial.begin(9600); while (!Serial) ; // wait until Arduino Serial Monitor opens setSyncProvider(RTC.get); // the function to get the time from the RTC if(timeStatus()! = timeSet) Serial.println("Unable to sync with the RTC"); else Serial.println("RTC has set the system time"); ) void loop() ( if (timeStatus() == timeSet) ( digitalClockDisplay( ); ) else ( Serial.println("The time has not been set. Please run the Time"); Serial.println("TimeRTCSet example, or DS1307RTC SetTime example."); Serial.println(); delay(4000) ; ) delay(1000); ) void digitalClockDisplay())( // digital clock display of the time Serial.print(hour()); printDigits(minute()); printDigits(second()); Serial.print(" " ); Serial.print(day()); Serial.print(" "); Serial.print(month()); Serial.print(" "); Serial.print(year()); Serial.println() ; ) void printDigits(int digits)( // utility function for digital clock display: prints preceding colon and leading 0 Serial.print(":"); if(digits< 10) Serial.print("0"); Serial.print(digits); }

#include

#include

#include

void setup() (

Serial. begin(9600);

while (! Serial ) ; // wait until Arduino Serial Monitor opens

setSyncProvider(RTC.get); // the function to get the time from the RTC

if (timeStatus() != timeSet)

Serial. println("Unable to sync with the RTC");

else

Serial. println("RTC has set the system time");

void loop()

if (timeStatus() == timeSet) (

digitalClockDisplay();

) else (

Serial. println( "The time has not been set. Please run the Time") ;

Serial. println( "TimeRTCSet example, or DS1307RTC SetTime example.") ;

Serial. println();

delay(4000);

delay(1000);

void digitalClockDisplay() (

// digital clock display of the time

Serial. print(hour());

printDigits(minute());

printDigits(second());

Serial. print (" " ) ;

Serial. print(day());

Serial. print (" " ) ;

Serial. print(month());

Serial. print (" " ) ;

Serial. print(year());

Serial. println();

void printDigits(int digits) (

// utility function for digital clock display: prints preceding colon and leading 0

Serial. print(":");

if (digits< 10 )

Serial. print("0");

Serial. print(digits);

After loading the sketch into the board, launch the port monitor (Tools->port monitor). You will see messages from the library. The displayed time will be incorrect, or the library will complain that the clock is not configured. To set the clock, load an example from the DS1307RTC “SetTime” library into the board (Examples->DS1307RTC->SetTime). Load this example into your board. After downloading, the watch will be set to sketch compilation time. Delay between compilation and fully loaded will be quite a bit, which will be enough for a finely tuned watch. But if you disconnect and reconnect the board's power, even after several hours, the clock time will still be reset to the time of compilation and will be incorrect. Therefore, use this example only for setup, after setup, turn off the clock or upload another sketch to the board.

So, real time clock. This useful little thing solves most useful time-related problems. Let's say you control watering at 5 o'clock in the morning at your dacha. Or turning lights on and off at a certain moment. By date you can start heating in any house. The thing is quite interesting and useful. And more specifically? We will look at the DS1302 real-time clock for the popular Arduino platform.

From this article you will learn:

Good day, dear readers of the kip-world block! How are you doing? Write in the comments, are you interested in robotics? What does this topic mean to you?

I can't stop thinking about this for a minute. I dream and see when we will finally come to the point where everyone can afford to buy a personal robot assistant. It doesn’t matter what he does, picking up trash, mowing lawns, washing a car.

I can just imagine how complex algorithms they must contain in their “brains”.

After all, we will come to the point where we will flash software in the same way as on personal computers. Also download application programs. Sew on arms, legs, change claws, manipulators.

Watch the films "I Robot", " Artificial intelligence", "Star Wars".

The Japanese have been implementing their developments for a long time. Why are we worse?? We have very little popularity. I know few developers. I can count it on my fingers. We are doing something else. We are resellers. We just buy ready-made kits, robots, toys and all sorts of rubbish.

Why don't we develop this:

Or this:

I finished my thoughts out loud. Let's talk about connecting the DS1302 Real Time Clock Timer to Arduino.

Real time clock DS1302

The Arduino controller does not have its own clock. Therefore, if necessary, it must be supplemented with a special DS1302 microcircuit.

For power supply, these boards can use their own battery, or be powered directly from the Arduino board.

Pinout table:

Connection diagram with Arduino UNO:


Method for programming Arduino to work with DS1302

It is imperative to download a valid library from reliable sources.

The library allows you to read and write real-time parameters. I give a short description below:

#include // Connect the library.
iarduino_RTC AN OBJECT ( NAME [, RST_OUTPUT [, CLK_OUTPUT [, DAT_OUTPUT ]]] ); // Create an object.

Function begin();// Initialization of work RTC module.

Function settime( SEC [, MIN [, HOUR [, DAY [, MONTH [, YEAR [, DAY]]]]]] ); // Setting the time.

Function gettime([ LINE ] ); // Read the time.

function blinktime ( PARAMETER [FREQUENCY] ); // Causes the gettime function to "blink" specified parameter time.

function period( MINUTES ); // Indicates the minimum period for accessing the module in minutes.

Variable seconds// Returns seconds from 0 to 59.

Variable minutes// Returns minutes from 0 to 59.

Variable hours// Returns hours from 1 to 12.

Variable Hours// Returns hours from 0 to 23.

Variable midday// Returns noon 0 or 1 (0-am, 1-pm).

Variable day// Returns the day of the month from 1 to 31.

Variable weekday// Returns the day of the week from 0 to 6 (0 is Sunday, 6 is Saturday).

Variable month// Returns the month from 1 to 12.

Variable year// Returns the year from 0 to 99.

We are writing a simple program. Setting the current time in the RTC module (DS1302):

Arduino

#include iarduino_RTC time(RTC_DS1302,6,7,8); void setup() ( delay(300); Serial.begin(9600); time.begin(); time.settime(0,51,21,27,10,15,2); // 0 sec, 51 min, 21 hours, October 27, 2015, Tuesday ) void loop())( if(millis()%1000==0)( // if 1 second has passed Serial.println(time.gettime("d-m-Y, H:i: s, D")); // display the time delay(1); // pause for 1 ms so as not to display the time several times in 1 ms ) )

#include

iarduino_RTCtime(RTC_DS1302, 6, 7, 8);

void setup() (

delay(300);

Serial. begin(9600);

time. begin();

time. settime(0, 51, 21, 27, 10, 15, 2); // 0 sec, 51 min, 21 hours, October 27, 2015, Tuesday

void loop() (

if (millis() % 1000 == 0 ) ( // if 1 second has passed

Serial. println (time . gettime ( "d-m-Y, H:i:s, D" ) ) ; // display time

delay(1); // pause for 1 ms so as not to display the time several times in 1 ms

We read the current time from the RTC module (DS1302) and output it to the “Serial port”:

#include iarduino_RTC time(RTC_DS1302,6,7,8); void setup() ( delay(300); Serial.begin(9600); time.begin(); ) void loop())( if(millis()%1000==0)( // if 1 second has passed Serial.println (time.gettime("d-m-Y, H:i:s, D")); // display the time delay(1); // pause for 1 ms so as not to display the time several times in 1 ms ) )

One of the first projects that beginners build using an Arduino board is a simple clock that keeps time. Basically, such clocks are based on an RTC (Real Time Clock) module connected to Arduino. On the market today electronic components available different models RTCs that vary in accuracy and price. Common models include DS1302, DS1307, DS3231.



But you can make a clock on Arduino without using an RTC, especially if you can’t get such modules. Of course, the accuracy is in this case will be small, so the project should rather be considered as a training project.


The operating principle of such watches is quite simple. Every time you turn on this Arduino clock, you will need to set it to the current time, just like any analog clock. It is certainly better not to use such watches in your Everyday life if they are active for a long time without rebooting and further configuration, since desynchronization with current time during long-term operation can be significant.


This watch can be assembled using a regular breadboard, since it doesn't require many components. Our main link here will be the Arduino Uno board. To display the time, you can take a 16x2 LCD display. To change the time settings, you need to connect two buttons (for hours and minutes). The buttons are connected to Aduino via 10KΩ resistors. To change the brightness of the display you will need a 10 kOhm potentiometer. The connection diagram for all these components to the Arduino Uno board is presented below.



Now you need to program the Arduino. A simple code (sketch) that allows you to display the time on the LCD screen is given below.


#include LiquidCrystal lcd(12,11,5,4,3,2); int h=12; int m; int s; int flag; int TIME; const int hs=8; const int ms=9; int state1; int state2; void setup() ( lcd.begin(16,2); ) void loop() ( lcd.setCursor(0,0); s=s+1; lcd.print("TIME:"); lcd.print(h ); lcd.print(":"); lcd.print(m); lcd.print(":"); lcd.print(s); if(flag<12)lcd.print("AM"); if(flag==12)lcd.print("PM"); if(flag>12)lcd.print("PM"); 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; ) if(h==13 ) ( h=1; ) lcd.setCursor(0,1); lcd.print("HAVE A NICE DAY"); //-------Time // setting-------// state1=digitalRead(hs); if(state1==1) ( h=h+1; flag=flag+1; if(flag<12)lcd.print("AM"); if(flag==12)lcd.print("PM"); if(flag>12)lcd.print("PM"); if(flag==24)flag=0; if(h==13)h=1; ) state2=digitalRead(ms); if(state2==1)( s=0; m=m+1; ) )

   Thank you for your interest in the website information project.
   If you want interesting and useful materials to be published more often and with less advertising,
   You can support our project by donating any amount for its development.

This article discusses an example of creating a real time clock. The indicator will display the exact time, and the colon on it will blink once per second. Exact time will be automatically installed during firmware compilation.

Description of components

Real time clock

We use the real-time clock module from Seeed Studio. They are based on the DS1307 chip from Maxim Integrated. Of the strapping elements, it requires three resistors, a clock quartz and a battery, which are already available on this module. The module has the following properties:

    Counting time (seconds, minutes, hours), date (year, month, day), day of week

    Two-wire I²C interface

The essence of a real-time clock is that if there is a battery, it can run even if the main device is de-energized. We come across such clocks all the time in laptops or digital cameras. If you remove the battery from these devices and put them back after a while, the time will not reset. This is thanks to the real time clock, Real Time Clock (RTC).

All required libraries can be downloaded from the official website.

Indicator

We use a four-digit indicator from Seeed Studio. The main thing in the indicator is the TM1637 chip, which is a driver for individual 7-segment bits. This module uses 4 bits. The module has the following properties:

    8 brightness levels

    Two-wire operation interface (CLK, DIO)

We use this module to display time: hours and minutes. The convenience of the module is that it is connected via only two wires and does not require software implementation of dynamic indication, since everything is already implemented inside the module.

Dynamic indication is a process in which the indicators in our module light up sequentially. But we don’t see flickering, since the human eye has great inertia. This method allows you to very well save the number of connections between the indicators and the controller:

    Static display: 4 digits × 7 segments = 28 connections.

    Dynamic indication: 7 segments + 4 common anodes or cathodes = 11 connections.

    Chip TM1637: 2 connections.

The benefit is obvious.

Connection

The real time clock module must be connected to the SCL/SDA pins related to the I²C bus. It is also necessary to connect the power (Vcc) and ground (GND) lines.

The SDA/SCL lines have their own separate pins on the Arduino, but internally they are somehow connected to the pins general purpose. If we look at the Arduino Uno, the SDA line corresponds to pin A4, and the SCL line corresponds to A5.

The module comes with a cable with female contacts, which are more convenient to connect to Troyka Shield. However, separate SDA and SCL pins are not displayed on it, so we connected directly through pins A5 and A4.

In terms of connecting the indicator, everything is much simpler. The CLK and DIO pins can be connected to any digital pins. In this case, the 12th and 11th pins are used, respectively.

Writing firmware

The setup function should initialize the real-time clock and indicator, and record the compilation time in internal memory real time clock. The entire action, or rather, reading the time from the RTC and displaying it on the indicator, will be performed in the loop function.

The code for this looks like this:

rtc.ino #include #include //Classes TM1637 and DS1307 are declared in them clock ; void setup() ( clock .begin () ; clock clock .setTime () ; ) void loop() ( int8_t timeDisp[ 4 ] ; //Request the time from the clock] = clock .minute % 10 ; display.point (clock .second % 2 ? POINT_ON : POINT_OFF) ; ) //The contents of the function are explained below char getInt(const char * string, int startIndex) ( return int (string[ startIndex] - "0" ) * 10 + int (string[ startIndex+ 1 ] ) - "0" ; )

Now we load this code into the development environment, compile and upload. We look at the display - bingo! The time on the display is the compilation time.

getInt function explained

First, you need to understand where the time comes from in the compileTime array. It appears in this line:

unsigned char compileTime = __TIME__;

The compiler replaces __TIME__ with a string containing the compilation time in the form __TIME__ = "hh:mm:ss" , where hh is hours, mm is minutes, ss is seconds.

Let's return to the code that needs to be explained:

char getInt(const char * string, int startIndex) ( return int (string[ startIndex] - "0" ) * 10 + int (string[ startIndex+ 1 ] ) - "0" ; )

In the string array passed as a parameter to the getInt function, we get the character at index startIndex and the one following it to end up with a two-digit integer. However, initially this is not a number, but a pair characters. To get a number from a symbol, we need to subtract the zero symbol (“0”) from this symbol: after all, in ASCII table all digit symbols come one after another, starting with the zero symbol. Therefore, the code int(string) - "0"), literally, does the following: “Take the character number startIndex , subtract the zero character from it and convert it to an integer type.”

Problems

Yes, this code is working, and the clock will run. However, if you turn off the power and turn it on a few minutes later, then after turning it on, the time will again become the same as it was during compilation.

This happens because after turning on the power, the code found in the setup function is executed again. And he writes the old time value to the real time clock.

To avoid this, we need to modify the code a little more. Each time in the setup function, a “hash” of the compilation time will be calculated - the number of seconds that have passed from 00:00:00 to the compilation time will be calculated. And this hash will be compared with the hash in the EEPROM. Let us remind you that EEPROM is a memory that is not reset when the power is turned off.

If the values ​​of the calculated and previously saved hash coincide, this means that there is no need to rewrite the time in the clock module: this has already been done. But if this check does not pass, then the time is overwritten in the RTC.

To write/read a number of the unsigned int type to/from EEPROM, two additional functions EEPROMWriteInt and EEPROMReadInt . They are added because the EEPROM.read and EEPROM.write functions can only read and write char data.

rtc-eeprom.ino #include #include #include "TM1637.h" #include "DS1307.h" //Array containing compile time char compileTime = __TIME__; //Numbers of Arduino pins to which the indicator is connected#define DISPLAY_CLK_PIN 12 #define DISPLAY_DIO_PIN 13 //To work with the clock chip and indicator we use libraries TM1637 display(DISPLAY_CLK_PIN, DISPLAY_DIO_PIN) ; DS1307 clock ; void setup() ( //Enable and configure the indicator display.set(); display.init(); //Start the real time clock clock.begin(); //Get a number from a string, knowing the number of the first character byte hour = getInt(compileTime, 0 ) ; byte minute = getInt(compileTime, 3 ) ; byte second = getInt(compileTime, 6 ) ; //Improvised time hash //Contains the number of seconds since the beginning of the day unsigned int hash = hour * 60 * 60 + minute * 60 + second; //Check if the new hash does not match the hash in the EEPROM if (EEPROMReadInt(0 ) != hash) ( //Save the new hash EEPROMWriteInt(0 , hash) ; //Prepare hours, minutes, seconds for recording in RTC clock .fillByHMS (hour, minute, second) ; //Write this data to the internal memory of the watch. //From this moment they begin to count the time we need clock.setTime(); ) ) void loop() ( //Values ​​to display on each of the 4 digits int8_t timeDisp[ 4 ] ; //Request the time from the clock] = clock .minute % 10 ; //... and then display it on the screen display.display(timeDisp); //we don't have separate digits for seconds, so //we will turn the colon on and off every second display.point (clock .second % 2 ? POINT_ON : POINT_OFF) ; ) char getInt(const char * string, int startIndex) ( return int (string[ startIndex] - "0" ) * 10 + int (string[ startIndex+ 1 ] ) - "0" ; ) //Write a two-byte number into memory void EEPROMWriteInt(int address, int value) ( ​​EEPROM.write (address, lowByte(value) ) ; EEPROM.write (address + 1 , highByte(value) ) ; ) //Reading a number from memory unsigned int EEPROMReadInt(int address) ( byte lowByte = EEPROM.read (address) ; byte highByte = EEPROM.read (address + 1 ) ; return (highByte<< 8 ) | lowByte; }

Conclusion

This article showed an example of working with the RTC DS1307 real-time clock chip and the TM1637 indicator driver chip; we also learned how to obtain the date and time at the compilation stage. Now, if you set the desired time on the clock, and then turn off the power for at least a few hours, then after turning it on the time will again be accurate. Checked!

In this article you will get acquainted with an excellent battery-powered real-time clock module.

With this module, you can track the time in your Arduino projects even in case of reprogramming or power failure. This is one of the necessary elements for projects of alarm clocks, alarms, and taking readings from sensors in real time. One of the most popular models of real time clock module is DS1307. This is where we will focus. The module fits perfectly with Arduino microcontrollers, which have 5 V logic power.

Features of the module from the manufacturing company Adafruit (the Chinese offer similar options three to four times cheaper):

  • Everything is included: chip, harness, battery;
  • Easy to assemble and easy to use;
  • Installs on any breadboard or connects directly using wires;
  • There are excellent libraries and example sketches;
  • Two holes for mounting;
  • Duration of work - about five years!

The real-time clock module may already be soldered, or it may be sold in the form of separate components, soldering of which will take about 15 minutes, no more.

What is a real time clock?

A real time clock is... a clock. The module operates on autonomous power - batteries and continues to count down time, even if the power is lost on your Arduino project. Using a real-time module, you can keep track of time even if you want to make changes to your sketch and reprogram the microcontroller.

Most microcontrollers, including Arduino, have a built-in time counter called millis(). There are also timers built into the chip that can track longer periods of time (minutes or days). So why do you need a separate clock module? The main problem is that millis() only tracks time from the moment power is applied to the Arduino. That is, as soon as you disconnect the board, the timer is reset to 0. The Arduino lice does not know what it is, for example, Thursday or March 8th. All you can get from the built-in counter is "14000 milliseconds have passed since the last time it was turned on."

For example, you created a program and want to count down time from this moment. If you turn off the power to the microcontroller, the time counter will be lost. Much like what happens with cheap Chinese watches: when the battery runs out, they start blinking at 12:00.

In some Arduino projects you will need reliable time control without interruptions. It is in such cases that an external real-time clock module is used. The chip that is used in such watches keeps track of the years and even knows how many days there are in a month (the only thing that is usually not taken into account is the transition to summer and winter time, since such conversions are different in different parts of the world).

The figure below shows a computer motherboard with a DS1387 real-time clock. The watch uses a lithium battery, so it has grown in size.

We will look at an example using the DS1307 real time clock. This is a cheap, easy to use module that lasts for several years on a small battery.

Until the battery in the module itself runs out of charge, the DS1307 will keep time, even if the Arduino is unplugged or reprogrammed.

The nodes that make up the real-time clock module

Adafruit DS1307 Real Time Clock Module Details
Drawing Designation Description Manufacturer Quantity
IC2 Real time clock chip DS1307 1
Q1 32.768 KHz, 12.5 pF crystal Generic 1
R1, R2 1/4W 5% 2.2Kohm resistor Red, Red, Red, Gold Generic 2
C1 0.1uF ceramic capacitor Generic 1
5-pin rail (1x5) Generic 1
Battery 12mm 3V lithium battery CR1220 1
12mm coin cell holder Keystone 3001 1
Pay Adafruit Industries 1

Assembling the Real Time Clock Module

Assembling the Adafruit DS1307 Real Time Clock
Photo Explanations

Prepare for assembly. Check that you have all the necessary parts and tools. Place the circuit board in a vice.

Apply some solder to the negative terminal of the battery.

Install two 2.2KΩ resistors and a ceramic capacitor. How exactly you arrange them is not important. Polarity doesn't matter. After this, install the crystal (also symmetrically), the holder (holder) for the battery and the real-time clock chip. The real-time module chip must be installed in such a way that the mark (groove) on the chip is located in accordance with the designation on the circuit board. Look carefully at the photo on the left, the chip is installed correctly.


To prevent the battery holder from falling out, it is better to solder it on top. After this, turn the board over and solder the remaining pins.

Remove the remaining contacts from the resistors, crystal and capacitor.

If you want to use the pins to mount the module on a solderless circuit board, install the pin rail on the breadboard, the RTC module on top, and solder the pins.

Install the battery. The flat part of the battery should be on top. On average, the battery will last about 5 years. Even if the battery is low, do not leave the battery slot empty.

Arduino library for working with DS1307

The DS1307 easily connects to any microcontroller with 5V logic power and I2C connectivity. We will look at connecting and using this module with Arduino.

We will use the RTClib library to obtain and configure readings from the DS1307. If you have questions about installing additional Arduino libraries, check out these instructions.

The article discusses an example of a real-time clock from Adafruit, but you can just as easily use Chinese analogues. The principle of operation and connection is no different.

  • BUY Arduino Uno R3;
  • BUY Breadboard ;
  • BUY real time clock module DS1307;

There are 5 pins on the real clock: 5V, GND, SCL, SDA and SQW.

  • 5V is used to power the real time clock module chip when you query it for time data. If the 5V signal is not supplied, the chip goes into sleep mode.
  • GND - common ground. Must be connected to the circuit.
  • SCL - i2c clock contact - is necessary for exchanging data with the real-time clock.
  • SDA is a contact through which data from the real-time clock is transmitted via i2c.
  • SQW makes it possible to configure data output in the form of square-wave. In most cases this contact is not used.

If you have configured analog pin 3 (digital 17) to be OUTPUT and HIGH and analog pin 2 (digital 16) to be OUTPUT and LOW, you can power the real time clock directly from these pins!

Connect analog pin 4 on Arduino to SDA. Connect analog pin 5 on the Arduino to SCL.


Sketch for Arduino

Checking the real time clock

The first sketch to run is a program that will read data from the real-time clock module once per second.

First, let's see what happens if we remove the battery and replace it with another one while the Arduino is not connected to USB. Wait 3 seconds and remove the battery. As a result, the chip on the real-time clock will reboot. After that, paste the code below (the code can also be uploaded to Examples→RTClib→ds1307 in Arduino IDE) and upload it to Arduino.

You will also need the OneWire.h library, you can download it

.

// date and time functions using DS1307 real time clock connected via I2C. The sketch uses the Wire lib library

#include <Wire.h>

#include "RTClib.h"

Serial.begin(57600);

if (!RTC.isrunning()) (

Serial.println("RTC is NOT running!");

// RTC.adjust(DateTime(__DATE__, __TIME__));

DateTime now = RTC.now();

Serial.print("/");

Serial.print("/");

Serial.print(now.day(), DEC);

Serial.print(" ");

Serial.print(":");

Serial.print(":");

Serial.println();

Serial.print(now.unixtime());

Serial.print("s = ");

Serial.println("d");

// calculate the date: 7 days and 30 seconds

DateTime future(now.unixtime() + 7 * 86400L + 30);

Serial.print(" now + 7d + 30s: ");

Serial.print(future.year(), DEC);

Serial.print("/");

Serial.print(future.month(), DEC);

Serial.print("/");

Serial.print(future.day(), DEC);

Serial.print(" ");

Serial.print(future.hour(), DEC);

Serial.print(":");

Serial.print(future.minute(), DEC);

Serial.print(":");

Serial.print(future.second(), DEC);

Serial.println();

Serial.println();

Now open the serial monitor window and make sure that the baud rate is set correctly: 57600 bps.

As a result, you should see something like this in the serial monitor window:


If the real time clock loses power, it will display 0:0:0. The seconds will stop counting. After setting the time, a new countdown will begin. It is for this reason that the battery cannot be removed while the real-time clock module is running.

Setting the time on the clock module

In the same sketch, uncomment the line that starts with RTC.adjust:

// the line below is used to set the date and time of the clock

RTC.adjust(DateTime(__DATE__, __TIME__));

The process of setting the date and time is very elegant. This line contains data from your counter on your personal computer (at the time the code is compiled). This data is used to flash your real time clock module. That is, if the time on your PC is set incorrectly, we recommend that you first fix this bug and then move on to flashing the clock module for Arduino.

After setup, open the serial monitor and make sure the clock is set correctly:


All. From now on, and for the next few years, there will be no need to configure the DS1307.

Reading time from DS1307

Once the DS1307 real-time clock is configured, it can send queries to it. Let's look at the part of the sketch that implements these queries.

DateTime now = RTC.now();

Serial.print(now.year(), DEC);

Serial.print("/");

Serial.print(now.month(), DEC);

Serial.print("/");

Serial.print(now.day(), DEC);

Serial.print(" ");

Serial.print(now.hour(), DEC);

Serial.print(":");

Serial.print(now.minute(), DEC);

Serial.print(":");

Serial.print(now.second(), DEC);

Serial.println();

Essentially there is one option for getting time using a real time clock. To do this, use the now() function, which returns a DateTime object. This object contains data about the year, month, day, hour, minute and second.

There are a number of real-time clock libraries that provide functions like RTC.year() and RTC.hour(). These functions pull out the year and hour separately. But their use comes with a number of problems: if you make a request to display the minutes at a time, for example, 3:14:59, that is, right before the minutes reading should equal “15” (3:15:00), the resulting data will be equal to 3:14:00 - that is, you will lose one minute.

In general, the use of separate functions for calling the hour or year is justified only if the accuracy of time control with a spread of one minute/year is not critical for your project (as a rule, this is in cases where readings are taken rarely - once a day , once a week). In any case, if you want to avoid errors in readings, use now(), and from the received data, extract the readings you need (minutes, years, etc.).

There is another data format that we can learn - the number of seconds since midnight, January 1, 1970. The unixtime() function is used for this:

Serial.print(" since 1970 = ");

Serial.print(now.unixtime());

Serial.print("s = ");

Serial.print(now.unixtime() / 86400L);

Serial.println("d");

Since there are 60*60*24 = 86400 seconds in one day, you can convert the resulting value into days and years. A very convenient option if you need to track how much time has passed since the last request. For example, if 5 minutes have passed since the Arduino last accessed the DS1307 real-time clock, the value returned by the unixtime() function will be greater than 300.

Leave your comments, questions and share your personal experiences below. New ideas and projects are often born in discussions!







2024 gtavrl.ru.