forked from raspberry-sharp/raspberry-sharp-io
/
I2cDriver.cs
443 lines (364 loc) · 16.6 KB
/
I2cDriver.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
#region References
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using Raspberry.IO.GeneralPurpose;
using RaspberryInterop = Raspberry.IO.GeneralPurpose.Interop;
using Raspberry.Timers;
#endregion
namespace Raspberry.IO.InterIntegratedCircuit
{
/// <summary>
/// Represents a driver for I2C devices.
/// </summary>
public class I2cDriver : IDisposable
{
#region Fields
private readonly object driverLock = new object();
private readonly ProcessorPin sdaPin;
private readonly ProcessorPin sclPin;
private readonly bool wasSdaPinSet;
private readonly bool wasSclPinSet;
private readonly IntPtr gpioAddress;
private readonly IntPtr bscAddress;
private int currentDeviceAddress;
private int waitInterval;
#endregion
#region Instance Management
/// <summary>
/// Initializes a new instance of the <see cref="I2cDriver"/> class.
/// </summary>
/// <param name="sdaPin">The SDA pin.</param>
/// <param name="sclPin">The SCL pin.</param>
public I2cDriver(ProcessorPin sdaPin, ProcessorPin sclPin)
{
this.sdaPin = sdaPin;
this.sclPin = sclPin;
var bscBase = GetBscBase(sdaPin, sclPin);
string memFilePath = "/dev/gpiomem";
if (RaspberryInterop.access("/dev/gpiomem", 0) != 0)
{
memFilePath = "/dev/mem";
}
var memoryFile = RaspberryInterop.open(memFilePath, RaspberryInterop.O_RDWR + RaspberryInterop.O_SYNC);
try
{
gpioAddress = RaspberryInterop.mmap(
IntPtr.Zero,
RaspberryInterop.BCM2835_BLOCK_SIZE,
RaspberryInterop.PROT_READ | RaspberryInterop.PROT_WRITE,
RaspberryInterop.MAP_SHARED,
memoryFile,
GetProcessorGpioAddress(Board.Current.Processor));
bscAddress = RaspberryInterop.mmap(
IntPtr.Zero,
RaspberryInterop.BCM2835_BLOCK_SIZE,
RaspberryInterop.PROT_READ | RaspberryInterop.PROT_WRITE,
RaspberryInterop.MAP_SHARED,
memoryFile,
bscBase);
}
finally
{
RaspberryInterop.close(memoryFile);
}
if (bscAddress == (IntPtr) RaspberryInterop.MAP_FAILED)
throw new InvalidOperationException("Unable to access device memory");
// Set the I2C pins to the Alt 0 function to enable I2C access on them
// remembers if the values were actually changed to clear them or not upon dispose
wasSdaPinSet = SetPinMode((uint)(int)sdaPin, RaspberryInterop.BCM2835_GPIO_FSEL_ALT0); // SDA
wasSclPinSet = SetPinMode((uint) (int) sclPin, RaspberryInterop.BCM2835_GPIO_FSEL_ALT0); // SCL
// Read the clock divider register
var dividerAddress = bscAddress + (int) RaspberryInterop.BCM2835_BSC_DIV;
var divider = (ushort) SafeReadUInt32(dividerAddress);
waitInterval = GetWaitInterval(divider);
var addressAddress = bscAddress + (int) RaspberryInterop.BCM2835_BSC_A;
SafeWriteUInt32(addressAddress, (uint) currentDeviceAddress);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
// Set all the I2C/BSC1 pins back to original values if changed
if (wasSdaPinSet)
{
SetPinMode((uint)(int)sdaPin, RaspberryInterop.BCM2835_GPIO_FSEL_INPT); // SDA
}
if (wasSclPinSet)
{
SetPinMode((uint)(int)sclPin, RaspberryInterop.BCM2835_GPIO_FSEL_INPT); // SCL
}
RaspberryInterop.munmap(gpioAddress, RaspberryInterop.BCM2835_BLOCK_SIZE);
RaspberryInterop.munmap(bscAddress, RaspberryInterop.BCM2835_BLOCK_SIZE);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the clock divider.
/// </summary>
/// <value>
/// The clock divider.
/// </value>
public int ClockDivider
{
get
{
var dividerAddress = bscAddress + (int) RaspberryInterop.BCM2835_BSC_DIV;
return (ushort) SafeReadUInt32(dividerAddress);
}
set
{
var dividerAddress = bscAddress + (int) RaspberryInterop.BCM2835_BSC_DIV;
SafeWriteUInt32(dividerAddress, (uint) value);
var actualDivider = (ushort) SafeReadUInt32(dividerAddress);
waitInterval = GetWaitInterval(actualDivider);
}
}
#endregion
#region Methods
/// <summary>
/// Connects the specified device address.
/// </summary>
/// <param name="deviceAddress">The device address.</param>
/// <returns>The device connection</returns>
public I2cDeviceConnection Connect(int deviceAddress)
{
return new I2cDeviceConnection(this, deviceAddress);
}
#endregion
#region Internal Methods
/// <summary>
/// Executes the specified transaction.
/// </summary>
/// <param name="deviceAddress">The address of the device.</param>
/// <param name="transaction">The transaction.</param>
internal void Execute(int deviceAddress, I2cTransaction transaction)
{
lock (driverLock)
{
var control = bscAddress + (int)RaspberryInterop.BCM2835_BSC_C;
foreach (I2cAction action in transaction.Actions)
{
if (action is I2cWriteAction)
{
Write(deviceAddress, action.Buffer);
}
else if (action is I2cReadAction)
{
Read(deviceAddress, action.Buffer);
}
else
{
throw new InvalidOperationException("Only read and write transactions are allowed.");
}
}
WriteUInt32Mask(control, RaspberryInterop.BCM2835_BSC_S_DONE, RaspberryInterop.BCM2835_BSC_S_DONE);
}
}
#endregion
#region Private Helpers
private void Write(int deviceAddress, byte[] buffer)
{
this.EnsureDeviceAddress(deviceAddress);
var len = (uint)buffer.Length;
var dlen = this.bscAddress + (int)RaspberryInterop.BCM2835_BSC_DLEN;
var fifo = this.bscAddress + (int)RaspberryInterop.BCM2835_BSC_FIFO;
var status = this.bscAddress + (int)RaspberryInterop.BCM2835_BSC_S;
var control = this.bscAddress + (int)RaspberryInterop.BCM2835_BSC_C;
var remaining = len;
var i = 0;
// Clear FIFO
WriteUInt32Mask(control, RaspberryInterop.BCM2835_BSC_C_CLEAR_1, RaspberryInterop.BCM2835_BSC_C_CLEAR_1);
// Clear Status
WriteUInt32(status, RaspberryInterop.BCM2835_BSC_S_CLKT | RaspberryInterop.BCM2835_BSC_S_ERR | RaspberryInterop.BCM2835_BSC_S_DONE);
// Set Data Length
WriteUInt32(dlen, len);
while (remaining != 0 && i < RaspberryInterop.BCM2835_BSC_FIFO_SIZE)
{
WriteUInt32(fifo, buffer[i]);
i++;
remaining--;
}
// Enable device and start transfer
WriteUInt32(control, RaspberryInterop.BCM2835_BSC_C_I2CEN | RaspberryInterop.BCM2835_BSC_C_ST);
while ((ReadUInt32(status) & RaspberryInterop.BCM2835_BSC_S_DONE) == 0)
{
while (remaining != 0 && (ReadUInt32(status) & RaspberryInterop.BCM2835_BSC_S_TXD) != 0)
{
// Write to FIFO, no barrier
WriteUInt32(fifo, buffer[i]);
i++;
remaining--;
}
this.Wait(remaining);
}
if ((SafeReadUInt32(status) & RaspberryInterop.BCM2835_BSC_S_ERR) != 0) // Received a NACK
throw new InvalidOperationException("Read operation failed with BCM2835_I2C_REASON_ERROR_NACK status");
if ((SafeReadUInt32(status) & RaspberryInterop.BCM2835_BSC_S_CLKT) != 0) // Received Clock Stretch Timeout
throw new InvalidOperationException("Read operation failed with BCM2835_I2C_REASON_ERROR_CLKT status");
if (remaining != 0) // Not all data is sent
throw new InvalidOperationException(string.Format("Read operation failed with BCM2835_I2C_REASON_ERROR_DATA status, missing {0} bytes", remaining));
}
private void Read(int deviceAddress, byte[] buffer)
{
this.EnsureDeviceAddress(deviceAddress);
var dlen = this.bscAddress + (int)RaspberryInterop.BCM2835_BSC_DLEN;
var fifo = this.bscAddress + (int)RaspberryInterop.BCM2835_BSC_FIFO;
var status = this.bscAddress + (int)RaspberryInterop.BCM2835_BSC_S;
var control = this.bscAddress + (int)RaspberryInterop.BCM2835_BSC_C;
var remaining = (uint)buffer.Length;
uint i = 0;
// Clear FIFO
WriteUInt32Mask(control, RaspberryInterop.BCM2835_BSC_C_CLEAR_1, RaspberryInterop.BCM2835_BSC_C_CLEAR_1);
// Clear Status
WriteUInt32(status, RaspberryInterop.BCM2835_BSC_S_CLKT | RaspberryInterop.BCM2835_BSC_S_ERR | RaspberryInterop.BCM2835_BSC_S_DONE);
// Set Data Length
WriteUInt32(dlen, (uint)buffer.Length);
// Start read
WriteUInt32(control, RaspberryInterop.BCM2835_BSC_C_I2CEN | RaspberryInterop.BCM2835_BSC_C_ST | RaspberryInterop.BCM2835_BSC_C_READ);
while ((ReadUInt32(status) & RaspberryInterop.BCM2835_BSC_S_DONE) == 0)
{
while ((ReadUInt32(status) & RaspberryInterop.BCM2835_BSC_S_RXD) != 0)
{
// Read from FIFO, no barrier
buffer[i] = (byte)ReadUInt32(fifo);
i++;
remaining--;
}
this.Wait(remaining);
}
while (remaining != 0 && (ReadUInt32(status) & RaspberryInterop.BCM2835_BSC_S_RXD) != 0)
{
buffer[i] = (byte)ReadUInt32(fifo);
i++;
remaining--;
}
if ((SafeReadUInt32(status) & RaspberryInterop.BCM2835_BSC_S_ERR) != 0) // Received a NACK
throw new InvalidOperationException("Read operation failed with BCM2835_I2C_REASON_ERROR_NACK status");
if ((SafeReadUInt32(status) & RaspberryInterop.BCM2835_BSC_S_CLKT) != 0) // Received Clock Stretch Timeout
throw new InvalidOperationException("Read operation failed with BCM2835_I2C_REASON_ERROR_CLKT status");
if (remaining != 0) // Not all data is received
throw new InvalidOperationException(string.Format("Read operation failed with BCM2835_I2C_REASON_ERROR_DATA status, missing {0} bytes", remaining));
}
private static uint GetProcessorBscAddress(Processor processor)
{
return RaspberryInterop.GetProcessorBscAddress(processor);
}
private static uint GetProcessorGpioAddress(Processor processor)
{
return RaspberryInterop.GetProcessorGpioBaseAddress(processor);
}
private void EnsureDeviceAddress(int deviceAddress)
{
if (deviceAddress != currentDeviceAddress)
{
var addressAddress = bscAddress + (int)RaspberryInterop.BCM2835_BSC_A;
SafeWriteUInt32(addressAddress, (uint)deviceAddress);
currentDeviceAddress = deviceAddress;
}
}
private void Wait(uint remaining)
{
// When remaining data is to be received, then wait for a fully FIFO
if (remaining != 0)
Timer.Sleep(TimeSpan.FromMilliseconds(waitInterval * (remaining >= RaspberryInterop.BCM2835_BSC_FIFO_SIZE ? RaspberryInterop.BCM2835_BSC_FIFO_SIZE : remaining) / 1000d));
}
private static int GetWaitInterval(ushort actualDivider)
{
// Calculate time for transmitting one byte
// 1000000 = micros seconds in a second
// 9 = Clocks per byte : 8 bits + ACK
return (int)((decimal)actualDivider * 1000000 * 9 / RaspberryInterop.BCM2835_CORE_CLK_HZ);
}
private static uint GetBscBase(ProcessorPin sdaPin, ProcessorPin sclPin)
{
switch (GpioConnectionSettings.ConnectorPinout)
{
case ConnectorPinout.Rev1:
if (sdaPin == ProcessorPin.Pin0 && sclPin == ProcessorPin.Pin1)
return RaspberryInterop.BCM2835_BSC0_BASE;
throw new InvalidOperationException("No I2C device exist on the specified pins");
case ConnectorPinout.Rev2:
if (sdaPin == ProcessorPin.Pin28 && sclPin == ProcessorPin.Pin29)
return RaspberryInterop.BCM2835_BSC0_BASE;
if (sdaPin == ProcessorPin.Pin2 && sclPin == ProcessorPin.Pin3)
return RaspberryInterop.BCM2835_BSC1_BASE;
throw new InvalidOperationException("No I2C device exist on the specified pins");
case ConnectorPinout.Plus:
if (sdaPin == ProcessorPin.Pin2 && sclPin == ProcessorPin.Pin3)
return GetProcessorBscAddress(Board.Current.Processor);
throw new InvalidOperationException("No I2C device exist on the specified pins");
default:
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Connector pinout {0} is not supported", GpioConnectionSettings.ConnectorPinout));
}
}
/// <summary>
///
/// </summary>
/// <param name="pin"></param>
/// <param name="mode"></param>
/// <returns>True when value was changed, false otherwise.</returns>
private bool SetPinMode(uint pin, uint mode)
{
// Function selects are 10 pins per 32 bit word, 3 bits per pin
var paddr = gpioAddress + (int) (RaspberryInterop.BCM2835_GPFSEL0 + 4*(pin/10));
var shift = (pin%10)*3;
var mask = RaspberryInterop.BCM2835_GPIO_FSEL_MASK << (int) shift;
var value = mode << (int) shift;
var existing = ReadUInt32(paddr) & mask;
if (existing != value)
{
//Console.WriteLine($"existing is {x} masked:{x & mask} vs mask:{mask} value:{value}");
WriteUInt32Mask(paddr, value, mask);
return true;
}
else
{
return false;
}
}
private static void WriteUInt32Mask(IntPtr address, uint value, uint mask)
{
var v = SafeReadUInt32(address);
v = (v & ~mask) | (value & mask);
SafeWriteUInt32(address, v);
}
private static uint SafeReadUInt32(IntPtr address)
{
// Make sure we dont return the _last_ read which might get lost
// if subsequent code changes to a different peripheral
unchecked
{
var returnValue = (uint) Marshal.ReadInt32(address);
Marshal.ReadInt32(address);
return returnValue;
}
}
private static uint ReadUInt32(IntPtr address)
{
unchecked
{
return (uint) Marshal.ReadInt32(address);
}
}
private static void SafeWriteUInt32(IntPtr address, uint value)
{
// Make sure we don't rely on the first write, which may get
// lost if the previous access was to a different peripheral.
unchecked
{
Marshal.WriteInt32(address, (int)value);
Marshal.WriteInt32(address, (int)value);
}
}
private static void WriteUInt32(IntPtr address, uint value)
{
unchecked
{
Marshal.WriteInt32(address, (int)value);
}
}
#endregion
}
}