RPi GPIO
Name |
Board Pin |
VCC |
1/17 |
GND |
6/9/14/20/25/30/34/39 |
3Vo |
N/A |
CS |
24 |
SCK |
23 |
D0 |
21 |
using System;
using Windows.Devices.Enumeration;
using Windows.Devices.Spi;
namespace CYFang
{
/// <summary>
/// Max31855
/// </summary>
public sealed class Max31855 : IDisposable
{
/// <summary>
/// SPI
/// </summary>
private SpiDevice sensor;
/// <summary>
/// read buff
/// </summary>
private byte[] readBuff = new byte[4];
/// <summary>
///
/// </summary>
public Max31855() { this.InitSPI(); }
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
if (sensor != null)
{
sensor.Dispose();
sensor = null;
}
}
/// <summary>
/// 取得IC溫度
/// </summary>
/// <returns></returns>
public double GetInternalTemperatureDataCelcius()
{
GetThermocoupleData();
uint data = BitConverter.ToUInt32(readBuff, 0);
data >>= 4;
double celsius = data & 0x7FF;
if ((data & 0x800) == 1)
{
celsius = 0xF800 | (data & 0x7FF);
}
//15 to 4 /= 16.0
celsius /= 16.0;
return celsius;
}
/// <summary>
/// 取得IC華氏溫度
/// </summary>
/// <returns></returns>
public double GetInternalTemperatureDataFahrenheit() { return ConvertCelsiusToFahrenheit(GetInternalTemperatureDataCelcius()); }
/// <summary>
/// 取得K型接頭溫度
/// </summary>
/// <returns></returns>
public double GetProbeTemperatureDataCelsius()
{
GetThermocoupleData();
uint data = BitConverter.ToUInt32(readBuff, 0);
data = ((data & 0x80000000) != 0) ?
data = ((data >> 18) & 0x00003FFFF) | 0xFFFFC000 :
data >>= 18;
double celsius = data;
// 31 to 18 = /=4.0
celsius /= 4.0f;
return celsius;
}
/// <summary>
/// 取得K型接頭華氏溫度
/// </summary>
/// <returns></returns>
public double GetProbeTemperatureDataFahrenheit() { return ConvertCelsiusToFahrenheit(GetProbeTemperatureDataCelsius()); }
/// <summary>
/// Init SPI
/// </summary>
private async void InitSPI()
{
var settings = new SpiConnectionSettings(0)
{
ClockFrequency = 5000000,
Mode = SpiMode.Mode0
};
string spiAqs = SpiDevice.GetDeviceSelector("SPI0");
var deviceInfo = await DeviceInformation.FindAllAsync(spiAqs);
this.sensor = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings);
}
/// <summary>
/// 取得數值
/// </summary>
private void GetThermocoupleData()
{
byte[] readBuff = new byte[4];
sensor.Read(readBuff);
Array.Reverse(readBuff);
this.readBuff = readBuff;
}
/// <summary>
/// 攝氏轉華氏
/// </summary>
/// <param name="c">攝氏</param>
/// <returns></returns>
private double ConvertCelsiusToFahrenheit(double c)
{
c *= 9.0;
c /= 5.0;
c += 32;
return c;
}
}
}