forked from nanoframework/nanoFramework.IoT.Device
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMcp23xxx.cs
566 lines (495 loc) · 20.1 KB
/
Mcp23xxx.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
// 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.Gpio;
using System.Runtime.CompilerServices;
namespace Iot.Device.Mcp23xxx
{
/// <summary>
/// Base class for Mcp23xxx GPIO expanders
/// </summary>
public abstract partial class Mcp23xxx : GpioDriver
{
private readonly int _reset;
private readonly int _interruptA;
private readonly int _interruptB;
private BankStyle _bankStyle;
private GpioController? _controller;
private bool _shouldDispose;
/// <summary>
/// Bus adapter (I2C/SPI) used to communicate with the device
/// </summary>
protected BusAdapter _bus;
private bool _increments = true;
private ushort _gpioCache;
private bool _cacheValid;
private bool _disabled;
/// <summary>
/// A general purpose parallel I/O expansion for I2C or SPI applications.
/// </summary>
/// <param name="bus">The bus the device is connected to.</param>
/// <param name="reset">The output pin number that is connected to the hardware reset.</param>
/// <param name="interruptA">The input pin number that is connected to the interrupt for Port A (INTA).</param>
/// <param name="interruptB">The input pin number that is connected to the interrupt for Port B (INTB).</param>
/// <param name="gpioController">
/// The controller for the reset and interrupt pins. If not specified, the default controller will be used.
/// </param>
/// <param name="bankStyle">
/// The current bank style of the ports. This does not set the bank style- it tells us what the bank style is.
/// It is *highly* recommended not to change the bank style from the default as there is no direct way to
/// detect what style the chip is in and most apps will fail if the chip is not set to defaults. This setting
/// has no impact on 8-bit expanders.
/// </param>
/// <param name="shouldDispose">True to dispose the Gpio Controller</param>
protected Mcp23xxx(BusAdapter bus, int reset = -1, int interruptA = -1, int interruptB = -1,
GpioController? gpioController = null, BankStyle bankStyle = BankStyle.Sequential, bool shouldDispose = true)
{
_bus = bus;
_bankStyle = bankStyle;
_reset = reset;
_interruptA = interruptA;
_interruptB = interruptB;
// Only need master controller if there are external pins provided.
if (_reset != -1 || _interruptA != -1 || _interruptB != -1)
{
_shouldDispose = shouldDispose || gpioController is null;
_controller = gpioController ?? new GpioController();
if (_interruptA != -1)
{
_controller.OpenPin(_interruptA, PinMode.Input);
}
if (_interruptB != -1)
{
_controller.OpenPin(_interruptB, PinMode.Input);
}
if (_reset != -1)
{
_controller.OpenPin(_reset, PinMode.Output);
Disable();
}
}
if (!_disabled)
{
// Set all of the pins to input, GPIO outputs to low, and set input polarity to match the input.
// This is the normal power-on / reset state of the Mcp23xxx chips.
if (PinCount == 8)
{
InternalWriteByte(Register.IODIR, 0xFF, Port.PortA);
InternalWriteByte(Register.GPIO, 0x00, Port.PortA);
InternalWriteByte(Register.IPOL, 0x00, Port.PortA);
}
else
{
InternalWriteUInt16(Register.IODIR, 0xFFFF);
InternalWriteUInt16(Register.GPIO, 0x0000);
InternalWriteUInt16(Register.IPOL, 0x0000);
}
}
}
private void UpdateCache()
{
// Ouput state is read from the latches (OLAT)
_gpioCache = PinCount == 8
? InternalReadByte(Register.OLAT, Port.PortA)
: InternalReadUInt16(Register.OLAT);
_cacheValid = true;
}
/// <summary>
/// Reads a number of bytes from registers.
/// </summary>
/// <param name="register">The register to read from.</param>
/// <param name="buffer">The buffer to read bytes into.</param>
/// <param name="port">The I/O port used with the register.</param>
protected void InternalRead(Register register, SpanByte buffer, Port port)
{
if (_disabled)
{
ThrowDisabled();
}
_bus.Read(GetMappedAddress(register, port, _bankStyle), buffer);
}
/// <summary>
/// Writes a number of bytes to registers.
/// </summary>
/// <param name="register">The register address to write to.</param>
/// <param name="data">The data to write to the registers.</param>
/// <param name="port">The I/O port used with the registers.</param>
protected void InternalWrite(Register register, SpanByte data, Port port)
{
if (_disabled)
{
ThrowDisabled();
}
_bus.Write(GetMappedAddress(register, port, _bankStyle), data);
}
// Keeping this a separate method to allow the Read/Write methods to inline
[MethodImpl(MethodImplOptions.NoInlining)]
private void ThrowDisabled() => throw new InvalidOperationException("Chip is disabled");
/// <summary>
/// Reads byte from the device register
/// </summary>
/// <param name="register">Register to read the value from</param>
/// <param name="port">Port related with the <paramref name="register"/></param>
/// <returns>Byte read from the device register</returns>
protected byte InternalReadByte(Register register, Port port)
{
SpanByte buffer = new byte[1];
InternalRead(register, buffer, port);
return buffer[0];
}
/// <summary>
/// Write byte to device register
/// </summary>
/// <param name="register">Register to write the value to</param>
/// <param name="value">Value to be written to the <paramref name="register"/></param>
/// <param name="port">Port related with the <paramref name="register"/></param>
protected void InternalWriteByte(Register register, byte value, Port port)
{
SpanByte buffer = new byte[1];
buffer[0] = value;
InternalWrite(register, buffer, port);
}
/// <summary>
/// Read a byte from the given register.
/// </summary>
/// <remarks>
/// Writes to the A port registers on 16 bit devices.
/// </remarks>
public byte ReadByte(Register register) => InternalReadByte(register, Port.PortA);
/// <summary>
/// Write a byte to the given register.
/// </summary>
/// <remarks>
/// Writes to the A port registers on 16 bit devices.
/// </remarks>
public void WriteByte(Register register, byte value) => InternalWriteByte(register, value, Port.PortA);
/// <summary>
/// Read 16-bit unsigned integer from the device register
/// </summary>
/// <param name="register">Register to read the value from</param>
/// <returns>16-bit unsigned integer read from the device</returns>
protected ushort InternalReadUInt16(Register register)
{
SpanByte buffer = new byte[2];
if (_increments)
{
// Can read both bytes at the same time
InternalRead(register, buffer, Port.PortA);
}
else
{
// Have to read each separately
InternalRead(register, buffer.Slice(0, 1), Port.PortA);
InternalRead(register, buffer.Slice(1), Port.PortB);
}
return (ushort)(buffer[0] | buffer[1] << 8);
}
/// <summary>
/// Writes 16-bit unsigned integer to the device register
/// </summary>
/// <param name="register">Register to write <paramref name="value"/> to</param>
/// <param name="value">16-bit unsigned integer to write to the <paramref name="register"/></param>
protected void InternalWriteUInt16(Register register, ushort value)
{
SpanByte buffer = new byte[2];
buffer[0] = (byte)value;
buffer[1] = (byte)(value >> 8);
if (_increments)
{
// Can write both at the same time
InternalWrite(register, buffer, Port.PortA);
}
else
{
// Have to write each separately
InternalWrite(register, buffer.Slice(0, 1), Port.PortA);
InternalWrite(register, buffer.Slice(1), Port.PortB);
}
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (_shouldDispose)
{
_controller?.Dispose();
_controller = null;
}
_bus?.Dispose();
_bus = null!;
base.Dispose(disposing);
}
/// <summary>
/// Disables the device by setting the reset pin low.
/// </summary>
public void Disable()
{
if (_reset == -1 || _controller is null)
{
throw new InvalidOperationException("No reset pin configured.");
}
_controller.Write(_reset, PinValue.Low);
// Registers will all be reset when re-enabled
_bankStyle = BankStyle.Sequential;
_increments = true;
_disabled = true;
}
/// <summary>
/// Enables the device by setting the reset pin high.
/// </summary>
public void Enable()
{
if (_reset == -1 || _controller is null)
{
throw new InvalidOperationException("No reset pin configured.");
}
_controller.Write(_reset, PinValue.High);
_disabled = false;
_cacheValid = false;
}
/// <summary>
/// Reads interrupt value
/// </summary>
/// <param name="port">Port to read interrupt on</param>
/// <returns>Value of intterupt pin</returns>
protected PinValue InternalReadInterrupt(Port port)
{
int pinNumber = port switch
{
Port.PortA => _interruptA,
Port.PortB => _interruptB,
_ => throw new ArgumentOutOfRangeException(nameof(port)),
};
if (pinNumber == -1 || _controller is null)
{
throw new ArgumentException("No interrupt pin configured.", nameof(port));
}
return _controller.Read(pinNumber);
}
/// <summary>
/// Returns the value of the interrupt pin if configured.
/// </summary>
/// <returns>
/// Returns the interrupt for port A on 16 bit devices.
/// </returns>
public PinValue ReadInterrupt() => InternalReadInterrupt(Port.PortA);
/// <summary>
/// Sets a mode to a pin.
/// </summary>
/// <param name="pinNumber">The pin number.</param>
/// <param name="mode">The mode to be set.</param>
protected override void SetPinMode(int pinNumber, PinMode mode)
{
if (mode != PinMode.Input && mode != PinMode.Output)
{
throw new ArgumentException("The Mcp controller supports Input and Output modes only.");
}
ValidatePin(pinNumber);
byte SetBit(byte data, int bitNumber) => (byte)(data | (1 << bitNumber));
byte ClearBit(byte data, int bitNumber) => (byte)(data & ~(1 << bitNumber));
if (pinNumber < 8)
{
byte value = mode == PinMode.Output
? ClearBit(InternalReadByte(Register.IODIR, Port.PortA), pinNumber)
: SetBit(InternalReadByte(Register.IODIR, Port.PortA), pinNumber);
InternalWriteByte(Register.IODIR, value, Port.PortA);
}
else
{
byte value = mode == PinMode.Output
? ClearBit(InternalReadByte(Register.IODIR, Port.PortB), pinNumber - 8)
: SetBit(InternalReadByte(Register.IODIR, Port.PortB), pinNumber - 8);
InternalWriteByte(Register.IODIR, value, Port.PortB);
}
}
/// <summary>
/// Reads the value of a pin.
/// </summary>
/// <param name="pinNumber">The pin number.</param>
/// <returns>High or low pin value.</returns>
protected override PinValue Read(int pinNumber)
{
ValidatePin(pinNumber);
var pinValuePairs = new PinValuePair[]
{
new PinValuePair(pinNumber, default)
};
Read(pinValuePairs);
return pinValuePairs[0].PinValue;
}
/// <summary>
/// Reads the value of a set of pins
/// </summary>
protected void Read(PinValuePair[] pinValuePairs)
{
(uint pins, _) = new PinVector32(pinValuePairs);
if ((pins >> PinCount) > 0)
{
ThrowBadPin(nameof(pinValuePairs));
}
ushort result;
if (pins < 0xFF + 1)
{
// Only need to get the first 8 pins (PortA)
result = InternalReadByte(Register.GPIO, Port.PortA);
}
else if ((pins & 0xFF) == 0)
{
// Only need to get the second 8 pins (PortB)
result = (ushort)(InternalReadByte(Register.GPIO, Port.PortB) << 8);
}
else
{
// Need to get both
result = InternalReadUInt16(Register.GPIO);
}
for (int i = 0; i < pinValuePairs.Length; i++)
{
int pin = pinValuePairs[i].PinNumber;
pinValuePairs[i] = new PinValuePair(pin, result & (1 << pin));
}
}
/// <summary>
/// Writes a value to a pin.
/// </summary>
/// <param name="pinNumber">The pin number.</param>
/// <param name="value">The value to be written.</param>
protected override void Write(int pinNumber, PinValue value)
{
ValidatePin(pinNumber);
var pinValuePairs = new PinValuePair[]
{
new PinValuePair(pinNumber, value)
};
Write(pinValuePairs);
}
/// <summary>
/// Writes values to a set of pins
/// </summary>
protected void Write(PinValuePair[] pinValuePairs)
{
(uint mask, uint newBits) = new PinVector32(pinValuePairs);
if ((mask >> PinCount) > 0)
{
ThrowBadPin(nameof(pinValuePairs));
}
if (!_cacheValid)
{
UpdateCache();
}
ushort cachedValue = _gpioCache;
ushort newValue = SetBits(cachedValue, (ushort)newBits, (ushort)mask);
if (cachedValue == newValue)
{
return;
}
if (mask < 0xFF + 1)
{
// Only need to change the first 8 pins (PortA)
InternalWriteByte(Register.GPIO, (byte)newValue, Port.PortA);
}
else if ((mask & 0xFF) == 0)
{
// Only need to change the second 8 pins (PortB)
InternalWriteByte(Register.GPIO, (byte)(newValue >> 8), Port.PortB);
}
else
{
// Need to change both
InternalWriteUInt16(Register.GPIO, newValue);
}
_gpioCache = newValue;
}
private ushort SetBits(ushort current, ushort bits, ushort mask)
{
current &= (ushort)~mask;
current |= bits;
return current;
}
private void ValidatePin(int pinNumber)
{
if (pinNumber >= PinCount || pinNumber < 0)
{
ThrowBadPin(nameof(pinNumber));
}
}
private void ThrowBadPin(string argument)
{
throw new ArgumentOutOfRangeException(argument, $"Only pins {0} through {PinCount - 1} are valid.");
}
/// <summary>
/// Gets the mapped address for a register.
/// </summary>
/// <param name="register">The register.</param>
/// <param name="port">The bank of I/O ports used with the register.</param>
/// <param name="bankStyle">The bank style that determines how the register addresses are grouped.</param>
/// <returns>The byte address of the register for the given port bank and bank style.</returns>
private byte GetMappedAddress(Register register, Port port = Port.PortA,
BankStyle bankStyle = BankStyle.Sequential)
{
if (port != Port.PortA && port != Port.PortB)
{
throw new ArgumentOutOfRangeException(nameof(port));
}
if (bankStyle != BankStyle.Separated && bankStyle != BankStyle.Sequential)
{
throw new ArgumentOutOfRangeException(nameof(bankStyle));
}
byte address = (byte)register;
// There is no mapping for 8 bit expanders
if (PinCount == 8)
{
return address;
}
if (bankStyle == BankStyle.Sequential)
{
// Registers for each bank are sequential
// (IODIRA = 0x00, IODIRB = 0x01, IPOLA = 0x02, IPOLB = 0x03, ...)
address += address;
return port == Port.PortA ? address : ++address;
}
// Registers for each bank are separated
// (IODIRA = 0x00, ... OLATA = 0x0A, IODIRB = 0x10, ... OLATB = 0x1A)
return port == Port.PortA ? address : address += 0x10;
}
/// <inheritdoc/>
protected override void OpenPin(int pinNumber)
{
// No-op
}
/// <inheritdoc/>
protected override void ClosePin(int pinNumber)
{
// No-op
}
/// <inheritdoc/>
protected override PinMode GetPinMode(int pinNumber)
{
ValidatePin(pinNumber);
// IsBitSet returns true if bitNumber is flipped on in data.
bool IsBitSet(byte data, int bitNumber) => (data & (1 << bitNumber)) != 0;
if (pinNumber < 8)
{
return IsBitSet(InternalReadByte(Register.IODIR, Port.PortA), pinNumber)
? PinMode.Input
: PinMode.Output;
}
else
{
return IsBitSet(InternalReadByte(Register.IODIR, Port.PortB), pinNumber - 8)
? PinMode.Input
: PinMode.Output;
}
}
/// <inheritdoc/>
protected override void AddCallbackForPinValueChangedEvent(int pinNumber, PinEventTypes eventTypes,
PinChangeEventHandler callback) => throw new NotImplementedException();
/// <inheritdoc/>
protected override void RemoveCallbackForPinValueChangedEvent(int pinNumber, PinChangeEventHandler callback) =>
throw new NotImplementedException();
/// <inheritdoc/>
protected override int ConvertPinNumberToLogicalNumberingScheme(int pinNumber) => pinNumber;
/// <inheritdoc/>
protected override bool IsPinModeSupported(int pinNumber, PinMode mode) =>
(mode == PinMode.Input || mode == PinMode.Output);
}
}