如何使用DS3231时钟模块
这个项目将展示如何使用实时时钟模块(DS3231),并将在串口监视器上显示时钟值。
DS3231实时时钟模块
DS3231时钟模块是一个可以测量时间值的模块,它可以独立使用,也可以依赖于Arduino开发板使用,Arduino开发板可以通过它测量时钟模块打开以来的运行时间(单位:ms)。该模块安装纽扣电池后即可使用。

DS3231模块参数
尺寸:38mm(长)22mm(宽)14mm(高)
重量:8g
工作电压:3.3–5.5V
时钟芯片:高精度时钟芯片DS3231
时钟精度:0-40℃范围内,精度2ppm,年误差约1分钟,2个日历闹钟可编程方波输出,实时时钟产生秒、分、时、星期、日期、月和年计时,并提供有效期到2100年的闰年补偿芯片内部自带温度传感器,精度为±3℃。
存储芯片:AT24C32(存储容量32K),IIC总线接口,最高传输速度400KHz(工作电压为5V时),可级联其它IIC设备,24C32地址可通过短路A0/A1/A2修改,默认地址为0x57 带可充电电池LIR2032,保证系统断电后,时钟任然正常走动 。
DS3231接口定义

左侧为连接开发板的I2C接口,右侧是连接外联设备的I2C及其它接口。
与Arduino开发板的连接
Arduino SCL –> DS3231 SCL
Arduino SDA –> DS3231 SDA
Arduino VCC –> DS3231 5V ( or 3.3V )
Arduino GND –> DS3231 GND
测试代码
#include "Wire.h" #define DS3231_I2C_ADDRESS 0x68 byte decToBcd(byte val) { return( (val/10*16) + (val%10) ); } byte bcdToDec(byte val) { return( (val/16*10) + (val%16) ); } void setup() { Wire.begin(); Serial.begin(9600); } void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte dayOfMonth, byte month, byte year) { Wire.beginTransmission(DS3231_I2C_ADDRESS); Wire.write(0); Wire.write(decToBcd(second)); Wire.write(decToBcd(minute)); Wire.write(decToBcd(hour)); Wire.write(decToBcd(dayOfWeek)); Wire.write(decToBcd(dayOfMonth)); Wire.write(decToBcd(month)); Wire.write(decToBcd(year)); Wire.endTransmission(); } void readDS3231time(byte *second, byte *minute, byte *hour, byte *dayOfWeek, byte *dayOfMonth, byte *month, byte *year) { Wire.beginTransmission(DS3231_I2C_ADDRESS); Wire.write(0); Wire.endTransmission(); Wire.requestFrom(DS3231_I2C_ADDRESS, 7); *second = bcdToDec(Wire.read() & 0x7f); *minute = bcdToDec(Wire.read()); *hour = bcdToDec(Wire.read() & 0x3f); *dayOfWeek = bcdToDec(Wire.read()); *dayOfMonth = bcdToDec(Wire.read()); *month = bcdToDec(Wire.read()); *year = bcdToDec(Wire.read()); } void displayTime() { byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year); Serial.print(hour, DEC); Serial.print("h"); if (minute<10) { Serial.print("0"); } Serial.print(minute, DEC); Serial.print("min"); if (second<10) { Serial.print("0"); } Serial.print(second, DEC); Serial.print("sec "); Serial.print(dayOfMonth, DEC); Serial.print("/"); Serial.print(month, DEC); Serial.print("/"); Serial.print(year, DEC); Serial.print(" "); Serial.print(" Day : "); switch(dayOfWeek){ case 1: Serial.println("Sunday"); break; case 2: Serial.println("Monday"); break; case 3: Serial.println("Tuesday"); break; case 4: Serial.println("Wednesday"); break; case 5: Serial.println("Thursday"); break; case 6: Serial.println("Friday"); break; case 7: Serial.println("Saturday"); break; } } void loop() { displayTime(); delay(1000); }
上传代码后,打开Arduino IDE的串口监视器即可看到输出信息。