-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathSimRacing.cpp
More file actions
1779 lines (1432 loc) · 51 KB
/
SimRacing.cpp
File metadata and controls
1779 lines (1432 loc) · 51 KB
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
/*
* Project Sim Racing Library for Arduino
* @author David Madison
* @link github.com/dmadison/Sim-Racing-Arduino
* @license LGPLv3 - Copyright (c) 2022 David Madison
*
* This file is part of the Sim Racing Library for Arduino.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SimRacing.h"
/**
* @file SimRacing.cpp
* @brief Source file for the Sim Racing Library
*/
namespace SimRacing {
#if defined(__AVR_ATmega32U4__) || defined(SIM_RACING_DOXYGEN)
template<>
LogitechPedals CreateShieldObject<LogitechPedals, 1>() {
// Power (VCC): DE-9 pin 9, bridged to DE-9 pin 6
// Ground (GND): DE-9 pin 1
const PinNum Pin_Gas = A2; // DE-9 pin 2
const PinNum Pin_Brake = A1; // DE-9 pin 3
const PinNum Pin_Clutch = A0; // DE-9 pin 4
const PinNum Pin_Detect = 10; // DE-9 pin 6, requires 10k Ohm pull-down
return LogitechPedals(Pin_Gas, Pin_Brake, Pin_Clutch, Pin_Detect);
}
template<>
LogitechPedals CreateShieldObject<LogitechPedals, 2>() {
// version 2 of the pedals shield has the same pinout,
// so we can use the v1 function
return CreateShieldObject<LogitechPedals, 1>();
}
template<>
LogitechShifter CreateShieldObject<LogitechShifter, 1>() {
// Power (VCC): DE-9 pin 9, bridged to DE-9 pin 7
// Ground (GND): DE-9 pin 6
// DE-9 pin 3 (CS) needs to be pulled-up to VCC
const PinNum Pin_X_Wiper = A1; // DE-9 pin 4
const PinNum Pin_Y_Wiper = A0; // DE-9 pin 8
const PinNum Pin_DataOut = 14; // DE-9 pin 2
const PinNum Pin_Detect = A2; // DE-9 pin 7, requires 10k Ohm pull-down
return LogitechShifter(Pin_X_Wiper, Pin_Y_Wiper, Pin_DataOut, Pin_Detect);
}
template<>
LogitechShifter CreateShieldObject<LogitechShifter, 2>() {
// version 2 of the shifter shield has the same data pinout for
// the Driving Force shifter, so we can use the v1 function
return CreateShieldObject<LogitechShifter, 1>();
}
template<>
LogitechShifterG27 CreateShieldObject<LogitechShifterG27, 2>() {
// Power (VCC): DE-9 pin 9, bridged to DE-9 pin 7
// Ground (GND): DE-9 pin 6
const PinNum Pin_X_Wiper = A1; // DE-9 pin 4
const PinNum Pin_Y_Wiper = A0; // DE-9 pin 8
const PinNum Pin_DataOut = 14; // DE-9 pin 2
const PinNum Pin_Latch = 10; // DE-9 pin 3, aka chip select, requires 10k Ohm pull-up
const PinNum Pin_Clock = 15; // DE-9 pin 1, should have 470 Ohm resistor to prevent shorts
const PinNum Pin_LED = 16; // DE-9 pin 5, has a 100-120 Ohm series resistor
const PinNum Pin_Detect = A2; // DE-9 pin 7, requires 10k Ohm pull-down
return LogitechShifterG27(Pin_X_Wiper, Pin_Y_Wiper, Pin_Latch, Pin_Clock, Pin_DataOut, Pin_LED, Pin_Detect);
}
template<>
LogitechShifterG25 CreateShieldObject<LogitechShifterG25, 2>() {
// Power (VCC): DE-9 pin 9, bridged to DE-9 pin 1
// Ground (GND): DE-9 pin 6
const PinNum Pin_X_Wiper = A1; // DE-9 pin 4
const PinNum Pin_Y_Wiper = A0; // DE-9 pin 8
const PinNum Pin_DataOut = 14; // DE-9 pin 2
const PinNum Pin_Latch = 10; // DE-9 pin 3, aka chip select, requires 10k Ohm pull-up
const PinNum Pin_Clock = A2; // DE-9 pin 7, should have 470 Ohm resistor to prevent shorts
const PinNum Pin_LED = 16; // DE-9 pin 5, has a 100-120 Ohm series resistor
const PinNum Pin_Detect = 15; // DE-9 pin 1, requires 10k Ohm pull-down
return LogitechShifterG25(Pin_X_Wiper, Pin_Y_Wiper, Pin_Latch, Pin_Clock, Pin_DataOut, Pin_LED, Pin_Detect);
}
#endif // ATmega32U4 for shield functions
/**
* Take a pin number as an input and sanitize it to a known working value
*
* In an ideal world this would check against the available pins on the micro,
* but as far as I know the Arduino API does not have a "valid pin" function.
* Instead, we'll just accept any positive number as a pin and reject any
* negative number as invalid ("Unused").
*
* @param pin the pin number to sanitize
* @returns the pin number, or UnusedPin
*/
static constexpr PinNum sanitizePin(PinNum pin) {
return pin < 0 ? UnusedPin : pin;
}
/**
* Invert an input value so it's at the same relative position
* at the other side of an input range.
*
* @param value the value to invert
* @param min the minimum value of the range
* @param max the maximum value of the range
*
* @return the input value, mapped to the other end of the axis
*/
static constexpr long invertAxis(long value, long min, long max) {
return max - value + min; // flip to other side of the scale
}
/**
* Wraps the existing Arduino "map" function to include range checks, so the
* output is never outside the min/max range.
*
* If inMin/inMax are flipped (max less than min), this will adjust the input value
* so its position is relative to the min/max axis. For example, if the min is
* 0 and the max is 100 with an input value of 5, the input value with be set to
* 95 (5 off of max) before being rescaled to the output.
*
* @param value the value to remap to a new range
* @param inMin the minimum range of the input value
* @param inMax the maximum range of the input value
* @param outMin the minimum range of the output value
* @param outMax the maximum range of the output value
*
* @return the remapped value
*/
static long remap(long value, long inMin, long inMax, long outMin, long outMax) {
// if inverted, swap min/max and adjust position of value
if (inMin > inMax) {
const long temp = inMin;
inMin = inMax;
inMax = temp;
value = invertAxis(value, inMin, inMax);
}
if (value <= inMin) return outMin;
if (value >= inMax) return outMax;
return map(value, inMin, inMax, outMin, outMax);
}
/**
* Filters a floating point value to a valid percentile range (0-1)
*
* @param pct the input value
* @return the input value limited to 0-1
*/
static float floatPercent(float pct) {
if (pct < 0.0) pct = 0.0;
else if (pct > 1.0) pct = 1.0;
return pct;
}
/**
* Flushes a Stream of input data until no data is remaining.
*
* This includes a delay() statement so that platforms that require a yield()
* call for the watchdog timer don't freeze up.
*
* @param client the Stream client to flush
*/
static void flushClient(Stream& client) {
while (client.read() != -1) { delay(2); } // 9600 baud = ~1 ms per byte
}
/**
* Waits until new data is avaiable on a given Stream interface.
*
* @param client the Stream client to read from
*/
static void waitClient(Stream& client) {
flushClient(client);
while (client.peek() == -1) { delay(1); } // wait for a new byte (using delay to avoid watchdog)
}
/**
* Read a floating point percentage value from a given Stream interface.
*
* The user can skip setting a floating point value by sending the character
* 'n' when prompted. If 'n' is received the value is left unchanged.
*
* Note that this does *not* handle non-numeric strings. If a non-numeric string
* is sent the parseFloat() function will time out and default to "0.0".
*
* @param value the floating point input, passed by reference
* @param client the Stream client to read from and write messages to
*/
static void readFloat(float& value, Stream& client) {
client.print("(to skip this step and go with the default value of '");
client.print(value);
client.print("', send 'n')");
client.println();
waitClient(client);
if (client.peek() == 'n') return; // skip this step
float input;
while (true) {
client.setTimeout(200);
input = client.parseFloat();
if (input >= 0.0 && input <= 1.0) {
client.print(F("Set the new value to '"));
client.print(input);
client.println("'");
break;
}
client.print(F("Input '"));
client.print(input);
client.print(F("' not within acceptable range (0.0 - 1.0). Please try again."));
client.println();
waitClient(client);
}
value = input;
}
//#########################################################
// DeviceConnection #
//#########################################################
DeviceConnection::DeviceConnection(PinNum pin, bool activeLow, unsigned long detectTime)
:
pin(sanitizePin(pin)), inverted(activeLow), stablePeriod(detectTime), // constants(ish)
/* Assume we're connected on first call
*/
state(ConnectionState::Connected),
/* Init state to "not inverted", which is the connected state. For example
* if we're looking for 'HIGH' then inverted is false, which means the
* initial state is 'true' and thus connected.
*
* We're assuming we're connected on first call here because it allows
* the device to be read as connected as soon as the board turns on, without
* having to wait an arbitrary amount.
*/
pinState(!inverted),
/* Set the last pin change to right now minus the stable period so it's
* read as being already stable. Again, this will make the class return
* 'present' as soon as the board starts up
*/
lastChange(millis() - detectTime)
{
if (pin != UnusedPin) {
pinMode(pin, INPUT); // set pin as input, *no* pull-up
}
}
void DeviceConnection::poll() {
const bool newState = readPin();
if (newState == HIGH && state == ConnectionState::Connected) return; // short circuit, already connected
// check if the pin changed. if it did, record the time
if (pinState != newState) {
pinState = newState;
lastChange = millis();
// rising, we just connected
if (pinState == HIGH) {
state = ConnectionState::PlugIn;
}
// falling, we just disconnected
else {
state = ConnectionState::Unplug;
}
}
// if pin hasn't changed, compare stable times
else {
// check stable connection (over time)
if (pinState == HIGH) {
const unsigned long now = millis();
if (now - lastChange >= stablePeriod) {
state = ConnectionState::Connected;
}
}
// if we were previously unplugged and are still low, now we're disconnected
else if (state == ConnectionState::Unplug) {
state = ConnectionState::Disconnected;
}
}
}
DeviceConnection::ConnectionState DeviceConnection::getState() const {
return state;
}
bool DeviceConnection::isConnected() const {
return this->getState() == ConnectionState::Connected;
}
void DeviceConnection::setStablePeriod(unsigned long t) {
stablePeriod = t;
if (state == ConnectionState::Connected) {
const unsigned long now = millis();
// if we were previously considered connected, adjust the timestamps
// accordingly so that we still are
if (now - lastChange < stablePeriod) {
lastChange = now - stablePeriod;
}
}
}
bool DeviceConnection::readPin() const {
if (pin == UnusedPin) return HIGH; // if no pin is set, we're always connected
const bool state = digitalRead(pin);
return inverted ? !state : state;
}
//#########################################################
// AnalogInput #
//#########################################################
AnalogInput::AnalogInput(PinNum pin)
: pin(sanitizePin(pin)), position(AnalogInput::Min), cal({AnalogInput::Min, AnalogInput::Max})
{
if (pin != UnusedPin) {
pinMode(pin, INPUT);
}
}
bool AnalogInput::read() {
bool changed = false;
if (pin != UnusedPin) {
const int previous = this->position;
this->position = analogRead(pin);
// check if value is different for 'changed' flag
if (previous != this->position) {
const int rMin = isInverted() ? getMax() : getMin();
const int rMax = isInverted() ? getMin() : getMax();
if (
// if the previous value was under the minimum range
// and the current value is as well, no change
!(previous < rMin && this->position < rMin) &&
// if the previous value was over the maximum range
// and the current value is as well, no change
!(previous > rMax && this->position > rMax)
)
{
// otherwise, the current value is either within the
// range limits *or* it has changed from one extreme
// to the other. Either way, mark it changed!
changed = true;
}
}
}
return changed;
}
long AnalogInput::getPosition(long rMin, long rMax) const {
// inversion is handled within the remap function
return remap(getPositionRaw(), getMin(), getMax(), rMin, rMax);
}
int AnalogInput::getPositionRaw() const {
return this->position;
}
bool AnalogInput::isInverted() const {
return (this->cal.min > this->cal.max); // inverted if min is greater than max
}
void AnalogInput::setPosition(int newPos) {
this->position = newPos;
}
void AnalogInput::setInverted(bool invert) {
if (isInverted() == invert) return; // inversion already set
// to change inversion, swap max and min of the current calibration
AnalogInput::Calibration inverted = { this->cal.max, this->cal.min };
setCalibration(inverted);
}
void AnalogInput::setCalibration(AnalogInput::Calibration newCal) {
this->cal = newCal;
}
//#########################################################
// Peripheral #
//#########################################################
bool Peripheral::update() {
// if the detector exists, poll for state
if (this->detector) {
this->detector->poll();
}
// get the connected state from the detector
const bool connected = this->isConnected();
// call the derived class update function
return this->updateState(connected);
}
bool Peripheral::isConnected() const {
// if detector exists, return state
if (this->detector) {
return this->detector->isConnected();
}
// otherwise, assume always connected
return true;
}
void Peripheral::setDetectPtr(DeviceConnection* d) {
this->detector = d;
}
void Peripheral::setStablePeriod(unsigned long t) {
// if detector exists, set the stable period
if (this->detector) {
this->detector->setStablePeriod(t);
}
}
//#########################################################
// Pedals #
//#########################################################
Pedals::Pedals(AnalogInput* dataPtr, uint8_t nPedals)
:
pedalData(dataPtr),
NumPedals(nPedals),
changed(false)
{}
void Pedals::begin() {
update(); // set initial pedal position
}
bool Pedals::updateState(bool connected) {
this->changed = false;
// if we're connected, read all pedal positions
if (connected) {
for (int i = 0; i < getNumPedals(); ++i) {
changed |= pedalData[i].read();
}
}
// otherwise, zero all pedals
else {
for (int i = 0; i < getNumPedals(); ++i) {
const int min = pedalData[i].getMin();
const int prev = pedalData[i].getPositionRaw();
if (min != prev) {
pedalData[i].setPosition(min);
changed = true;
}
}
}
return this->changed;
}
long Pedals::getPosition(PedalID pedal, long rMin, long rMax) const {
if (!hasPedal(pedal)) return rMin; // not a pedal
return pedalData[pedal].getPosition(rMin, rMax);
}
int Pedals::getPositionRaw(PedalID pedal) const {
if (!hasPedal(pedal)) return AnalogInput::Min; // not a pedal
return pedalData[pedal].getPositionRaw();
}
bool Pedals::hasPedal(PedalID pedal) const {
return (pedal < getNumPedals());
}
void Pedals::setCalibration(PedalID pedal, AnalogInput::Calibration cal) {
if (!hasPedal(pedal)) return;
pedalData[pedal].setCalibration(cal);
pedalData[pedal].setPosition(pedalData[pedal].getMin()); // reset to min position
}
String Pedals::getPedalName(PedalID pedal) {
String name;
switch (pedal) {
case(PedalID::Gas):
name = F("gas");
break;
case(PedalID::Brake):
name = F("brake");
break;
case(PedalID::Clutch):
name = F("clutch");
break;
default:
name = F("???");
break;
}
return name;
}
void Pedals::serialCalibration(Stream& iface) {
const char* separator = "------------------------------------";
iface.println();
iface.println(F("Sim Racing Library Pedal Calibration"));
iface.println(separator);
iface.println();
// read minimums
iface.println(F("Take your feet off of the pedals so they move to their resting position."));
iface.println(F("Send any character to continue."));
waitClient(iface);
const int MaxPedals = 3; // hard-coded at 3 pedals
AnalogInput::Calibration pedalCal[MaxPedals];
// read minimums
for (int i = 0; (i < getNumPedals()) && (i < MaxPedals); i++) {
pedalData[i].read(); // read position
pedalCal[i].min = pedalData[i].getPositionRaw(); // set min to the recorded position
}
iface.println(F("\nMinimum values for all pedals successfully recorded!\n"));
iface.println(separator);
// read maximums
iface.println(F("\nOne at a time, let's measure the maximum range of each pedal.\n"));
for (int i = 0; (i < getNumPedals()) && (i < MaxPedals); i++) {
iface.print(F("Push the "));
String name = getPedalName(static_cast<PedalID>(i));
name.toLowerCase();
iface.print(name);
iface.print(F(" pedal to the floor. "));
iface.println(F("Send any character to continue."));
waitClient(iface);
pedalData[i].read(); // read position
pedalCal[i].max = pedalData[i].getPositionRaw(); // set max to the recorded position
}
// deadzone options
iface.println(separator);
iface.println();
float DeadzoneMin = 0.01; // by default, 1% (trying to keep things responsive)
float DeadzoneMax = 0.025; // by default, 2.5%
iface.println(F("These settings are optional. Send 'y' to customize. Send any other character to continue with the default values."));
iface.print(F(" * Pedal Travel Deadzone, Start: \t"));
iface.print(DeadzoneMin);
iface.println(F(" (Used to avoid the pedal always being slightly pressed)"));
iface.print(F(" * Pedal Travel Deadzone, End: \t"));
iface.print(DeadzoneMax);
iface.println(F(" (Used to guarantee that the pedal can be fully pressed)"));
iface.println();
waitClient(iface);
if (iface.read() == 'y') {
iface.println(F("Set the pedal travel starting deadzone as a floating point percentage."));
readFloat(DeadzoneMin, iface);
iface.println();
iface.println(F("Set the pedal travel ending deadzone as a floating point percentage."));
readFloat(DeadzoneMax, iface);
iface.println();
}
flushClient(iface);
// calculate deadzone offsets
for (int i = 0; (i < getNumPedals()) && (i < MaxPedals); i++) {
auto &cMin = pedalCal[i].min;
auto &cMax = pedalCal[i].max;
const int range = abs(cMax - cMin);
const int dzMin = DeadzoneMin * (float)range;
const int dzMax = DeadzoneMax * (float)range;
// non-inverted
if (cMax >= cMin) {
cMax -= dzMax; // 'cut' into the range so it limits sooner
cMin += dzMin;
}
// inverted
else {
cMax += dzMax;
cMin -= dzMin;
}
}
// print finished calibration
iface.println(F("Here is your calibration:"));
iface.println(separator);
iface.println();
iface.print(F("pedals.setCalibration("));
for (int i = 0; (i < getNumPedals()) && (i < MaxPedals); i++) {
if(i > 0) iface.print(F(", "));
iface.print('{');
iface.print(pedalCal[i].min);
iface.print(F(", "));
iface.print(pedalCal[i].max);
iface.print('}');
this->setCalibration(static_cast<PedalID>(i), pedalCal[i]); // and set it ourselves, too
}
iface.print(");");
iface.println();
iface.println();
iface.println(separator);
iface.println();
iface.print(F("Paste this line into the setup() function. The "));
iface.print(F("pedals"));
iface.print(F(" will be calibrated with these values on startup."));
iface.println(F("\nCalibration complete! :)\n\n"));
flushClient(iface);
}
TwoPedals::TwoPedals(PinNum gasPin, PinNum brakePin)
: Pedals(pedalData, NumPedals),
pedalData{ AnalogInput(gasPin), AnalogInput(brakePin) }
{}
void TwoPedals::setCalibration(AnalogInput::Calibration gasCal, AnalogInput::Calibration brakeCal) {
this->Pedals::setCalibration(PedalID::Gas, gasCal);
this->Pedals::setCalibration(PedalID::Brake, brakeCal);
}
ThreePedals::ThreePedals(PinNum gasPin, PinNum brakePin, PinNum clutchPin)
: Pedals(pedalData, NumPedals),
pedalData{ AnalogInput(gasPin), AnalogInput(brakePin), AnalogInput(clutchPin) }
{}
void ThreePedals::setCalibration(AnalogInput::Calibration gasCal, AnalogInput::Calibration brakeCal, AnalogInput::Calibration clutchCal) {
this->Pedals::setCalibration(PedalID::Gas, gasCal);
this->Pedals::setCalibration(PedalID::Brake, brakeCal);
this->Pedals::setCalibration(PedalID::Clutch, clutchCal);
}
LogitechPedals::LogitechPedals(PinNum gasPin, PinNum brakePin, PinNum clutchPin, PinNum detectPin)
:
ThreePedals(gasPin, brakePin, clutchPin),
detectObj(detectPin, false) // active high
{
this->setDetectPtr(&this->detectObj);
// taken from calibrating my own pedals. the springs are pretty stiff so while
// this covers the whole travel range, users may want to back it down for casual
// use (esp. for the brake travel)
this->setCalibration({ 904, 48 }, { 944, 286 }, { 881, 59 });
}
LogitechDrivingForceGT_Pedals::LogitechDrivingForceGT_Pedals(PinNum gasPin, PinNum brakePin, PinNum detectPin)
:
TwoPedals(gasPin, brakePin),
detectObj(detectPin, false) // active high
{
this->setDetectPtr(&this->detectObj);
this->setCalibration({ 646, 0 }, { 473, 1023 }); // taken from calibrating my own pedals
}
//#########################################################
// Shifter #
//#########################################################
Shifter::Shifter(Gear min, Gear max)
:
MinGear(min), MaxGear(max)
{
this->currentGear = this->previousGear = 0; // neutral
}
void Shifter::setGear(Gear gear) {
// if gear is out of range, set it to neutral
if (gear < MinGear || gear > MaxGear) {
gear = 0;
}
this->previousGear = this->currentGear;
this->currentGear = gear;
}
char Shifter::getGearChar(int gear) {
char c = '?';
switch (gear) {
case(-1):
c = 'r';
break;
case(0):
c = 'n';
break;
default:
if (gear > 0 && gear <= 9)
c = '0' + gear;
break;
}
return c;
}
char Shifter::getGearChar() const {
return getGearChar(getGear());
}
String Shifter::getGearString(int gear) {
String name;
switch (gear) {
case(-1):
name = F("reverse");
break;
case(0):
name = F("neutral");
break;
default: {
if (gear < 0 || gear > 9) {
name = F("???");
break; // out of range
}
name = gear; // set string to current gear
switch (gear) {
case(1):
name += F("st");
break;
case(2):
name += F("nd");
break;
case(3):
name += F("rd");
break;
default:
name += F("th");
break;
}
break;
}
}
return name;
}
String Shifter::getGearString() const {
return getGearString(getGear());
}
/* Static calibration constants
* These values are arbitrary - just what worked well with my own shifter.
*/
const float AnalogShifter::CalEngagementPoint = 0.70;
const float AnalogShifter::CalReleasePoint = 0.50;
const float AnalogShifter::CalEdgeOffset = 0.60;
AnalogShifter::AnalogShifter(
Gear gearMin, Gear gearMax,
PinNum pinX, PinNum pinY, PinNum pinRev
) :
Shifter(gearMin, gearMax),
/* Two axes, X and Y */
analogAxis{ AnalogInput(pinX), AnalogInput(pinY) },
pinReverse(sanitizePin(pinRev)),
reverseState(false)
{}
void AnalogShifter::begin() {
if (this->pinReverse != UnusedPin) {
pinMode(pinReverse, INPUT);
}
update(); // set initial gear position
}
bool AnalogShifter::updateState(bool connected) {
// if not connected, reset our position back to neutral
// and immediately return
if (!connected) {
// set axis values to calibrated neutral
analogAxis[Axis::X].setPosition(calibration.neutralX);
analogAxis[Axis::Y].setPosition(calibration.neutralY);
// set reverse state to unpressed
this->reverseState = false;
// set gear to neutral
this->setGear(0);
// status changed if gear changed
return this->gearChanged();
}
// poll the analog axes for new data
analogAxis[Axis::X].read();
analogAxis[Axis::Y].read();
const int x = analogAxis[Axis::X].getPosition();
const int y = analogAxis[Axis::Y].getPosition();
// poll the reverse button and cache in the class
this->reverseState = this->readReverseButton();
// check previous gears for comparison
const Gear previousGear = this->getGear();
const bool prevOdd = ((previousGear != -1) && (previousGear & 1)); // were we previously in an odd gear
const bool prevEven = (!prevOdd && previousGear != 0); // were we previously in an even gear
Gear newGear = 0;
// If we're below the 'release' thresholds, we must still be in the previous gear
if ((prevOdd && y > calibration.oddRelease) || (prevEven && y < calibration.evenRelease)) {
newGear = previousGear;
}
// If we're *not* below the release thresholds, we may be in a different gear
else {
// Check if we're in even or odd gears (Y axis)
if (y > calibration.oddTrigger) {
newGear = 1; // we're in an odd gear
}
else if (y < calibration.evenTrigger) {
newGear = 2; // we're in an even gear
}
if (newGear != 0) {
// Now check *which* gear we're in, if we're in one (X axis)
if (x > calibration.rightEdge) newGear += 4; // 1-2 + 4 = 5-6
else if (x >= calibration.leftEdge) newGear += 2; // 1-2 + 2 = 3-4
// (note the '>=', because it would normally be a '<' check for the lower range)
// else gear = 1-2 (as set above)
const bool reverse = getReverseButton();
// If the reverse button is pressed and we're in 5th gear
// something is wrong. Revert that and go back to neutral.
if (reverse && newGear == 5) {
newGear = 0;
}
// If the reverse button is pressed or we were previously
// in reverse *and* we are currently in 6th gear, then we
// should be in reverse.
else if ((reverse || previousGear == -1) && newGear == 6) {
newGear = -1;
}
}
}
// finally, store the newly calculated gear
this->setGear(newGear);
return this->gearChanged();
}
long AnalogShifter::getPosition(Axis ax, long min, long max) const {
if (ax != Axis::X && ax != Axis::Y) return min; // not an axis
return analogAxis[ax].getPosition(min, max);
}
int AnalogShifter::getPositionRaw(Axis ax) const {
if (ax != Axis::X && ax != Axis::Y) return AnalogInput::Min; // not an axis
return analogAxis[ax].getPositionRaw();
}
bool AnalogShifter::readReverseButton() {
// if the reverse pin is not set, avoid reading the
// floating input and just return 'false'
if (pinReverse == UnusedPin) {
return false;
}
return digitalRead(pinReverse);
}
bool AnalogShifter::getReverseButton() const {
// return the cached reverse state from updateState(bool)
// do NOT poll the button!
return this->reverseState;
}
void AnalogShifter::setCalibration(
GearPosition neutral,
GearPosition g1, GearPosition g2, GearPosition g3, GearPosition g4, GearPosition g5, GearPosition g6,
float engagePoint, float releasePoint, float edgeOffset) {
// limit percentage thresholds
engagePoint = floatPercent(engagePoint);
releasePoint = floatPercent(releasePoint);
edgeOffset = floatPercent(edgeOffset);
const int xLeft = (g1.x + g2.x) / 2; // find the minimum X position average
const int xRight = (g5.x + g6.x) / 2; // find the maximum X position average
const int yOdd = (g1.y + g3.y + g5.y) / 3; // find the maximum Y position average
const int yEven = (g2.y + g4.y + g6.y) / 3; // find the minimum Y position average
// set X/Y calibration and inversion
analogAxis[Axis::X].setCalibration({ xLeft, xRight });
analogAxis[Axis::Y].setCalibration({ yEven, yOdd });
// save neutral values (raw)
calibration.neutralX = neutral.x;
calibration.neutralY = neutral.y;
// get normalized and inverted neutral values
// this lets us take advantage of the AnalogInput normalization function
// that handles inverted axes and automatic range rescaling, so the rest of
// the calibration options can be in the normalized range
const Axis axes[2] = { Axis::X, Axis::Y };
int* const neutralAxis[2] = { &neutral.x, &neutral.y };
for (int i = 0; i < 2; i++) {
const int previous = analogAxis[axes[i]].getPositionRaw(); // save current value
analogAxis[axes[i]].setPosition(*neutralAxis[i]); // set new value to neutral calibration
*neutralAxis[i] = analogAxis[axes[i]].getPosition(); // get normalized neutral value
analogAxis[axes[i]].setPosition(previous); // reset axis position to previous
}
// calculate the distances between each neutral and the limits of each axis
const int yOddDiff = AnalogInput::Max - neutral.y;
const int yEvenDiff = neutral.y - AnalogInput::Min;
const int leftDiff = neutral.x - AnalogInput::Min;
const int rightDiff = AnalogInput::Max - neutral.x;
// calculate and save the trigger and release points for each level
calibration.oddTrigger = neutral.y + ((float)yOddDiff * engagePoint);
calibration.oddRelease = neutral.y + ((float)yOddDiff * releasePoint);
calibration.evenTrigger = neutral.y - ((float)yEvenDiff * engagePoint);
calibration.evenRelease = neutral.y - ((float)yEvenDiff * releasePoint);
calibration.leftEdge = neutral.x - ((float)leftDiff * edgeOffset);
calibration.rightEdge = neutral.x + ((float)rightDiff * edgeOffset);
#if 0
Serial.print("Odd Trigger: ");
Serial.println(calibration.oddTrigger);
Serial.print("Odd Release: ");
Serial.println(calibration.oddRelease);
Serial.print("Even Trigger: ");
Serial.println(calibration.evenTrigger);