-
-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathLm75.cs
123 lines (105 loc) · 3.12 KB
/
Lm75.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Device.I2c;
using System.Device.Model;
using UnitsNet;
namespace Iot.Device.Lm75
{
/// <summary>
/// Digital Temperature Sensor LM75
/// </summary>
[Interface("Digital Temperature Sensor LM75")]
public class Lm75 : IDisposable
{
private I2cDevice _i2cDevice;
/// <summary>
/// LM75 I2C Address
/// </summary>
public const byte DefaultI2cAddress = 0x48;
#region prop
/// <summary>
/// LM75 Temperature
/// </summary>
[Telemetry]
public Temperature Temperature { get => Temperature.FromDegreesCelsius(GetTemperature()); }
private bool _disable;
/// <summary>
/// Disable LM75
/// </summary>
[Telemetry]
public bool Disabled
{
get => _disable;
set
{
SetShutdown(value);
_disable = value;
}
}
#endregion
/// <summary>
/// Creates a new instance of the LM75
/// </summary>
/// <param name="i2cDevice">The I2C device used for communication.</param>
public Lm75(I2cDevice i2cDevice)
{
_i2cDevice = i2cDevice ?? throw new ArgumentException(nameof(i2cDevice));
Disabled = false;
}
/// <summary>
/// Read LM75 Temperature (℃)
/// </summary>
/// <returns>Temperature</returns>
private double GetTemperature()
{
SpanByte readBuff = new byte[2];
_i2cDevice.WriteByte((byte)Register.LM_TEMP);
_i2cDevice.Read(readBuff);
// Details in Datasheet P10
double temp = 0;
ushort raw = (ushort)((readBuff[0] << 3) | (readBuff[1] >> 5));
if ((readBuff[0] & 0x80) == 0)
{
// temperature >= 0
temp = raw * 0.125;
}
else
{
// temperature < 0
// two's complement
raw |= 0xF800;
raw = (ushort)(~raw + 1);
temp = raw * (-1) * 0.125;
}
return Math.Round(temp * 10) / 10.0;
}
/// <summary>
/// Set LM75 Shutdown
/// </summary>
/// <param name="isShutdown">Shutdown when value is true.</param>
private void SetShutdown(bool isShutdown)
{
_i2cDevice.WriteByte((byte)Register.LM_CONFIG);
byte config = _i2cDevice.ReadByte();
config &= 0xFE;
if (isShutdown)
{
config |= 0x01;
}
SpanByte writeBuff = new byte[]
{
(byte)Register.LM_CONFIG, config
};
_i2cDevice.Write(writeBuff);
}
/// <summary>
/// Cleanup
/// </summary>
public void Dispose()
{
_i2cDevice?.Dispose();
_i2cDevice = null!;
}
}
}