Getting SPI temperature data from outside of class

痞子三分冷 提交于 2019-12-23 02:51:03

问题


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.


回答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.



来源:https://stackoverflow.com/questions/38038788/getting-spi-temperature-data-from-outside-of-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!