Подключение RTC часы реального времени DS1302, DS1307, DS3231 к Arduino
Для подключения RTC часов реального времени DS1302, DS1307, DS3231, была разработана универсальная библиотека.
Подключение:
Подключение DS1307 к Arduino :
RTC DS1307 | Arduino UNO |
---|---|
GND | GND |
VCC | +5V |
SDA | A4 |
SCL | A5 |
Подключение DS1302 к Arduino :
RTC DS1302 | Arduino UNO |
---|---|
GND | GND |
VCC | +5V |
RST | 10 (Можно изменить на другие в скетче) |
CLK | 13 (Можно изменить на другие в скетче) |
DAT | 12 (Можно изменить на другие в скетче) |
Подключение DS3231 к Arduino :
RTC DS3231 | Arduino UNO | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
GND | GND | ||||||||||
VCC | +5V | ||||||||||
SDA | A4 | ||||||||||
SCL | A5 Программа:В зависимости от того какой модуль Вы подключаете, необходимо в программе указать Для DS1307: Для DS1302 : Для DS3231 : Пример установки текущего времени в RTC модуль (DS1307): Пример считывания текущего времени с RTC модуля (DS1307) и вывод в «Последовательный порт» : Преимущества библиотеки: — библиотека имеет внутренние функции аппаратной обработки протоколов передачи данных I2C и SPI, а следовательно не требует подключения дополнительных библиотек, но и не конфликтует с ними, если таковые всё же подключены. — библиотека имеет внутренние функции программой обработки протокола передачи данных 3-Wire — для инициализации модуля необходимо вызвать функцию begin с названием модуля. — подключение модулей осуществляется к аппаратным выводам arduino используемой шины (за исключением 3-Wire) — простота установки и чтения времени функциями settime и gettime функция settime может устанавливать дату и время, как полностью, так и частично (например только минуты, или только день, и т.д.) функция gettime работает как функция date в php, возвращая строку со временем, но если её вызвать без параметра, то функция ничего не вернёт, а время можно прочитать из переменных в виде чисел. — библиотека расширяемая, то есть для того, чтоб она работала с новым модулем, нужно указать параметры этого модуля в уже существующих массивах файла RTC.h (тип шины, частота шины в кГц, режимы работы, адреса регистров и т.д.), как всё это сделать, описано в файле extension.txt Таким образом добавив новый модуль в библиотеку, мы лишь увеличим область занимаемой динамической памяти на 36 байт, при этом не затронув область памяти программ. — при вызове функции begin, библиотека читает флаги регистров модуля и при необходимости устанавливает или сбрасывает их так, чтоб модуль мог работать от аккумуляторной батареи, а на программируемом выводе меандра (если таковой у модуля есть) установилась частота 1Гц, тогда этот вывод можно использовать в качестве внешнего посекундного прерывания. — при работе с модулем DS1302 не нужны никакие резисторы на выводе GND (которые нужны для его работы с другими библиотеками этого модуля), это достигнуто тем, что для шины 3-Wire указана конкретная частота 10кГц, не зависимо от частоты CPU arduino. — в библиотеке реализована еще одна не обязательная функция period, принимающая в качестве единственного аргумента — количество минут (от 1 до 255) если в течении указанного времени была вызвана функция gettime несколько раз, то запрос к модулю по шине будет отправлено только в первый раз, а ответом на все остальные запросы будет сумма времени последнего ответа модуля и времени прошедшего с этого ответа. Функцию period достаточно вызвать один раз. Обзор часов реального времени DS1307 (RTC)Автор: Сергей · Опубликовано 24.11.2016 · Обновлено 13.04.2020 DS1307 это небольшой модуль, предназначенный для подсчета времени. Собранный на базе микросхемы DS1307ZN с реализацией питания от литиевой батарейки (LIR2032), что позволяет работать автономно в течение длительного времени. Также на модуле, установлена энергонезависимая память EEPROM объемом 32 Кбайт (AT24C32). Микросхема AT24C32 и DS1307ZN связаны обшей шиной интерфейсом I2C. Технические параметры► Напряжение питания: 5В Общие сведенияИспользовании модуля DS1307 зачастую очень оправдано, например, когда данные считываются редко, интервалом более недели, использовать собственные ресурсы контроллера, неоправданно или невозможно. Обеспечивание бесперебойное питание, например платы Arduino, на длительный срок дорого, даже при использовании батареи. Обмен данными с другими устройствами осуществляется по интерфейсу I2C с выводов SCL и SDA. Конденсаторы С1 и С2 необходимы для снижения помех по линию питания. Чтобы обеспечить надлежащего уровня сигналов SCL и SDA установлены резисторы R2 и R3 (подтянуты к питанию). Для проверки работоспособности модуля, на вывод 7 микросхему DS1307Z, подается сигнал SQ, прямоугольной формы с частотой 1 Гц. Элементы R4, R5, R6, VD1 необходимы для подзарядку литиевой батарейки. Так же, на плате предусмотрено посадочное место (U1), для установки датчика температуры DS18B20 (при необходимости можно впаять его), считывать показания, можно с вывода DS, который подтянут к пиатнию, через резистор R1 сопротивлением 3.3 кОм. Принципиальную схему и назначение контактов можно посмотреть на рисунках ниже. На плате расположено две группы контактов, шагом 2.54 мм, для удобного подключения к макетной плате, буду использовать штырьевые разъемы, их необходимо впаять. Первая группа контактов: Вторая группа контактов: Подзарядка батареи Подключение DS1307 к ArduinoНеобходимые детали: Подключение: Установка времени DS1307 Interfacing DS1307 RTC Module with Arduino & Make a Reminder © GPL3+In this tutorial, you will learn how to use RTC DS1307 module with Arduino to make a reminder. You can read this and other amazing tutorials onElectroPeak’s official website In many electronic projects it is necessary to run an operation according to the time or date And the calculation of the time and date shouldn’t stop when the system shuts down. For this purpose, Real Time Clock (RTC) modules are used. In this tutorial, you will learn how to use RTC DS1 with Arduino to make a reminder. What You Will Learn:
What is Real Time Clock? Real Time Clock or RTC is a system that keeps track of the current time and can be used in any device which needs to keep accurate time. You can also keep tracking the exact time without using RTC systems, but RTCs have some important advantages. Here are some of these advantages:
RTCs often have an alternate source of power, so that they can continue to keep time while the primary source of power is off or unavailable. RTCs often use a 32.768 kHz crystal oscillator. But why 32, 768? 32768 is equal to 215 and hence can generate 1 second easily. Also, the crystal must be small with proper width and low power consumption, which can be satisfied with using 32876 Hz. Higher frequencies are larger and fragile crystals, and the lower frequencies have more power consumption that 32, 768KHz. You can also keep tracking the exact time without using RTC systems, but RTCs have some important advantages. Here are some of these advantages:
RTCs often have an alternate source of power, so that they can continue to keep time while the primary source of power is off or unavailable. RTCs often use a 32.768 kHz crystal oscillator. But why 32, 768? 32768 is equal to 215 and hence can generate 1 second easily. Also, the crystal must be small with proper width and low power consumption, which can be satisfied with using 32876 Hz. Higher frequencies are larger and fragile crystals, and the lower frequencies have more power consumption that 32, 768KHz. DS1307 Module Feature & Specifications DS1307 module is one of the most affordable and common RTCs modules. It can accurately keep track of seconds, minutes, hours, days, months, and years. Some of the DS1307 important features are:
The DS1307 module has the capability to install a 3-volt CR2023 backup battery. there is also an embedded EEPROM 24c32 memory on this module that can save 32kb of data. In addition, you can measure the environment temperature by installing a DS18B20 sensor on the built-in-place. And you can also read the backup battery voltage from BAT pin. Guide for Real Time Clock (RTC) Module with Arduino (DS1307 and DS3231)This post is about how to use the DS1307 Real Time Clock (RTC) module with the Arduino. You can also follow this guide for other similar modules like the DS3231 RTC. Introducing the Real Time Clock moduleThe real time clock module is the one in the figure below (front and back view). When you first use this module, you need to solder some header pins. As you can see in the picture above, the module has a backup battery installed. This allows the module to retain the time, even when it’s not being powered up by the Arduino. This way, every time you turn on and off your module, the time doesn’t reset. This module uses I2C communication. This means that it communicates with the Arduino using just 2 pins. Where to buy?The Real Time Clock is an affordable module. You can check the DS1307 Real Time Clock module on Maker Advisor and find the best price. Pin WiringWiring the RTC module is pretty straightforward!
If you’re using other Arduino board rather than the uno, chek out what are their SCL and SDA pins.
Example: Displaying date and time on the serial monitorThis example displays date and time on the serial monitor. Parts requiredFor this example you need the following parts (click the links below to find the best price at Maker Advisor): You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price! SchematicsConnect your Real Time Clock module to your Arduino as in the schematics below. Working with the RTC requires two important steps:
Set the current time in the Real Time ClockFor setting the current time you need to change the code provided.
The parameters for the function are highlighted in red: seconds, minutes, hours, day of the week, date, month and year (in this order). Sunday is the day 1 of the week and Saturday is 7. Don’t forget to uncomment that line of code. After setting the current time, you can upload the provided code with the required modifications. The code provided was written by John Boxall from tronixstuff. You can read his tutorial here. Retain the time in the Real Time ClockIf you don’t want to reset the time everytime the RTC is turned off, you should do the following:
This is a very important step to set up the time in your RTC. If you don’t do this, everytime your RTC resets, it will display the time that you’ve set up previously and not the current time. DemonstrationOpen the serial monitor at a baud rate of 9600 and you’ll see the results. Here’s the Serial Monitor displaying the current date and time. Wrapping upI hope you’ve found this guide useful. The RTC module is really useful and you can use it as a clock, timer, etc.. If you would like to display the date and time with the RTC module in the OLED display, check the following post: What projects have you done or are you expecting to build with this module? Let me know by writing a comment down below. Thanks for reading,
[eBook] Build Web Servers with ESP32 and ESP8266 (2nd Edition)Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD » Recommended ResourcesBuild a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED. Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects. Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience! What to Read Next…ESP32 NTP Time – Setting Up Timezones and Daylight Saving TimeBetter Debugging for Arduino IDE: SerialDebug Library (Part 1)ESP8266 DS18B20 Temperature Sensor with Arduino IDE (Single, Multiple, Web Server)Enjoyed this project? Stay updated by subscribing our newsletter!31 thoughts on “Guide for Real Time Clock (RTC) Module with Arduino (DS1307 and DS3231)”Excellent!! You’re welcome! Thanks for reading Hi Rui. I plan to pay the book tomorrow (home automation vith esp8266). But now i wonder can i use RTC and arduino as trigger at some def moment to send me a message etc information on my serial monitor from analog sensor via SIM800L modul on my mobile phone? You should be able to do that, but I don’t have any tutorials on that exact subject. Thanks for asking, Hello, good morning. Could you please tell me how you did this figure on fritzing, because I’ve tried and I don’t found on it? Thank you. Simply search for “RTC Arduino fritzing part” and add it to your Fritzing parts lits thank you very much riu how to apply this to RFID attendance system Hi. Hi! The day of the month doesn’t change, what line am I missing that controls this. Everything else works fine. Thanks! Great project. Hi Jim. Sara Santos Thank you very much for your information Hi👋 I’m trying to work on RTC with ESP32 Cam but unfortunately I don’t know where to connect SDA and SCL of RTC to esp32 cam. Can you please help me on how to make it work? Hi. Hi, do you have an idea on how to update the RTC time directly with an NTP server ? It could be done once at the initialisation to be sure the RTC remains precise. Thanks Rui and Sara ! Good question, so our rtc will update despite DST changes. Hi Rui and Sara, and congratulations always for your instructive and interesting guides. Hi Mike. Thanks for putting this together. Just learning how to deal with all of this. Is there any info on using the rtc to drive an action every other day? Is it safe to connect the VCC to the pin which i have defined HIGH? void setup() < I have connected led to gpio 15 of my esp8266. I left the gpip15 high, after 2sec led will be off because of sleep. So can i use that 2sec to read time? Or is there any risk that I’m missing? I don’t want to destroy my ds3231. I have learnt too much from here because your tutorial are filtered beautifully. Thanks. Hi. i cant use rfid and sd card together, becuse if sd card avelable, rfid cant worked and conflict miso pin, plz hep to me Hi. Interesting, I noted that this isn’t dependent upon an external library. Is that because the sketch provides all the utility that’s needed? Thank you Hello Rui, Awesome! I am currently working on building a seven segment 4 digit clock using the uno, ds3231, and 114 ws2812b leds. I wanted to build a large display. I’m new at all of this so I’m hoping to find enough info to make it work. Thanks! Hi Rui and Sara, and congratulations always for your instructive and interesting guides. Can u Add this for Temperature on DS3231on your exemple ?? Maybe this help. void showTemperature() < Wire.requestFrom(DS3231_I2C_ADDRESS, 2); // Serial.print(“Temperature : “); Serial.print ((float)msb + (lsb >> 6) * 0.25f ); Serial.print(” C “); I see that there is nearly full consensus that this code works for setting and keeping the time even when disconnected from power. I have done this and many other “ideas” from various people on the web and my DS3231 clocks never keep the correct time if I unplug it from power with a battery in it. I have wasted hours taking out and replacing batteries, restarting, etc. etc. etc. Yes, etc. So, what I do now is put in two buttons to manually advance the hour and/minute settings when my clock starts up. All I need are the clock times so this works well for my clocks and I never have to worry again about the RTC keeping the correct time. No need to respond, I have given up on having my RTC’s retain the correct time. Buy another DS3231 – your unit must be faulty. Retain the time in the Real Time Clock after setting up the time, you should comment the function that sets the time and upload the code again. This is a very important step to set up the time in your RTC. If you don’t do this, everytime your RTC resets, it will display the time that you’ve set up previously and not the current time. hi rui i want to interface the ds3231 with esp8266 ow do i go about it Adblockdetector |