首页 > 解决方案 > 使用在 Windows 10 IoT 核心上运行的 raspberrypi 从 RTC 模块获取日期和时间,并在 Windows 10 IoT 仪表板上显示日期时间

问题描述

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

标签: c#raspberry-pi3windows-10-iot-corereal-time-clock

解决方案


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

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

推荐阅读