1

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 になります。

誰かが私が間違っていることを理解するのを手伝ってくれますか? ありがとうございました。

4

1 に答える 1

0

データを返すには、GetThermocouplerData() を少なくとも 1 回呼び出す必要があります。コード サンプルでは、​​インスタンス化後 1 秒まで実行されません。InitSpi の GetThermocoupleData(null) への呼び出しを try ブロックの最後の行に追加するだけで、少なくとも 1 つの呼び出しが既にあることから開始できます。

于 2016-06-26T15:40:38.793 に答える