如何用运行Windows 10 IoT Core的树莓派读取DS3231 RTC时间并显示于IoT仪表板
嗨,我来一步步帮你搞定在Windows 10 IoT Core树莓派上读取DS3231 RTC模块并在IoT仪表板显示的问题!
步骤1:准备工作
确保你手头有这些东西:
- 刷好Windows 10 IoT Core系统的树莓派(建议用3B/3B+及以上型号)
- DS3231 RTC模块
- 若干杜邦线
- 已安装Windows 10 IoT仪表板的电脑
- 树莓派已联网,能被电脑上的IoT仪表板识别到
步骤2:硬件接线
DS3231通过I2C协议通信,接线对应关系如下(树莓派引脚按BCM编号):
- DS3231的VCC → 树莓派3.3V引脚(千万别接5V,容易烧模块)
- DS3231的GND → 树莓派GND引脚
- DS3231的SDA → 树莓派GPIO2引脚
- DS3231的SCL → 树莓派GPIO3引脚
接好线后,记得在IoT仪表板里启用I2C:找到你的树莓派设备,进入「设备设置」,找到I2C控制器选项并开启。
步骤3:编写UWP应用读取DS3231
Windows 10 IoT Core主要用UWP开发,这里用C#为例:
- 在Visual Studio中创建空白UWP项目,目标版本选择与Windows 10 IoT Core匹配的版本。
- 编辑
Package.appxmanifest,添加I2C权限:
<Capabilities> <DeviceCapability Name="lowLevel" /> </Capabilities>
- 在
MainPage.xaml中添加一个用于显示时间的控件:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <TextBlock x:Name="DateTimeDisplay" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="28" Foreground="White"/> </Grid>
- 在
MainPage.xaml.cs中编写读取DS3231的核心代码:
using Windows.Devices.I2c; using System.Threading.Tasks; using Windows.UI.Core; namespace DS3231Reader { public sealed partial class MainPage { public MainPage() { InitializeComponent(); _ = ReadRtcDataLoopAsync(); } private async Task ReadRtcDataLoopAsync() { // DS3231的固定I2C地址是0x68 var i2cSettings = new I2cConnectionSettings(0x68) { BusSpeed = I2cBusSpeed.FastMode }; // 获取树莓派的I2C控制器(默认是I2C1) var controller = await I2cController.GetDefaultAsync(); if (controller == null) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { DateTimeDisplay.Text = "未检测到I2C控制器"; }); return; } using var rtcDevice = controller.GetDevice(i2cSettings); while (true) { // 从DS3231的0x00寄存器开始读取7字节数据(秒、分、时、星期、日、月、年) byte[] readBuffer = new byte[7]; rtcDevice.WriteRead(new byte[] { 0x00 }, readBuffer); // 将BCD格式的数值转为十进制(DS3231输出是BCD编码) int seconds = BcdToDecimal(readBuffer[0]); int minutes = BcdToDecimal(readBuffer[1]); int hours = BcdToDecimal(readBuffer[2]); int day = BcdToDecimal(readBuffer[4]); int month = BcdToDecimal((byte)(readBuffer[5] & 0x1F)); // 屏蔽世纪位 int year = 2000 + BcdToDecimal(readBuffer[6]); // 构造DateTime对象 var currentTime = new DateTime(year, month, day, hours, minutes, seconds); // 更新UI(必须在UI线程执行) await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { DateTimeDisplay.Text = $"DS3231时间:\n{currentTime:yyyy-MM-dd HH:mm:ss}"; }); // 每秒刷新一次 await Task.Delay(1000); } } // BCD转十进制的辅助方法 private int BcdToDecimal(byte bcdValue) { return ((bcdValue >> 4) * 10) + (bcdValue & 0x0F); } } }
步骤4:部署应用到树莓派
在Visual Studio中,将目标设备选择为你的树莓派(可以通过IoT仪表板获取设备名称或IP),点击「部署」按钮。部署成功后,树莓派上会自动启动这个应用,屏幕上会显示从DS3231读取到的时间。
步骤5:在Windows 10 IoT仪表板查看
- 打开Windows 10 IoT仪表板,找到你的树莓派设备。
- 点击「设备门户」,输入树莓派的用户名(默认
Administrator)和密码(默认password)进入设备管理界面。 - 在设备门户中,你可以查看运行中的应用状态,也可以通过「远程桌面」功能直接查看树莓派屏幕上的时间显示;如果需要更定制化的仪表板展示,还可以将时间数据上传到Azure IoT中心,再通过Power BI等工具制作可视化仪表板。
内容的提问来源于stack exchange,提问作者Shreyas Dattashivarama
相关产品推荐
相关产品推荐

