使用在Windows 10 IoT核心版上运行的raspberrypi从RTC模块获取日期和时间,并在Windows 10 IoT仪表板上显示日期时间

问题描述

谁能告诉我如何使用Windows 10 IoT核心版上运行的RaspBerrypi从RTC模块DS3231读取日期和时间,并在IoT仪表板中显示日期和时间。 预先谢谢你。

解决方法

我们可以通过I2C端口将DS3231模块连接到Raspberry Pi,以便在Windows IoT核心版上与您的应用程序通信模块。然后请参考以下代码以读取日期和时间。

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));
 }