-
Notifications
You must be signed in to change notification settings - Fork 598
/
Copy pathGoPiGo3.cs
1025 lines (925 loc) · 41 KB
/
GoPiGo3.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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Buffers.Binary;
using System.Device.Spi;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Iot.Device.GoPiGo3.Models;
namespace Iot.Device.GoPiGo3
{
/// <summary>
/// A GoPiGo3 class for a GoPiGo3 Dexter Industries robot kit
/// </summary>
public class GoPiGo : IDisposable
{
private const int DefaultMotorGearRatio = 120;
private const int DefaultEncoderTicksPerRotation = 6;
private const int GroveI2cLengthLimit = 32;
private const string ManufacturerName = "Dexter Industries";
private const string BoardName = "GoPiGo3";
// this is used by GoPiGo3 when the data returned are correct
private const byte SpiCorrectDataReturned = 0xA5;
// This is used by GoPiGo3 when returning I2C data returned are correct
private const byte I2cCorrectData = 0;
private bool _autoDispose;
private SpiDevice _spiDevice = null;
#region Properties
/// <summary>
/// Get the SPI address of GoPiGo3. By default, it is 8
/// </summary>
public byte SpiAddress { get; internal set; }
/// <summary>
/// Set or get a specific gear ratio for the encoder
/// </summary>
public int MotorGearRatio { get; set; }
/// <summary>
/// Set or get a specific ticks per rotation for the encoder
/// </summary>
public int EncoderTicksPerRotation { get; set; }
/// <summary>
/// Return the number of ticks per degree
/// </summary>
public double MotorTicksPerDegree => (MotorGearRatio * EncoderTicksPerRotation / 360.0);
/// <summary>
/// The 2 Grove Sensor
/// </summary>
public GroveSensor[] GroveSensor { get; internal set; }
/// <summary>
/// The GoPiGo3 information including hardware, firmware, ID and Manufacturer
/// </summary>
public GoPiGoInfo GoPiGo3Info { get; internal set; }
/// <summary>
/// Get the real 5V and Battery/VCC voltages
/// </summary>
public GoPiGoVoltage GoPiGoVoltage => new GoPiGoVoltage() { Voltage5V = GetVoltage5V(), VoltageBattery = GetVoltageBatteryVcc() };
#endregion
#region Constructor and Dispose
/// <summary>
/// Create a GoPiGo class
/// </summary>
/// <param name="spiDevice">The SpiDevice</param>
/// <param name="spiAddress">The SPI address, by default 8</param>
/// <param name="autoDetect">Try to autodetect the board</param>
/// <param name="autoDispose">True to dispose the SpiDevice when disposing the class</param>
public GoPiGo(SpiDevice spiDevice, byte spiAddress = 8, bool autoDetect = true, bool autoDispose = true)
{
_spiDevice = spiDevice ?? throw new ArgumentException("SpiDevice can't be null");
SpiAddress = spiAddress;
_autoDispose = autoDispose;
InitializeGoPiGo(autoDetect);
}
private void InitializeGoPiGo(bool autoDetect)
{
GoPiGo3Info = new GoPiGoInfo();
if (autoDetect == true)
{
try
{
GoPiGo3Info.Manufacturer = GetManufacturer();
GoPiGo3Info.Board = GetBoard();
GoPiGo3Info.SoftwareVersion = GetFirmwareVersion();
GoPiGo3Info.HardwareVersion = GetHardwareVersion();
GoPiGo3Info.Id = GetIdHex();
}
catch (IOException ex)
{
throw new IOException($"No SPI response. GoPiGo3 with address {SpiAddress} not connected.", ex);
}
}
if ((GoPiGo3Info.Manufacturer != ManufacturerName) || (GoPiGo3Info.Board != BoardName))
{
throw new IOException($"GoPiGo3 with address {SpiAddress} not connected.");
}
MotorGearRatio = DefaultMotorGearRatio;
EncoderTicksPerRotation = DefaultEncoderTicksPerRotation;
// Initialise the 2 Grove sensors
GroveSensor = new GroveSensor[2]
{
new GroveSensor(GrovePort.Grove1),
new GroveSensor(GrovePort.Grove2)
};
}
/// <summary>
/// Reset everything
/// </summary>
public void Dispose()
{
// Reset Grove sensors
SetGroveType(GrovePort.Both, GroveSensorType.Custom);
SetGroveMode(GrovePort.Both, GroveInputOutput.InputDigital);
// Turn off the motors
SetMotorPower(MotorPort.Both, (byte)MotorSpeed.Float);
// Reset the motor limits
SetMotorLimits(MotorPort.Both, 0, 0);
// Turn off the servos
SetServo(ServoPort.Both, 0);
// Turn off the LEDs
SetLed((byte)GoPiGo3Led.LedEyeLeft + (byte)GoPiGo3Led.LedEyeRight + (byte)GoPiGo3Led.LedBlinkerLeft + (byte)GoPiGo3Led.LedBlinkerRight, Color.Black);
if (_autoDispose)
{
_spiDevice.Dispose();
}
}
#endregion
#region SPI transfer
/// <summary>
/// Conduct a SPI transaction
/// </summary>
/// <param name="buffer">A byte array to send.The length of the array will determine how many bytes are transferred.</param>
/// <returns>Returns an array of the bytes read.</returns>
private byte[] SpiTransferArray(byte[] buffer)
{
byte[] result = new byte[buffer.Length];
_spiDevice.TransferFullDuplex(buffer, result);
return result;
}
/// <summary>
/// Read a 32 bit value over SPI
/// </summary>
/// <param name="MessageType">The SPI message type</param>
/// <returns>Returns the value read</returns>
public int SpiRead32(SpiMessageType MessageType)
{
byte[] outArray = { SpiAddress, (byte)MessageType, 0, 0, 0, 0, 0, 0 };
byte[] reply = SpiTransferArray(outArray);
if (reply[3] == SpiCorrectDataReturned)
{
return BinaryPrimitives.ReadInt32BigEndian(new Span<byte>(reply).Slice(4));
}
throw new IOException($"{nameof(SpiRead32)} : no SPI response");
}
/// <summary>
/// Read a 16 bit value over SPI
/// </summary>
/// <param name="MessageType">The SPI message type</param>
/// <returns>Returns the value read</returns>
public short SpiRead16(SpiMessageType MessageType)
{
byte[] outArray = { SpiAddress, (byte)MessageType, 0, 0, 0, 0, };
byte[] reply = SpiTransferArray(outArray);
if (reply[3] == SpiCorrectDataReturned)
{
return BinaryPrimitives.ReadInt16BigEndian(new Span<byte>(reply).Slice(4));
}
throw new IOException($"{nameof(SpiRead16)} : no SPI response");
}
/// <summary>
/// Read a 8 bit value over SPI
/// </summary>
/// <param name="MessageType">The SPI message type</param>
/// <returns>Returns the value read</returns>
public byte SpiRead8(SpiMessageType MessageType)
{
byte[] outArray = { SpiAddress, (byte)MessageType, 0, 0, 0 };
byte[] reply = SpiTransferArray(outArray);
return (reply[3] == SpiCorrectDataReturned) ? reply[4] : throw new IOException($"{nameof(SpiRead16)} : no SPI response");
}
/// <summary>
/// Send a 8 bit value over SPI
/// </summary>
/// <param name="MessageType">The SPI message type</param>
/// <param name="Value">The value to be sent</param>
public void SpiWrite8(SpiMessageType MessageType, byte Value)
{
byte[] outArray = { SpiAddress, (byte)MessageType, Value };
SpiTransferArray(outArray);
}
/// <summary>
/// Send a 16 bit value over SPI
/// </summary>
/// <param name="MessageType">The SPI message type</param>
/// <param name="Value">The value to be sent</param>
public void SpiWrite16(SpiMessageType MessageType, short Value)
{
byte[] outArray = { SpiAddress, (byte)MessageType, (byte)((Value >> 8) & 0xFF), (byte)Value };
SpiTransferArray(outArray);
}
/// <summary>
/// Send a 24 bit value over SPI
/// </summary>
/// <param name="MessageType">The SPI message type</param>
/// <param name="Value">The value to be sent</param>
public void SpiWrite24(SpiMessageType MessageType, int Value)
{
byte[] outArray = { SpiAddress, (byte)MessageType, (byte)((Value >> 16) & 0xFF), (byte)((Value >> 8) & 0xFF), (byte)Value };
SpiTransferArray(outArray);
}
/// <summary>
/// Send a 32 bit value over SPI
/// </summary>
/// <param name="MessageType">The SPI message type</param>
/// <param name="Value">The value to be sent</param>
public void SpiWrite32(SpiMessageType MessageType, int Value)
{
byte[] outArray = { SpiAddress, (byte)MessageType, (byte)((Value >> 24) & 0xFF), (byte)((Value >> 16) & 0xFF), (byte)((Value >> 8) & 0xFF), (byte)Value };
SpiTransferArray(outArray);
}
#endregion
#region Board elements
/// <summary>
/// Read the 20 characters of GoPiGo3 manufacturer name
/// </summary>
/// <returns>Returns the GoPiGo3 manufacturer name string</returns>
public string GetManufacturer()
{
string retVal = string.Empty;
byte[] outArray =
{
SpiAddress, (byte)SpiMessageType.GetManufacturer, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
byte[] reply = SpiTransferArray(outArray);
if (reply[3] != SpiCorrectDataReturned)
{
throw new IOException("No SPI response");
}
return Encoding.ASCII.GetString(reply.Skip(4).Where(c => c != 0).ToArray());
}
/// <summary>
/// Read the 20 characters of GoPiGo3 board name
/// </summary>
/// <returns>Returns the GoPiGo3 board name string</returns>
public string GetBoard()
{
string retVal = string.Empty;
byte[] outArray =
{
SpiAddress, (byte)SpiMessageType.GetName, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
byte[] reply = SpiTransferArray(outArray);
if (reply[3] != SpiCorrectDataReturned)
{
throw new IOException("No SPI response");
}
return Encoding.ASCII.GetString(reply.Skip(4).Where(c => c != 0).ToArray());
}
/// <summary>
/// Read the hardware version
/// </summary>
/// <returns>Returns the hardware version as a string</returns>
public Version GetHardwareVersion()
{
string retVal = string.Empty;
int version = SpiRead32(SpiMessageType.GetHardwareVersion);
return new Version(version / 1000000, (version / 1000) % 1000, version % 1000);
}
/// <summary>
/// Read the 128 bit GoPiGo3 hardware serial number
/// </summary>
/// <returns>Returns the serial number as 32 char HEX formatted string</returns>
public string GetIdHex()
{
return string.Join(string.Empty, GetId().Select((b) => b.ToString("X2")));
}
/// <summary>
/// Read the 128 bit GoPiGo3 hardware serial number
/// </summary>
/// <returns>Returns the serial number as a byte array</returns>
public byte[] GetId()
{
string retVal = string.Empty;
byte[] outArray =
{
SpiAddress, (byte)SpiMessageType.GetId, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
byte[] reply = SpiTransferArray(outArray);
if (reply[3] != SpiCorrectDataReturned)
{
throw new IOException("No SPI response");
}
return reply.Skip(4).Take(16).ToArray();
}
/// <summary>
/// Read the firmware version
/// </summary>
/// <returns>Returns the firmware version</returns>
public Version GetFirmwareVersion()
{
string retVal = string.Empty;
int version = SpiRead32(SpiMessageType.GetFirmwareVersion);
return new Version(version / 1000000, (version / 1000) % 1000, version % 1000);
}
/// <summary>
/// Set the led color
/// </summary>
/// <param name="led">The led, either Left, Right, Blinky Left, Blinky Right and Wifi. Note you should only control the wifi one if you are sure to be connected to wifi</param>
/// <param name="ledColor">The Color of the <paramref name="led"/></param>
public void SetLed(byte led, Color ledColor)
{
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetLed, led, ledColor.R, ledColor.G, ledColor.B };
var reply = SpiTransferArray(outArray);
}
/// <summary>
/// Get the 5v circuit voltage
/// </summary>
/// <returns>Returns the real 5v circuit voltage</returns>
public double GetVoltage5V()
{
var value = SpiRead16(SpiMessageType.GetVoltage5V);
return (value / 1000.0);
}
/// <summary>
/// Get the battery voltage
/// </summary>
/// <returns>Returns the real battery/Vcc voltage</returns>
public double GetVoltageBatteryVcc()
{
var value = SpiRead16(SpiMessageType.GetVoltageVcc);
return (value / 1000.0);
}
#endregion
#region Servo and motors
/// <summary>
/// Move the servo motor with a specific pulse in microseconds
/// </summary>
/// <param name="servo">The servo port Servo1 or Servo2</param>
/// <param name="pulseMicroseconds">The pulse in microseconds</param>
public void SetServo(ServoPort servo, int pulseMicroseconds)
{
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetServo, (byte)servo, (byte)((pulseMicroseconds >> 8) & 0xFF), (byte)(pulseMicroseconds & 0xFF) };
var reply = SpiTransferArray(outArray);
}
/// <summary>
/// Set the motor power in percent
/// </summary>
/// <param name="port">The Motor port to use, can be MotorLeft and/or MotorRight</param>
/// <param name="power">The power from - 100 to 100, or -128 for float</param>
public void SetMotorPower(MotorPort port, int power)
{
power = Math.Clamp(power, -128, 127);
byte bPower = (byte)(power & 0xFF);
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetMotorPower, (byte)port, bPower };
var ret = SpiTransferArray(outArray);
}
/// <summary>
/// Set the motor target position in degrees
/// </summary>
/// <param name="port">The Motor port to use, can be MotorLeft and/or MotorRight</param>
/// <param name="positionDegree">The target position in degree</param>
public void SetMotorPosition(MotorPort port, int positionDegree)
{
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetMotorPosition, (byte)port, (byte)((positionDegree >> 24) & 0xFF), (byte)((positionDegree >> 16) & 0xFF), (byte)((positionDegree >> 8) & 0xFF), (byte)(positionDegree & 0xFF) };
var ret = SpiTransferArray(outArray);
}
/// <summary>
/// Set the motor target position KP constant
/// If you set KP higher, the motor will be more responsive to errors in position, at the cost of perhaps overshooting and oscillating.
/// KD slows down the motor as it approaches the target, and helps to prevent overshoot.
/// In general, if you increase KP, you should also increase KD to keep the motor from overshooting and oscillating.
/// See as well https://en.wikipedia.org/wiki/PID_controller
/// </summary>
/// <param name="port">The Motor port to use, can be MotorLeft and/or MotorRight</param>
/// <param name="kp">The KP constant (default 25)</param>
public void SetMotorPositionKP(MotorPort port, byte kp = 25)
{
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetMotorPositionKp, (byte)port, kp };
var ret = SpiTransferArray(outArray);
}
/// <summary>
/// Set the motor target position KD constant
/// If you set KP higher, the motor will be more responsive to errors in position, at the cost of perhaps overshooting and oscillating.
/// KD slows down the motor as it approaches the target, and helps to prevent overshoot.
/// In general, if you increase kp, you should also increase KD to keep the motor from overshooting and oscillating.
/// See as well https://en.wikipedia.org/wiki/PID_controller
/// </summary>
/// <param name="port">The Motor port to use, can be MotorLeft and/or MotorRight</param>
/// <param name="kd">The KD constant (default 70)</param>
public void SetMotorPositionKD(MotorPort port, byte kd = 70)
{
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetMotorPositionKd, (byte)port, kd };
var ret = SpiTransferArray(outArray);
}
/// <summary>
/// Set the motor target speed in degrees per second
/// </summary>
/// <param name="port">The Motor port to use, can be MotorLeft and/or MotorRight</param>
/// <param name="dps">The target speed in degrees per second</param>
public void SetMotorDps(MotorPort port, int dps)
{
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetMotorDps, (byte)port, (byte)((dps >> 8) & 0xFF), (byte)(dps & 0xFF) };
var ret = SpiTransferArray(outArray);
}
/// <summary>
/// Set the motor speed limit
/// </summary>
/// <param name="port">The Motor port to use, can be MotorLeft and/or MotorRight</param>
/// <param name="powerPercent">The power limit in percent (0 to 100), with 0 being no limit (100)</param>
/// <param name="dps">The speed limit in degrees per second, with 0 being no limit</param>
public void SetMotorLimits(MotorPort port, byte powerPercent = 0, int dps = 0)
{
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetMotorLimits, (byte)port, powerPercent, (byte)((dps >> 8) & 0xFF), (byte)(dps & 0xFF) };
var ret = SpiTransferArray(outArray);
}
/// <summary>
/// Read a motor status
/// </summary>
/// <param name="port">The Motor port to use, can be MotorLeft or MotorRight</param>
/// <returns>Returns MotorStatus containing the status of the motor</returns>
public MotorStatus GetMotorStatus(MotorPort port)
{
MotorStatus motorStatus = new MotorStatus();
SpiMessageType message_type = (port == MotorPort.MotorRight) ? SpiMessageType.GetMotorStatusRight : SpiMessageType.GetMotorStatusLeft;
byte[] outArray = { SpiAddress, (byte)message_type, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
var reply = SpiTransferArray(outArray);
if (reply[3] == SpiCorrectDataReturned)
{
motorStatus.Speed = reply[5];
if ((motorStatus.Speed & 0x80) > 0)
{
motorStatus.Speed = -motorStatus.Speed;
}
motorStatus.Encoder = (int)(BinaryPrimitives.ReadInt32BigEndian(new Span<byte>(reply).Slice(6)) / MotorTicksPerDegree);
motorStatus.Dps = ((reply[10] << 8) | reply[11]);
if ((motorStatus.Dps & 0x8000) > 0)
{
motorStatus.Dps = motorStatus.Dps - 0x10000;
}
motorStatus.Flags = (MotorStatusFlags)reply[4];
}
else
{
throw new IOException($"{nameof(GetMotorStatus)} error: no SPI response");
}
return motorStatus;
}
/// <summary>
/// Offset a motor encoder
/// </summary>
/// <param name="port">The Motor port to use, can be MotorLeft and/or MotorRight</param>
/// <param name="positionOffset">The encoder offset. Zero the encoder by offsetting it by the current position</param>
public void OffsetMotorEncoder(MotorPort port, int positionOffset)
{
positionOffset = (int)(positionOffset * MotorTicksPerDegree);
byte[] outArray = new byte[] { SpiAddress, (byte)SpiMessageType.OffsetMotorEncoder, (byte)port, (byte)((positionOffset >> 24) & 0xFF), (byte)((positionOffset >> 16) & 0xFF), (byte)((positionOffset >> 8) & 0xFF), (byte)(positionOffset & 0xFF) };
SpiTransferArray(outArray);
}
/// <summary>
/// Read a motor encoder in degrees
/// </summary>
/// <param name="port">The Motor port to use, can be MotorLeft or MotorRight</param>
/// <returns>Returns the encoder position in degrees</returns>
public int GetMotorEncoder(MotorPort port)
{
SpiMessageType message_type;
if (port == MotorPort.MotorLeft)
{
message_type = SpiMessageType.GetMotorEncoderLeft;
}
else if (port == MotorPort.MotorRight)
{
message_type = SpiMessageType.GetMotorEncoderRight;
}
else
{
throw new IOException($"{nameof(GetMotorEncoder)} error. Must be one motor port at a time, PortMotorLeft or PortMotorRight");
}
var encoder = SpiRead32(message_type);
if ((encoder & 0x80000000) > 0)
{
encoder = (int)(encoder - 0x100000000);
}
return (int)(encoder / MotorTicksPerDegree);
}
#endregion
#region Grove
/// <summary>
/// Set grove type
/// </summary>
/// <param name="port">The grove port(s). Grove1 and/or Grove2</param>
/// <param name="type">The grove device type, refer to GroveSensorType</param>
public void SetGroveType(GrovePort port, GroveSensorType type)
{
if ((port == GrovePort.Grove1) || (port == GrovePort.Both))
{
GroveSensor[0].SensorType = type;
}
if ((port == GrovePort.Grove2) || (port == GrovePort.Both))
{
GroveSensor[1].SensorType = type;
}
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetGroveType, (byte)port, (byte)type };
SpiTransferArray(outArray);
}
/// <summary>
/// Set grove analog digital pin mode as input or output
/// </summary>
/// <param name="port">The Grove Pin, can be any combination of Grove1Pin1, Grove1Pin2, Grove2Pin1 and/or Grove2Pin2</param>
/// <param name="mode">The Grove pin mode, refere to GroveInputOutput</param>
public void SetGroveMode(GrovePort port, GroveInputOutput mode)
{
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetGroveMode, (byte)port, (byte)mode };
SpiTransferArray(outArray);
}
/// <summary>
/// Set grove output pin low or high
/// </summary>
/// <param name="port">The Grove Pin, can be any combination of Grove1Pin1, Grove1Pin2, Grove2Pin1 and/or Grove2Pin2</param>
/// <param name="state">The pin state. false for low or true for high.</param>
public void SetGroveState(GrovePort port, bool state)
{
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetGroveState, (byte)port, (byte)(state ? 1 : 0) };
SpiTransferArray(outArray);
}
/// <summary>
/// Set grove output pin PWM
/// </summary>
/// <param name="port">The Grove Pin, can be any combination of Grove1Pin1, Grove1Pin2, Grove2Pin1 and/or Grove2Pin2</param>
/// <param name="duty">The PWM duty cycle in percent from 0.0 to 100.0, 1 floating point precision</param>
public void SetGrovePwmDuty(GrovePort port, double duty)
{
duty = Math.Clamp(duty, (byte)0, (byte)100);
var duty_value = (UInt16)(duty * 10.0);
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetGrovePwmDuty, (byte)port, (byte)((duty_value >> 8) & 0xFF), (byte)(duty_value & 0xFF) };
SpiTransferArray(outArray);
}
/// <summary>
/// Set grove PWM frequency
/// </summary>
/// <param name="port">The grove port(s).GROVE_1 and / or GROVE_2.</param>
/// <param name="freq">The PWM frequency.Range is 3 through 48000Hz.Default is 24000(24kHz). Limit to 48000, which is the highest frequency supported for 0.1% resolution.</param>
public void GetGrovePwmFrequency(GrovePort port, uint freq = 24000)
{
freq = Math.Clamp(freq, 3, 48000);
byte[] outArray = { SpiAddress, (byte)SpiMessageType.SetGrovePwmFrequency, (byte)port, (byte)((freq >> 8) & 0xFF), (byte)(freq & 0xFF) };
SpiTransferArray(outArray);
}
/// <summary>
/// Conduct an I2C transaction
/// </summary>
/// <param name="port">The grove port. GROVE_1 or GROVE_2</param>
/// <param name="addr">The I2C address of the slave to be addressed.</param>
/// <param name="arrayToSend">An array of bytes to send.</param>
/// <param name="inBytes">The number of bytes to read.</param>
/// <returns>Returns a byte array with what has been read from the I2C element</returns>
public byte[] GroveI2cTransfer(GrovePort port, byte addr, byte[] arrayToSend, byte inBytes = 0)
{
Stopwatch stopwatch = Stopwatch.StartNew();
var timeout = stopwatch.ElapsedMilliseconds + 5;
while (true)
{
try
{
GroveI2cStart(port, addr, arrayToSend, inBytes);
break;
}
catch (IOException ex)
{
if (stopwatch.ElapsedMilliseconds > timeout)
{
throw new IOException($"{nameof(GroveI2cTransfer)} error: timeout while transfering the I2C data", ex);
}
}
}
// Wait for the sensors to be read
// In theory 115µs per byte sent
int towait = 0;
if (arrayToSend != null)
{
if (arrayToSend.Length != 0)
{
towait += 1 + arrayToSend.Length;
}
}
if (inBytes > 0)
{
towait += 1 + inBytes;
}
timeout += (int)(0.115 * towait);
// but make sure we wait a minimum of 1 ms
if (towait > 0)
{
timeout = Math.Clamp(timeout, 1, 32);
Thread.Sleep((int)timeout);
}
timeout = stopwatch.ElapsedMilliseconds + 5;
while (true)
{
try
{
return GetGroveValue(port);
}
catch (IOException ex)
{
throw new IOException($"{nameof(GroveI2cTransfer)} error: timeout while transfering the I2C data", ex);
}
}
}
/// <summary>
/// Start an I2C transaction
/// </summary>
/// <param name="port">The Grove Port, one at the time Grove1 or Grove2</param>
/// <param name="addr">The I2C address of the slave to be addressed.</param>
/// <param name="arrayToSend">An array of bytes to send.</param>
/// <param name="inBytes">The number of bytes to read.</param>
public void GroveI2cStart(GrovePort port, byte addr, byte[] arrayToSend, byte inBytes = 0)
{
SpiMessageType message_type;
byte port_index;
if (port == GrovePort.Grove1)
{
message_type = SpiMessageType.StartGrove1I2c;
port_index = 0;
}
else if (port == GrovePort.Grove2)
{
message_type = SpiMessageType.StartGrove2I2c;
port_index = 1;
}
else
{
throw new ArgumentException($"{nameof(GroveI2cStart)} error: Port unsupported. Must be either Grove 1 or Grove 2.");
}
var address = ((addr & 0x7F) << 1);
if (inBytes > GroveI2cLengthLimit)
{
throw new ArgumentException($"{nameof(GroveI2cStart)} error: Read length error. Up to {GroveI2cLengthLimit} bytes can be read in a single transaction.");
}
if (arrayToSend.Length > GroveI2cLengthLimit)
{
throw new ArgumentException($"{nameof(GroveI2cStart)} error:Write length error. Up to {GroveI2cLengthLimit} bytes can be written in a single transaction.");
}
byte[] outArray = { SpiAddress, (byte)message_type, (byte)address, inBytes, (byte)arrayToSend.Length };
Array.Resize(ref outArray, outArray.Length + arrayToSend.Length);
Array.Copy(arrayToSend, 0, outArray, outArray.Length - arrayToSend.Length, arrayToSend.Length);
var reply = SpiTransferArray(outArray);
GroveSensor[port_index].I2cDataLength = inBytes;
if (reply[3] != SpiCorrectDataReturned)
{
throw new IOException($"{nameof(GroveI2cStart)} error: No SPI response");
}
if (reply[4] != I2cCorrectData)
{
throw new IOException($"{nameof(GroveI2cStart)} error: Not ready to start I2C transaction");
}
}
/// <summary>
/// Get a grove port value
/// </summary>
/// <param name="port">The Grove Port, one at the time Grove1 or Grove2</param>
/// <returns>Returns a byte array containing the read data</returns>
public byte[] GetGroveValue(GrovePort port)
{
string errorSpi = $"{nameof(GetGroveValue)} error: No SPI response";
string errorInvalidValue = $"{nameof(GetGroveValue)} error: Invalid value";
SpiMessageType message_type;
byte port_index;
if (port == GrovePort.Grove1)
{
message_type = SpiMessageType.GetGrove1Value;
port_index = 0;
}
else if (port == GrovePort.Grove2)
{
message_type = SpiMessageType.GetGrove2Value;
port_index = 1;
}
else
{
throw new ArgumentException($"{nameof(GroveI2cStart)} error: Port unsupported. Must be either Grove 1 or Grove 2.");
}
byte[] outArray = null;
byte[] reply = null;
switch (GroveSensor[port_index].SensorType)
{
case GroveSensorType.InfraredRemote:
outArray = new byte[] { SpiAddress, (byte)message_type, 0, 0, 0, 0, 0 };
reply = SpiTransferArray(outArray);
if (reply[3] == SpiCorrectDataReturned)
{
if ((reply[4] == (byte)GroveSensor[port_index].SensorType) && (reply[5] == I2cCorrectData))
{
return new byte[] { reply[6] };
}
else
{
throw new IOException(errorInvalidValue);
}
}
else
{
throw new IOException(errorSpi);
}
case GroveSensorType.InfraredEV3Remote:
outArray = new byte[] { SpiAddress, (byte)message_type, 0, 0, 0, 0, 0, 0, 0, 0 };
reply = SpiTransferArray(outArray);
if (reply[3] == SpiCorrectDataReturned)
{
if ((reply[4] == (byte)GroveSensor[port_index].SensorType) && (reply[5] == I2cCorrectData))
{
return new byte[] { reply[6], reply[7], reply[8], reply[9] };
}
else
{
throw new IOException(errorInvalidValue);
}
}
else
{
throw new IOException(errorSpi);
}
case GroveSensorType.Ultrasonic:
outArray = new byte[] { SpiAddress, (byte)message_type, 0, 0, 0, 0, 0, 0 };
reply = SpiTransferArray(outArray);
if (reply[3] == SpiCorrectDataReturned)
{
if ((reply[4] == (byte)GroveSensor[port_index].SensorType) && (reply[5] == I2cCorrectData))
{
return new byte[] { reply[6], reply[7] };
}
else
{
throw new IOException(errorInvalidValue);
}
}
else
{
throw new IOException(errorSpi);
}
case GroveSensorType.I2c:
outArray = new byte[6 + GroveSensor[port_index].I2cDataLength];
outArray[0] = SpiAddress;
outArray[1] = (byte)message_type;
// next 4 bytes are 0 then fill with the number of inbytes data
for (int i = 0; i < 4 + GroveSensor[port_index].I2cDataLength; i++)
{
outArray[2 + i] = 0;
}
reply = SpiTransferArray(outArray);
if (reply[3] == SpiCorrectDataReturned)
{
if (reply[4] == (byte)GroveSensor[port_index].SensorType)
{
if (reply[5] == (byte)GroveSensorState.ValidData)
{
return reply.Skip(5).ToArray();
}
else if (reply[5] == (byte)GroveSensorState.I2cError)
{
throw new IOException($"{nameof(GetGroveValue)} error: I2C bus error");
}
else
{
throw new IOException(errorInvalidValue);
}
}
else
{
throw new IOException($"{nameof(GetGroveValue)} error: Grove type mismatch");
}
}
else
{
throw new IOException(errorSpi);
}
case GroveSensorType.None:
case GroveSensorType.Custom:
default:
return new byte[] { (byte)SpiRead8(message_type) };
}
}
/// <summary>
/// Get a grove input pin state
/// </summary>
/// <param name="port">The Grove Pin, one at the time Grove1Pin1, Grove1Pin2, Grove2Pin1 or Grove2Pin2</param>
/// <returns>Returns the pin state</returns>
public byte GetGroveState(GrovePort port)
{
SpiMessageType message_type;
if (port == GrovePort.Grove1Pin1)
{
message_type = SpiMessageType.GetGrove1Pin1State;
}
else if (port == GrovePort.Grove1Pin2)
{
message_type = SpiMessageType.GetGrove1Pin2State;
}
else if (port == GrovePort.Grove2Pin1)
{
message_type = SpiMessageType.GetGrove2Pin1State;
}
else if (port == GrovePort.Grove2Pin2)
{
message_type = SpiMessageType.GetGrove2Pin2State;
}
else
{
throw new ArgumentException($"{nameof(GetGroveState)} error: Pin(s) unsupported. Must get one at a time.");
}
byte[] outArray = { SpiAddress, (byte)message_type, 0, 0, 0, 0 };
var reply = SpiTransferArray(outArray);
if (reply[3] == SpiCorrectDataReturned)
{
if (reply[4] == (byte)GroveSensorState.ValidData)
{
return reply[5];
}
else
{
throw new IOException($"{nameof(GetGroveState)} error: Invalid value");
}
}
else
{
throw new IOException($"{nameof(GetGroveState)} error: Grove type mismatch");
}
}
/// <summary>
/// Get a grove input pin analog voltage
/// </summary>
/// <param name="port">The Grove Pin, one at the time Grove1Pin1, Grove1Pin2, Grove2Pin1 or Grove2Pin2</param>
/// <returns>Returns the voltage in V</returns>
public double GetGroveVoltage(GrovePort port)
{
SpiMessageType message_type;
if (port == GrovePort.Grove1Pin1)
{
message_type = SpiMessageType.GetGrove1Pin1Voltage;
}
else if (port == GrovePort.Grove1Pin2)
{
message_type = SpiMessageType.GetGrove1Pin2Voltage;
}
else if (port == GrovePort.Grove2Pin1)
{
message_type = SpiMessageType.GetGrove2Pin1Voltage;
}
else if (port == GrovePort.Grove2Pin2)
{
message_type = SpiMessageType.GetGrove2Pin2Voltage;
}
else
{
throw new ArgumentException($"{nameof(GetGroveVoltage)} error: Pin(s) unsupported. Must get one at a time.");
}
byte[] outArray = { SpiAddress, (byte)message_type, 0, 0, 0, 0, 0 };
var reply = SpiTransferArray(outArray);
if (reply[3] == SpiCorrectDataReturned)
{
if (reply[4] == (byte)GroveSensorState.ValidData)
{
return ((reply[5] << 8) + reply[6]) / 1000.0;
}
else
{
throw new IOException($"{nameof(GetGroveVoltage)} error: Invalid value");
}
}
else
{
throw new IOException($"{nameof(GetGroveVoltage)} error: Grove type mismatch");
}
}
/// <summary>
/// Get a grove input pin 12-bit raw ADC reading
/// </summary>
/// <param name="port">The Grove Pin, one at the time Grove1Pin1, Grove1Pin2, Grove2Pin1 or Grove2Pin2</param>
/// <returns>Returns the analogic read</returns>
public int GetGroveAnalog(GrovePort port)
{
SpiMessageType message_type;
if (port == GrovePort.Grove1Pin1)
{
message_type = SpiMessageType.GetGrove1Pin1Analog;
}
else if (port == GrovePort.Grove1Pin2)
{
message_type = SpiMessageType.GetGrove1Pin2Analog;
}
else if (port == GrovePort.Grove2Pin1)
{
message_type = SpiMessageType.GetGrove2Pin1Analog;
}
else if (port == GrovePort.Grove2Pin2)
{
message_type = SpiMessageType.GetGrove2Pin2Analog;
}
else
{