1
我正在尝试编写一个类“Temperature”来处理与RaspberryPi通过SPI进行通信以读取一些温度数据。我们的目标是能够从我的Temperature类以外的地方调用GetTemp()方法,以便我可以在我的程序的其余部分中随时使用温度数据。从外部获取SPI温度数据
我的代码设置如下:
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()时,我的值始终为空。
任何人都可以帮我弄清楚我做错了什么吗?谢谢。
这使我在正确的道路上,所以我会将它标记为答案。在InitSpi的try {}结束时添加GetThermocoupleData(null)不起作用,但如果我改变我的temperatureData = new byte [4],并在我的Run()方法中添加一个延迟/循环,那么我会返回数据。谢谢! –
哦,darn,我没有注意到Init方法是异步的。这就是为什么我的建议没有奏效。在初始化执行完成之前,仍然可以询问温度。真高兴你做到了。 – Joel