1

我正在尝试编写一个“温度”类来处理通过 SPI 与我的 RaspberryPi 通信以读取一些温度数据。目标是能够从我的温度类外部调用 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() 时,我的值始终为空。

谁能帮我弄清楚我做错了什么?谢谢你。

4

1 回答 1

0

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

于 2016-06-26T15:40:38.793 回答