Search code examples
c#uwpwindows-10-universalwindowsiot

Getting SPI temperature data from outside of class


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;
    }
}

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.


Solution

  • 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.