-
-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathMcp342x.cs
345 lines (301 loc) · 11.4 KB
/
Mcp342x.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// 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.Buffers.Binary;
using System.Collections.Generic;
using System.Device.I2c;
using System.IO;
using System.Threading;
namespace Iot.Device.Mcp3428
{
/// <summary>
/// Base type for MCP342X ADC
/// </summary>
public abstract class Mcp342x : IDisposable
{
/// <summary>
/// Protected constructor to easily generate MCP3426/7 devices whose only difference is channel count and I2C address
/// </summary>
/// <param name="i2cDevice">The i2 c device.</param>
/// <param name="channels">The channels.</param>
/// <autogeneratedoc />
protected Mcp342x(I2cDevice i2cDevice, int channels)
{
_i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
ChannelCount = channels;
ReadValue(); // Don't like this in constructor, makes sure props are valid
}
/// <summary>
/// Gets the last transmitted bytes. Debug function
/// </summary>
/// <value>The last bytes.</value>
/// <autogeneratedoc />
public byte[] LastBytes
{
get
{
byte[] lastBytes = new byte[_readBuffer.Length];
Array.Copy(_readBuffer, lastBytes, _readBuffer.Length);
return lastBytes;
}
}
/// <summary>
/// Channel most recently read
/// </summary>
/// <value>The last channel.</value>
/// <autogeneratedoc />
public byte LastChannel => LastConversion.Channel;
/// <summary>
/// ADC mode
/// </summary>
public AdcMode Mode
{
get => _mode;
set
{
WriteConfig(Helpers.SetModeBit(LastConfigByte, value));
_mode = value;
}
}
/// <summary>
/// Gets or sets the input gain.
/// </summary>
/// <value>The pga gain.</value>
/// <autogeneratedoc />
public AdcGain InputGain
{
get => _pgaGain;
set
{
WriteConfig(Helpers.SetGainBits(LastConfigByte, value));
_pgaGain = value;
}
}
/// <summary>
/// Gets or sets the bit resolution of the result.
/// </summary>
/// <value>The resolution.</value>
/// <autogeneratedoc />
public AdcResolution Resolution
{
get => _resolution;
set
{
WriteConfig(Helpers.SetResolutionBits(LastConfigByte, value));
_resolution = value;
}
}
/// <summary>
/// Reads the channel.
/// </summary>
/// <param name="channel">The channel.</param>
/// <returns>System.Double.</returns>
/// <autogeneratedoc />
public double ReadChannel(int channel) => ReadValue(channel);
private readonly byte[] _readBuffer = new byte[3];
private I2cDevice _i2cDevice;
private bool _isReadyBit = false;
private byte _lastChannel = 0xFF;
private ConversionResult _lastConversion;
private AdcMode _mode = AdcMode.Continuous;
// Config params
private AdcGain _pgaGain = AdcGain.X1;
private AdcResolution _resolution = AdcResolution.Bit12;
private byte LastConfigByte => _readBuffer[2];
/// <summary>
/// Initiates One-shot reading and waits for the conversion to finish.
/// </summary>
/// <param name="channel">The channel.</param>
/// <exception cref="System.IO.IOException">
/// Device is not in One-Shot mode
/// or
/// ADC Conversion was not ready after {tries}
/// </exception>
/// <autogeneratedoc />
protected void OneShotRead(int channel = -1)
{
if (Mode != AdcMode.OneShot)
{
throw new IOException("Device is not in One-Shot mode");
}
_isReadyBit = false;
var conf = Helpers.SetReadyBit(LastConfigByte, false);
if (channel >= 0 && channel != LastChannel)
{
conf = Helpers.SetChannelBits(conf, channel);
}
WriteConfig(conf);
using (var source = new CancellationTokenSource(TimeSpan.FromMilliseconds(WaitTime * 5)))
{
WaitForConversion(TimeSpan.FromMilliseconds(WaitTime), cancellationToken: source.Token);
if (!_isReadyBit)
{
throw new IOException($"ADC Conversion was not ready after {WaitTime * 5} ms.");
}
}
}
/// <summary>
/// Waits for conversion to complete
/// </summary>
/// <param name="waitSpan">Time to wait for conversion before timing out</param>
/// <param name="cancellationToken">Token which can be used to cancel the operation</param>
protected void WaitForConversion(TimeSpan waitSpan = default(TimeSpan),
CancellationToken cancellationToken = default)
{
if (waitSpan == default(TimeSpan))
{
waitSpan = TimeSpan.FromMilliseconds(WaitTime);
}
var allms = 0;
_isReadyBit = false;
while (!_isReadyBit && !cancellationToken.IsCancellationRequested)
{
_i2cDevice.Read(_readBuffer);
ReadConfigByte(LastConfigByte);
if (_isReadyBit)
{
break;
}
Thread.Sleep((int)waitSpan.TotalMilliseconds);
cancellationToken.ThrowIfCancellationRequested();
allms += (int)waitSpan.TotalMilliseconds;
}
cancellationToken.ThrowIfCancellationRequested();
}
/// <summary>
/// Read (or load) configuration byte
/// </summary>
/// <param name="config">Configuration to be read</param>
protected void ReadConfigByte(byte config)
{
_isReadyBit = (config & Helpers.Masks.ReadyMask) == 0; // Negated bit
_lastChannel = (byte)((config & Helpers.Masks.ChannelMask) >> 5);
_mode = (AdcMode)(config & Helpers.Masks.ModeMask);
_pgaGain = (AdcGain)(config & Helpers.Masks.GainMask);
_resolution = (AdcResolution)(config & Helpers.Masks.ResolutionMask);
}
/// <summary>
/// Reads value on the specified channel
/// </summary>
/// <param name="channel">Channel to read the data from</param>
/// <returns>Value read from the channel</returns>
protected double ReadValue(int channel = -1)
{
if (Mode == AdcMode.OneShot)
{
OneShotRead(channel);
}
else
{
if (channel > 0 && channel != LastChannel)
{
var conf = Helpers.SetChannelBits(LastConfigByte, channel);
WriteConfig(conf);
}
using (var source = new CancellationTokenSource(TimeSpan.FromMilliseconds(WaitTime * 5)))
{
WaitForConversion(TimeSpan.FromMilliseconds(WaitTime / 5), cancellationToken: source.Token);
}
}
var value = BinaryPrimitives.ReadInt16BigEndian(new SpanByte(_readBuffer).Slice(0, 2));
LastConversion = new ConversionResult(_lastChannel, value, Resolution);
return LastConversion.Voltage;
}
/// <summary>
/// Write configuration register and read back value
/// </summary>
/// <param name="channel">The channel.</param>
/// <param name="mode">The mode.</param>
/// <param name="resolution">The resolution.</param>
/// <param name="pgaGain">The pga gain.</param>
/// <param name="errorList">List to write errors on failure</param>
/// <returns><c>true</c> if all values are set correctly, <c>false</c> otherwise.</returns>
/// <exception cref="ArgumentOutOfRangeException">channel</exception>
protected bool SetConfig(int channel = 0, AdcMode mode = AdcMode.Continuous,
AdcResolution resolution = AdcResolution.Bit12, AdcGain pgaGain = AdcGain.X1,
ListString errorList = null)
{
if (channel < 0 || channel > ChannelCount - 1)
{
throw new ArgumentOutOfRangeException(nameof(channel));
}
byte conf = 0;
var ok = true;
conf = Helpers.SetModeBit(conf, mode);
conf = Helpers.SetChannelBits(conf, channel);
conf = Helpers.SetGainBits(conf, pgaGain);
conf = Helpers.SetResolutionBits(conf, resolution);
conf = Helpers.SetReadyBit(conf, false);
_i2cDevice.WriteByte(conf);
_i2cDevice.Read(_readBuffer);
ReadConfigByte(LastConfigByte);
if (_lastChannel != channel)
{
errorList?.Add($"Channel update failed from {_lastChannel} to {channel}");
ok = false;
}
if (Resolution != resolution)
{
errorList?.Add($"Resolution update failed from {Resolution} to {resolution}");
ok = false;
}
if (mode != Mode)
{
errorList?.Add($"Mode update failed from {Mode} to {mode}");
ok = false;
}
if (InputGain != pgaGain)
{
errorList?.Add($"PGAGain update failed from {InputGain} to {pgaGain}");
ok = false;
}
if (!ok)
{
// Only use console on error
errorList?.Add($"Sent config byte {conf:X}, received {LastConfigByte:X}");
}
return ok;
}
/// <summary>
/// Wait period before operation is cancelled
/// </summary>
protected int WaitTime => (int)(1000.0 / Helpers.UpdateFrequency(Resolution));
/// <summary>
/// Number of channels
/// </summary>
public int ChannelCount { get; }
/// <summary>
/// Last conversion result
/// </summary>
protected ConversionResult LastConversion
{
get => _lastConversion;
set
{
_lastConversion = value;
OnConversion?.Invoke(this, _lastConversion);
}
}
/// <summary>
/// Event handler for ConversionResult
/// </summary>
/// <param name="sender">This class</param>
/// <param name="conversionResult">Convertion results</param>
public delegate void ConversionResultHandler(object sender, ConversionResult conversionResult);
/// <summary>
/// Event called when conversion is complete
/// </summary>
public event ConversionResultHandler OnConversion;
/// <summary>
/// Writes configuration
/// </summary>
/// <param name="configByte">Configuration to write</param>
protected void WriteConfig(byte configByte) => _i2cDevice.WriteByte(configByte);
/// <inheritdoc/>
public void Dispose()
{
_i2cDevice?.Dispose();
_i2cDevice = null!;
}
}
}