Libs_SequentMicrosystems/RTD_8chanels_board.cs

71 lines
2.6 KiB
C#
Raw Normal View History

using System.Device.I2c;
2023-11-22 16:24:01 +00:00
namespace Libs_SequentMicrosystems
{
public class RTDStackLevelReader
{
public readonly byte DEVICE_ADDRESS = 0x40;
public readonly byte RTD_RESISTANCE_ADD = 59;
/// <summary>
/// Read Single Resistance
/// </summary>
/// <param name="stack">Level on Stack 0-7</param>
/// <param name="channel">Chanel on stack layer 1-8</param>
/// <returns>Resistance of selected element</returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="IOException"></exception>
public float Get(byte stack, byte channel)
{
if (stack < 0 || stack > 7)
throw new ArgumentException("Invalid stack level");
if (channel < 1 || channel > 8)
throw new ArgumentException("Invalid channel number");
float val = -273.15f;
try
{
using (I2cDevice i2c = I2cDevice.Create(new I2cConnectionSettings(1, DEVICE_ADDRESS + stack)))
{
byte[] buffer = new byte[4];
i2c.WriteByte((byte)(RTD_RESISTANCE_ADD + (4 * (channel - 1))));
i2c.Read(buffer);
val = BitConverter.ToSingle(buffer, 0);
}
}
catch (IOException e)
{
throw new IOException($"Fail to communicate with the RTD card with message: \"{e.Message}\"");
}
return val;
}
/// <summary>
/// Get data from all inputs on stack level
/// </summary>
/// <param name="stack">Number of level in stack</param>
/// <param name="precision">Number of decimals numbers of measured resistance</param>
/// <returns>Measured resistances of all inputs</returns>
public float[] GetStack(byte stack, byte precision = 2)
{
float[] chanels = new float[8]; //initialize float array
2023-11-22 16:24:01 +00:00
chanels[0] = (float)Math.Round(Get(stack, 1), precision); //write readed value from input to array
chanels[1] = (float)Math.Round(Get(stack, 2), precision);
chanels[2] = (float)Math.Round(Get(stack, 3), precision);
chanels[3] = (float)Math.Round(Get(stack, 4), precision);
chanels[4] = (float)Math.Round(Get(stack, 5), precision);
chanels[5] = (float)Math.Round(Get(stack, 6), precision);
chanels[6] = (float)Math.Round(Get(stack, 7), precision);
chanels[7] = (float)Math.Round(Get(stack, 8), precision);
2023-11-22 16:24:01 +00:00
return chanels; //return array
}
2023-11-22 16:24:01 +00:00
}
}