Search code examples
c#.netiotgpioraspberry-pi4

Read more than one MAX31865


We are implementing temperature reading using PT100 (3 wires) and Raspberry 4 with .NET 6.

We are able to read the temperature using as reference this article.

SpiConnectionSettings settings = new(0, 0)
{
    ClockFrequency = Max31865.SpiClockFrequency,
    Mode = Max31865.SpiMode1,
    DataFlow = Max31865.SpiDataFlow
};

using (SpiDevice device = SpiDevice.Create(settings))
{
    using (Max31865 sensor = new(device, PlatinumResistanceThermometerType.Pt100, ResistanceTemperatureDetectorWires.ThreeWire, ElectricResistance.FromOhms(430)))
    {

        while (true)
        {
            Console.WriteLine(sensor.Faults.ToString());

            Thread.Sleep(1000);
        }
    }
}

Actually to work the script need the CS pin of Max31865 connected to pin 12 of raspberry GPIO. We would like to connect more than one Max31865 in order to record some temperatures from different Pt100.

How we can specify the right/specific GPIO port in the C# script for every Max31865 CS output pin? Actually seems there are no properties to change that pin but this feature will permit us to read more than one sensor.


Solution

  • The easiest thing is to do the CS handling manually, as automatic CS handling with multiple devices on the same bus is not fully implemented for the Raspberry Pi.

    var controller = new GpioController();
    controller.OpenPin(CsPinOfSensor1);
    controller.OpenPin(CsPinOfSensor2);
    controller.Write(CsPinOfSensor1, PinValue.Low); // CS is low-active!
    controller.Write(CsPinOfSensor2, PinValue.High);
    using Max31865 sensor1 = new(device, PlatinumResistanceThermometerType.Pt100, ResistanceTemperatureDetectorWires.ThreeWire, ElectricResistance.FromOhms(430));
    controller.Write(CsPinOfSensor1, PinValue.High); // CS is low-active!
    controller.Write(CsPinOfSensor2, PinValue.Low);
    using Max31865 sensor2 = new(device, PlatinumResistanceThermometerType.Pt100, ResistanceTemperatureDetectorWires.ThreeWire, ElectricResistance.FromOhms(430));
        {
    
            while (true)
            {
                controller.Write(CsPinOfSensor1, PinValue.Low); // CS is low-active!
                controller.Write(CsPinOfSensor2, PinValue.High);
                Console.WriteLine(sensor1.Temperature.ToString());
    
                controller.Write(CsPinOfSensor1, PinValue.High);
                controller.Write(CsPinOfSensor2, PinValue.Low);
                Console.WriteLine(sensor2.Temperature.ToString());
                Thread.Sleep(1000);
            }
        }
    

    There are multiple pins reserved as CS pins for each SPI bus, but I honestly do not even know how they would need to be selected at the OS level.

    Alternatively, you can of course also connect the second sensor to a second SPI bus. The Raspberry Pi4 has a total of 6 SPI channels.