从课外获取SPI温度数据

我正在尝试编写一个“温度”类来处理通过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。

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

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