从外部获取SPI温度数据

本文关键字:数据 温度 SPI 获取 从外部 | 更新日期: 2023-09-27 17:49:18

我试图写一个类"Temperature",处理通过SPI与我的RaspberryPi通信以读取一些温度数据。目标是能够从Temperature类外部调用GetTemp()方法,以便在程序的其余部分需要温度数据时使用温度数据。

我的代码是这样设置的:
public sealed class StartupTask : IBackgroundTask
{
    private BackgroundTaskDeferral deferral;
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        deferral = taskInstance.GetDeferral();
        Temperature t = new Temperature();
        //Want to be able to make a call like this throughout the rest of my program to get the temperature data whenever its needed
        var data = t.GetTemp();
    }
}
温度类:

class Temperature
{
    private ThreadPoolTimer timer;
    private SpiDevice thermocouple;
    public byte[] temperatureData = null;
    public Temperature()
    {
        InitSpi();
        timer = ThreadPoolTimer.CreatePeriodicTimer(GetThermocoupleData, TimeSpan.FromMilliseconds(1000));
    }
    //Should return the most recent reading of data to outside of this class
    public byte[] GetTemp()
    {
        return temperatureData;
    }
    private async void InitSpi()
    {
        try
        {
            var settings = new SpiConnectionSettings(0);
            settings.ClockFrequency = 5000000;
            settings.Mode = SpiMode.Mode0;
            string spiAqs = SpiDevice.GetDeviceSelector("SPI0");
            var deviceInfo = await DeviceInformation.FindAllAsync(spiAqs);
            thermocouple = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings);
        }
        catch (Exception ex)
        {
            throw new Exception("SPI Initialization Failed", ex);
        }
    }
    private void GetThermocoupleData(ThreadPoolTimer timer)
    {
        byte[] readBuffer = new byte[4];
        thermocouple.Read(readBuffer);
        temperatureData = readBuffer;
    }
}

当我在GetThermocoupleData()中添加一个断点时,我可以看到我正在获得正确的传感器数据值。但是,当我从类外部调用t.GetTemp()时,我的值总是null。

有谁能帮我找出我做错了什么吗?谢谢你。

从外部获取SPI温度数据

GetThermocouplerData()必须至少被调用一次才能返回数据。在您的代码示例中,直到实例化后1秒才运行它。只需在尝试块的最后一行中添加对InitSpi中的GetThermocoupleData(null)的调用,以便它开始时已经至少有1个调用。