从课堂外获取SPI温度数据

时间:2016-06-26 13:06:24

标签: c# uwp windows-10-universal windowsiot

我正在尝试编写一个“温度”类来处理通过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()时,我的值总是为空。

任何人都可以帮我弄清楚我做错了什么吗?谢谢。

1 个答案:

答案 0 :(得分:0)

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