Could anyone tell me as to how to read date and time from RTC module DS3231 using Raspberrypi running on windows 10 IoT core and displaying the date and time in the IoT dashboard. Thanking you in advance.
Asked
Active
Viewed 193 times
0
-
1can you suggest what have you tried ? so one can help you. – Ashok Rathod Nov 09 '20 at 14:48
1 Answers
0
We can connect DS3231 module to Raspberry Pi through I2C port, in order to communicate module with your application on Windows IoT Core. And then please refer to following code to read the date and time.
public async Task<DateTime> ReadDateTime()
{
I2cController i2c = await I2cController.GetDefaultAsync();
I2cConnectionSettings setting = new I2cConnectionSettings(0x68);
setting.BusSpeed = I2cBusSpeed.StandardMode;
var device = i2c.GetDevice(setting);
byte[] writeBuf = { 0x00 };
device.Write(writeBuf);
byte[] buffer = new byte[7];
device.Read(buffer);
byte second = BcdToDec((byte)(buffer[0] & 0x7f));
byte minute = BcdToDec(buffer[1]);
byte hour = BcdToDec((byte)(buffer[2] & 0x3f));
byte dayOfWeek = BcdToDec(buffer[3]);
byte dayOfMonth = BcdToDec(buffer[4]);
byte month = BcdToDec(buffer[5]);
int year = 2000 + BcdToDec(buffer[6]);
DateTime dt = new DateTime(year, month, dayOfMonth, hour, minute, second);
device.Dispose();
return dt;
}
private byte DecToBcd(byte val)
{
return Convert.ToByte((val / 10 * 16) + (val % 10));
}
private byte BcdToDec(byte val)
{
return Convert.ToByte((val / 16 * 10) + (val % 16));
}

Michael Xu
- 4,382
- 1
- 8
- 16