|
在本篇文章中,我们将学习如何基于Arduino开发板使用DS3231实时时钟模块。这里第一个问题是,当Arduino本身具有内置计时器时,为什么我们实际上需要为Arduino项目提供单独的RTC。好吧,原因就是RTC模块使用电池运行,即使我们重新编程微控制器或断开主电源,也可以保持时间运行。
DS3231实时时钟 DS3231是一款低成本、高精度的实时时钟,可以保持小时、分钟和秒,以及日、月和年等信息。此外,它还可以自动补偿闰年和少于31天的月份。
该模块可以在3.3或5 V下工作,这使其适用于许多开发平台或微控制器。电池输入为3V,常见的3V纽扣电池CR2032可为模块供电,并且保持超过一年的信息。
该模块使用I2C通信协议,这使得与Arduino板的连接变得非常容易。
以下是电路原理图:
所以我们需要的是4根线,用于为模块供电的VCC和GND引脚,以及两个I2C通信引脚,SDA和SCL。
本篇文章所需的组件如下所示:
● DS3231实时时钟 ● Arduino开发板 ● 面包板和跳线
程序设计 一旦我们连接模块,我们需要对Arduino开发板进行编程以使用实时时钟。但是,在编写Arduino和I2C模块之间的通信时,代码并不是那么小而且容易。幸运的是,DS3231 RTC已经有几个库,可以在互联网上找到这些库。
在本篇文章中,我选择使用Henning Karlsen制作的库文件,可以在他的网站www.rinkydinkelectronics.com上找到并下载。
因此,一旦我们下载并安装了库,我们就可以使用它的第一个演示示例来初始激活RTC模块的时钟。在演示示例代码的setup函数部分,我们可以注意到有三行代码需要取消注释才能初始设置星期几、时间和数据。 - // Code from the Demo Example of the DS3231 Library
- void setup()
- {
- // Setup Serial connection
- Serial.begin(115200);
- // Uncomment the next line if you are using an Arduino Leonardo
- //while (!Serial) {}
-
- // Initialize the rtc object
- rtc.begin();
-
- // The following lines can be uncommented to set the date and time
- //rtc.setDOW(WEDNESDAY); // Set Day-of-Week to SUNDAY
- //rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
- //rtc.setDate(1, 1, 2014); // Set the date to January 1st, 2014
- }
复制代码
第一行用于设置星期几,第二行用于设置以小时、分钟和秒为单位的时间,第三行用于设置以日、月和年为单位的日期。
上传该代码后,我们需要重新注释掉这三行代码并重新上传代码。 - // Code from the Demo Example of the DS3231 Library
- void loop()
- {
- // Send Day-of-Week
- Serial.print(rtc.getDOWStr());
- Serial.print(" ");
-
- // Send date
- Serial.print(rtc.getDateStr());
- Serial.print(" -- ");
- // Send time
- Serial.println(rtc.getTimeStr());
-
- // Wait one second before repeating
- delay (1000);
- }
复制代码
如果我们看一下代码的loop函数部分,我们可以看到现在使用三个自定义函数,我们从RTC获取信息并在串口监视器中打印它们。 以下是它们在串口监视器中的显示方式。
现在,即使我们断开Arduino电源,然后重新连接并再次运行串口监视器,我们也可以注意到时间不会复位。
所以现在我们的实时时钟启动并运行,可以在任何Arduino项目中使用。 在第二个例子中,我们将LCD显示屏连接到Arduino,并在显示屏上打印显示时间和日期。
以下是这个例子的源代码: - /*
- * Arduino DS3231 Real Time Clock Module Tutorial
- *
- * Crated by Dejan Nedelkovski,
- * www.HowToMechatronics.com
- *
- * DS3231 Library made by Henning Karlsen which can be found and downloaded from his website, www.rinkydinkelectronics.com.
- *
- */
- #include <DS3231.h>
- #include <LiquidCrystal.h> // includes the LiquidCrystal Library
- DS3231 rtc(SDA, SCL);
- LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)
- void setup() {
- rtc.begin(); // Initialize the rtc object
- lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display }
- }
- void loop() {
- lcd.setCursor(0,0);
- lcd.print("Time: ");
- lcd.print(rtc.getTimeStr());
-
- lcd.setCursor(0,1);
- lcd.print("Date: ");
- lcd.print(rtc.getDateStr());
-
- delay(1000);
- }
复制代码
以上就是本篇文章的全部内容,如果遇到任何问题,可以在本帖下面进行回复。 |