2016-06-26 147 views
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()時,我的值始終爲空。

任何人都可以幫我弄清楚我做錯了什麼嗎?謝謝。

回答

0

GetThermocouplerData()必須至少調用一次才能返回數據。在您的代碼示例中,實例化之後它將不會運行到1秒。只需在try塊的最後一行添加一個對InitSpi中的GetThermocoupleData(null)的調用,以便它已經至少有一次調用。

+0

這使我在正確的道路上,所以我會將它標記爲答案。在InitSpi的try {}結束時添加GetThermocoupleData(null)不起作用,但如果我改變我的temperatureData = new byte [4],並在我的Run()方法中添加一個延遲/循環,那麼我會返回數據。謝謝! –

+0

哦,darn,我沒有注意到Init方法是異步的。這就是爲什麼我的建議沒有奏效。在初始化執行完成之前,仍然可以詢問溫度。真高興你做到了。 – Joel