forked from dotnet/iot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Max7219.cs
376 lines (331 loc) · 12.3 KB
/
Max7219.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
// 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.Spi;
namespace Iot.Device.Max7219
{
/// <summary>
/// Max7219 LED matrix driver
/// </summary>
public partial class Max7219 : IDisposable
{
private SpiDevice _spiDevice;
/// <summary>
/// MAX7219 Spi Clock Frequency
/// </summary>
public const int SpiClockFrequency = 10_000_000;
/// <summary>
/// MAX7219 SPI Mode
/// </summary>
public const SpiMode SpiMode = System.Device.Spi.SpiMode.Mode0;
/// <summary>
/// Number of digits Register per Module
/// </summary>
public const int NumDigits = 8;
/// <summary>
/// internal buffer used to write to registers for all devices.
/// </summary>
private readonly byte[] _writeBuffer;
/// <summary>
/// A Buffer that contains the values of the digits registers per device
/// </summary>
private readonly byte[,] _buffer;
/// <summary>
/// Number of cascaded devices
/// </summary>
/// <value></value>
public int CascadedDevices { get; private set; }
/// <summary>
/// The Rotation to be applied (when modules are assembled rotated way)
/// </summary>
public RotationType Rotation { get; set; }
/// <summary>
/// Creates a Max7219 Device given a <see paramref="spiDevice" /> to communicate over and the
/// number of devices that are cascaded.
/// </summary>
public Max7219(SpiDevice spiDevice, int cascadedDevices = 1, RotationType rotation = RotationType.None)
{
_spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
CascadedDevices = cascadedDevices;
Rotation = rotation;
_buffer = new byte[CascadedDevices, NumDigits];
_writeBuffer = new byte[2 * CascadedDevices];
}
/// <summary>
/// Standard initialization routine.
/// </summary>
public void Init()
{
SetRegister(Register.SCANLIMIT, 7); // show all 8 digits
SetRegister(Register.DECODEMODE, 0); // use matrix (not digits)
SetRegister(Register.DISPLAYTEST, 0); // no display test
SetRegister(Register.SHUTDOWN, 1); // not shutdown mode
Brightness(4); // intensity, range: 0..15
ClearAll();
}
/// <summary>
/// Sends data to a specific register replicated for all cascaded devices
/// </summary>
internal void SetRegister(Register register, byte data)
{
var i = 0;
for (byte deviceId = 0; deviceId < CascadedDevices; deviceId++)
{
_writeBuffer[i++] = (byte)register;
_writeBuffer[i++] = data;
}
Write(_writeBuffer);
}
/// <summary>
/// Write data do the spi device.
/// </summary>
/// <remarks>
/// The size of the data should be 2 * cascaded devices.
/// </remarks>
private void Write(Span<byte> data) => _spiDevice.Write(data);
/// <summary>
/// Sets the brightness of all cascaded devices to the same intensity level.
/// </summary>
/// <param name="intensity">intensity level ranging from 0..15. </param>
public void Brightness(int intensity)
{
if (intensity < 0 || intensity > 15)
{
throw new ArgumentOutOfRangeException(nameof(intensity),
$"Invalid intensity for Brightness {intensity}");
}
SetRegister(Register.INTENSITY, (byte)intensity);
}
/// <summary>
/// Gets or Sets the value to the digit value for a given device
/// and digit position
/// </summary>
public byte this[int deviceId, int digit]
{
get
{
ValidatePosition(deviceId, digit);
return _buffer[deviceId, digit];
}
set
{
ValidatePosition(deviceId, digit);
_buffer[deviceId, digit] = value;
}
}
/// <summary>
/// Gets or Sets the value to the digit value for a given absolute index
/// </summary>
public byte this[int index]
{
get
{
ValidateIndex(index, out var deviceId, out var digit);
return _buffer[deviceId, digit];
}
set
{
ValidateIndex(index, out var deviceId, out var digit);
_buffer[deviceId, digit] = value;
}
}
/// <summary>
/// Gets the total number of digits (cascaded devices * num digits)
/// </summary>
public int Length => CascadedDevices * NumDigits;
private void ValidatePosition(int deviceId, int digit)
{
if (deviceId < 0 || deviceId >= CascadedDevices)
{
throw new ArgumentOutOfRangeException(nameof(deviceId), $"Invalid device Id: {deviceId}");
}
if (digit < 0 || digit >= NumDigits)
{
throw new ArgumentOutOfRangeException(nameof(digit), $"Invalid digit: {digit}");
}
}
private void ValidateIndex(int index, out int deviceId, out int digit)
{
if (index < 0 || index > Length)
{
throw new ArgumentOutOfRangeException(nameof(index), $"Invalid index {index}");
}
deviceId = Math.DivRem(index, NumDigits, out digit);
}
/// <summary>
/// Writes all the Values to the devices.
/// </summary>
public void Flush() => WriteBuffer(_buffer);
/// <summary>
/// Writes a two dimensional buffer containing all the values to the devices.
/// </summary>
public void WriteBuffer(byte[,] buffer)
{
switch (Rotation)
{
case RotationType.None:
WriteBufferWithoutRotation(buffer);
break;
case RotationType.Half:
WriteBufferRotateHalf(buffer);
break;
case RotationType.Right:
WriteBufferRotateRight(buffer);
break;
case RotationType.Left:
WriteBufferRotateLeft(buffer);
break;
}
}
/// <summary>
/// Writes a two dimensional buffer containing all the values to the devices without roation
/// </summary>
private void WriteBufferWithoutRotation(byte[,] buffer)
{
ValidateBuffer(buffer);
for (int digit = 0; digit < NumDigits; digit++)
{
var i = 0;
for (var deviceId = CascadedDevices - 1; deviceId >= 0; deviceId--)
{
_writeBuffer[i++] = (byte)((int)Register.DIGIT0 + digit);
_writeBuffer[i++] = buffer[deviceId, digit];
}
Write(_writeBuffer);
}
}
/// <summary>
/// Writes a two dimensional buffer containing all the values to the devices
/// rotating values by 180 degree.
/// </summary>
private void WriteBufferRotateHalf(byte[,] buffer)
{
ValidateBuffer(buffer);
for (int digit = 0; digit < NumDigits; digit++)
{
var i = 0;
for (var deviceId = CascadedDevices - 1; deviceId >= 0; deviceId--)
{
_writeBuffer[i++] = (byte)((int)Register.DIGIT0 + digit);
byte b = buffer[deviceId, 7 - digit];
// reverse bits in byte
b = (byte)((b * 0x0202020202 & 0x010884422010) % 1023);
_writeBuffer[i++] = b;
}
Write(_writeBuffer);
}
}
/// <summary>
/// Writes a two dimensional buffer containing all the values to the devices
/// rotating values to the right.
/// </summary>
private void WriteBufferRotateRight(byte[,] buffer)
{
ValidateBuffer(buffer);
for (int digit = 0; digit < NumDigits; digit++)
{
var mask = 0x01 << digit;
var i = 0;
for (var deviceId = CascadedDevices - 1; deviceId >= 0; deviceId--)
{
_writeBuffer[i++] = (byte)((int)Register.DIGIT0 + digit);
byte value = 0;
byte targetBit = 0x80;
for (int bitDigit = 0; bitDigit < NumDigits; bitDigit++, targetBit >>= 1)
{
if ((buffer[deviceId, bitDigit] & mask) != 0)
{
value |= targetBit;
}
}
_writeBuffer[i++] = value;
}
Write(_writeBuffer);
}
}
/// <summary>
/// Writes a two dimensional buffer containing all the values to the devices
/// rotating values to the left.
/// </summary>
private void WriteBufferRotateLeft(byte[,] buffer)
{
ValidateBuffer(buffer);
for (int digit = 0; digit < NumDigits; digit++)
{
var mask = 0x80 >> digit;
var i = 0;
for (var deviceId = CascadedDevices - 1; deviceId >= 0; deviceId--)
{
_writeBuffer[i++] = (byte)((int)Register.DIGIT0 + digit);
byte value = 0;
byte targetBit = 0x01;
for (int bitDigit = 0; bitDigit < NumDigits; bitDigit++, targetBit <<= 1)
{
if ((buffer[deviceId, bitDigit] & mask) != 0)
{
value |= targetBit;
}
}
_writeBuffer[i++] = value;
}
Write(_writeBuffer);
}
}
/// <summary>
/// Validates the buffer dimensions.
/// </summary>
/// <param name="buffer">Buffer to validate</param>
private void ValidateBuffer(byte[,] buffer)
{
if (buffer.Rank != 2)
{
throw new ArgumentException(nameof(buffer), $"buffer must be two dimensional.");
}
if (buffer.GetUpperBound(0) != CascadedDevices - 1)
{
throw new ArgumentException(nameof(buffer),
$"buffer upper bound ({buffer.GetUpperBound(0)}) for dimension 0 must be {CascadedDevices - 1}.");
}
if (buffer.GetUpperBound(1) != NumDigits - 1)
{
throw new ArgumentException(nameof(buffer),
$"buffer upper bound ({buffer.GetUpperBound(1)}) for dimension 1 must be {NumDigits - 1}.");
}
}
/// <summary>
/// Clears the buffer from the given start to end (exclusive) and flushes
/// </summary>
public void Clear(int start, int end, bool flush = true)
{
if (end < 0 || end > CascadedDevices)
{
throw new ArgumentOutOfRangeException(nameof(end));
}
if (start < 0 || start >= end)
{
throw new ArgumentOutOfRangeException(nameof(end));
}
for (int deviceId = start; deviceId < end; deviceId++)
{
for (int digit = 0; digit < NumDigits; digit++)
{
this[deviceId, digit] = 0;
}
}
if (flush)
{
Flush();
}
}
/// <summary>
/// Clears the buffer from the given start to end and flushes
/// </summary>
public void ClearAll(bool flush = true) => Clear(0, CascadedDevices, flush);
/// <inheritdoc/>
public void Dispose()
{
_spiDevice?.Dispose();
_spiDevice = null!;
}
}
}