私は、温度データを読み取るためにSPIを通してRaspberryPiとの通信を処理する "Temperature"クラスを作成しようとしています。目標は、私の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();
}
}
温度等級:私はGetThermocoupleData()にブレークポイントを追加すると
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;
}
}
、私は正しいセンサデータを取得していていることがわかります値。しかし、私がクラスの外からt.GetTemp()を呼び出すと、私の値は常にnullです。
誰でも私が間違っていることを理解するのに役立つことができますか?ありがとうございました。
これは正しい経路で私を指示したので、答えとしてマークします。 InitSpiのtry {}の最後にGetThermocoupleData(null)を追加しても動作しませんでしたが、temperatureData = new byte [4]を変更してRun()メソッドで遅延/ループを追加すると、データが返されます。ありがとう! –
ああ、私はInitメソッドが非同期であったことに気付かなかった。それが私の提案がうまくいかなかった理由です。 initが実行を終了する前に、依然として温度を求めることは可能でした。あなたがうまく働いてうれしい。 – Joel