Name | Board Pin |
---|---|
32K | N/A |
SQW | N/A |
SCL | 5 |
SDA | 3 |
VCC | 1/17 |
GND | 6/9/14/20/25/30/34/39 |
using System;
using Windows.Devices.I2c;
namespace CYFang
{
/// <summary>
/// RS3231 RTC
/// </summary>
public class DS3231 : IDisposable
{
/// <summary>
/// Slave address
/// </summary>
private const int SLAVE_ADDRESS = 0x68;
/// <summary>
/// I2C
/// </summary>
private I2cDevice device;
/// <summary>
/// DS3231
/// </summary>
public DS3231()
{
InitI2C();
}
/// <summary>
/// Init I2C
/// </summary>
private async void InitI2C()
{
var settings = new I2cConnectionSettings(SLAVE_ADDRESS);
var controller = await I2cController.GetDefaultAsync();
device = controller.GetDevice(settings);
}
/// <summary>
/// Set date and time to DS3231
/// </summary>
/// <param name="dt"></param>
public void SetDateTimeToDS3231(DateTime dt)
{
byte write_seconds = DecToBcd(dt.Second);
byte write_minutes = DecToBcd(dt.Minute);
byte write_hours = DecToBcd(dt.Hour);
byte write_dayofweek = DecToBcd((int)dt.DayOfWeek);
byte write_day = DecToBcd(dt.Day);
byte write_month = DecToBcd(dt.Month);
byte write_year = DecToBcd(dt.Year % 100);
byte[] write_time = { 0x00, write_seconds, write_minutes, write_hours, write_dayofweek, write_day, write_month, write_year };
device.Write(write_time);
}
/// <summary>
/// Get date and time from DS3231
/// </summary>
/// <returns></returns>
public DateTime GetDateTimeFromDS3231()
{
byte[] writeBuff = { 0x00 };
device.Write(writeBuff);
byte[] readBuff = new byte[7];
device.Read(readBuff);
int second = BcdToDec((byte)(readBuff[0] & 0x7f));
int minute = BcdToDec(readBuff[1]);
int hour = BcdToDec((byte)(readBuff[2] & 0x3f));
int dayOfWeek = BcdToDec(readBuff[3]);
int dayOfMonth = BcdToDec(readBuff[4]);
int month = BcdToDec(readBuff[5]);
int year = BcdToDec(readBuff[6]) + 2000;
return new DateTime(year, month, dayOfMonth, hour, minute, second);
}
/// <summary>
/// Binary-Coded Decimal
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
private static byte DecToBcd(int val) { return (byte)((val / 10 * 16) + (val % 10)); }
/// <summary>
/// Binary-Coded Decimal
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
private static int BcdToDec(int val) { return ((val / 16 * 10) + (val % 16)); }
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
if (device != null)
{
device.Dispose();
device = null;
}
}
}
}
參考資料:
https://datasheets.maximintegrated.com/en/ds/DS3231.pdf