问题描述
我试图写一个类温度的处理与通过SPI我树莓派通信读一些温度数据。我们的目标是能够从我的温度等级之外调用getTemp()这个方法,这样我可以使用的温度数据,每当我需要在我的程序的其余部分。
I'm trying to write a class "Temperature" that handles communicating with my RaspberryPi through SPI to read some temperature data. The goal is to be able to call a GetTemp() method from outside of my Temperature class so that I can use temperature data whenever I need it in the rest of my program.
我的代码设置是这样的:
My code is set up like this:
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();
}
}
温度等级:
Temperature class:
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。
When I add a breakpoint in GetThermocoupleData(), I can see that I am getting the correct sensor data values. However when I call t.GetTemp() from outside of my class, my value is always null.
谁能帮我找出我做错了吗?谢谢你。
Can anyone help me figure out what I'm doing wrong? Thank you.
推荐答案
GetThermocouplerData()必须已经调用ATLEAST一次返回的数据。在您的代码示例它不会一直运行,直到实例化之后1秒。只需在您try块的最后一行添加到GetThermocoupleData(空)的InitSpi通话,以便它开始了已经有至少1个电话。
GetThermocouplerData() must have been called atleast once to return data. In your code sample it will not have been run until 1 second after instantiation. Just add a call to GetThermocoupleData(null) in InitSpi in the last line of your try block so that it starts off already having at least 1 call.
这篇关于从类之外获取SPI温度数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!