C# iot 连接pcf8563 rtc

// See https://aka.ms/new-console-template for more information
using Iot.Device.Ft232H;
using Iot.Device.FtCommon;
using Iot.Device.Rtc;
using System;
using System.Device.I2c;

namespace Ft232hPcf8563
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. 初始化 FT232H
            var devices = FtCommon.GetDevices();
            if (devices.Count > 0)
            {
                var ft232h = new Ft232HDevice(devices[0]);
                I2cConnectionSettings Settings = new I2cConnectionSettings(0, 0x51);
                // 2. 打开 FT232H 的 I2C 总线
                var i2cDevice = ft232h.CreateI2cDevice(Settings);

                // 4. 初始化 RTC
                Pcf8563 rtc = new Pcf8563(i2cDevice);
                // ==============================================
                // 【关键】启动 RTC + 设置当前真实时间
                // ==============================================
                try
                {
                    rtc.LocalTimeZone = TimeZoneInfo.Local;
                    // 设置为电脑当前时间
                    rtc.DateTime = DateTime.Now;

                    Console.WriteLine("RTC 已启动并设置时间:" + rtc.DateTime);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("设置时间失败:" + ex.Message);
                }

                // ==========================================
                // 【只需要运行一次】设置当前时间
                // ==========================================
                // rtc.DateTime = DateTime.Now;

                // 循环读取时间
                while (true)
                {
                    DateTime now = rtc.RtcDateTime;
                    Console.WriteLine($"RTC 时间:{now:yyyy-MM-dd HH:mm:ss}");
                    System.Threading.Thread.Sleep(1000);
                }
            }
        }
    }
}

image

posted @ 2026-04-16 19:11  微笑的''80  阅读(14)  评论(0)    收藏  举报