forked from TheDIYGuy999/Rc_Engine_Sound_ESP32
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRc_Engine_Sound_ESP32.ino
3240 lines (2705 loc) · 127 KB
/
Rc_Engine_Sound_ESP32.ino
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
/* RC engine sound & LED controller for Arduino ESP32. Written by TheDIYGuy999
Based on the code for ATmega 328: https://github.com/TheDIYGuy999/Rc_Engine_Sound
* ***** ESP32 CPU frequency must be set to 240MHz! *****
ESP32 macOS Big Sur fix see: https://github.com/TheDIYGuy999/Rc_Engine_Sound_ESP32/blob/master/BigSurFix.md
Sound files converted with: https://github.com/TheDIYGuy999/Rc_Engine_Sound_ESP32/blob/master/Audio2Header.html
Original converter code by bitluni (send him a high five, if you like the code)
Parts of automatic transmision code from Wombii's fork: https://github.com/Wombii/Rc_Engine_Sound_ESP32
Dashboard, Neopixel and SUMD support by: https://github.com/Gamadril/Rc_Engine_Sound_ESP32
*/
const float codeVersion = 7.7; // Software revision.
//
// =======================================================================================================
// ERROR CODES (INDICATOR LIGHTS)
// =======================================================================================================
//
/* Constantly on = no SBUS signal (check "sbusInverted" true / false in "2_adjustmentsRemote.h")
Number of blinks = this channel signal is not between 1400 and 1600 microseconds and can't be auto calibrated
(check channel trim settings)
*/
//
// =======================================================================================================
// ! ! I M P O R T A N T ! ! ALL USER SETTINGS ARE DONE IN THE FOLLOWING TABS, WHICH ARE DISPLAYED ABOVE
// (ADJUST THEM BEFORE CODE UPLOAD), DO NOT CHANGE ANYTHING IN THIS TAB EXCEPT THE DEBUG OPTIONS
// =======================================================================================================
//
// All the required user settings are done in the following .h files:
#include "1_adjustmentsVehicle.h" // <<------- Select the vehicle you want to simulate
#include "2_adjustmentsRemote.h" // <<------- Remote control system related adjustments
#include "3_adjustmentsESC.h" // <<------- ESC related adjustments
#include "4_adjustmentsTransmission.h" // <<------- Transmission related adjustments
#include "5_adjustmentsShaker.h" // <<------- Shaker related adjustments
#include "6_adjustmentsLights.h" // <<------- Lights related adjustments
#include "7_adjustmentsServos.h" // <<------- Servo output related adjustments
#include "8_adjustmentsSound.h" // <<------- Sound related adjustments
#include "9_adjustmentsDashboard.h" // <<------- Dashboard related adjustments
// DEBUG options can slow down the playback loop! Only uncomment them for debugging, may slow down your system!
//#define CHANNEL_DEBUG // uncomment it for input signal debugging informations
//#define ESC_DEBUG // uncomment it to debug the ESC
//#define AUTO_TRANS_DEBUG // uncomment it to debug the automatic transmission
//#define MANUAL_TRANS_DEBUG // uncomment it to debug the manual transmission
//#define TRACKED_DEBUG // debugging tracked vehicle mode
//#define SERVO_DEBUG // uncomment it for servo calibration in BUS communication mode
// TODO = Things to clean up!
//
// =======================================================================================================
// LIRBARIES & HEADER FILES, REQUIRED ESP32 BOARD DEFINITION
// =======================================================================================================
//
// Header files
#include "headers/curves.h" // Nonlinear throttle curve arrays
// Libraries (you have to install all of them in the "Arduino sketchbook"/libraries folder)
// !! Do NOT install the libraries in the sketch folder.
#include <statusLED.h> // https://github.com/TheDIYGuy999/statusLED <<------- required for LED control
#include <SBUS.h> // https://github.com/TheDIYGuy999/SBUS <<------- you need to install my fork of this library!
#include <rcTrigger.h> // https://github.com/TheDIYGuy999/rcTrigger <<------- required for RC signal processing
#include <IBusBM.h> // https://github.com/bmellink/IBusBM <<------- required for IBUS interface
#include <TFT_eSPI.h> // https://github.com/Bodmer/TFT_eSPI <<------- required for LCD dashboard
#include <FastLED.h> // https://github.com/FastLED/FastLED <<------- required for Neopixel support
// Plugins (included, but not programmed by TheDIYGuy999)
#include "src/dashboard.h" // For LCD dashboard. See: https://github.com/Gamadril/Rc_Engine_Sound_ESP32
#include "src/SUMD.h" // For Graupner SUMD interface. See: https://github.com/Gamadril/Rc_Engine_Sound_ESP32
// No need to install these, they come with the ESP32 board definition
#include "driver/rmt.h" // for PWM signal detection
#include "driver/mcpwm.h" // for servo PWM output
// Install ESP32 board according to: https://randomnerdtutorials.com/installing-the-esp32-board-in-arduino-ide-windows-instructions/
// Warning: do not use Espressif ESP32 board definition v1.05, its causing crash & reboot loops! Use v1.04 instead.
// Adjust board settings according to: https://github.com/TheDIYGuy999/Rc_Engine_Sound_ESP32/blob/master/pictures/settings.png
// Make sure to remove -master from your sketch folder name
//
// =======================================================================================================
// PIN ASSIGNMENTS & GLOBAL VARIABLES (Do not play around here)
// =======================================================================================================
//
// Pin assignment and wiring instructions ****************************************************************
// ------------------------------------------------------------------------------------
// Use a 330Ohm resistor in series with all I/O pins! allows to drive LED directly and
// provides short circuit protection. Also works on the serial Rx pin "VP" (36)
// ------------------------------------------------------------------------------------
// Serial command pins for SBUS & IBUS -----
#define COMMAND_RX 36 // pin 36, labelled with "VP", connect it to "Micro RC Receiver" pin "TXO"
#define COMMAND_TX 39 // pin 39, labelled with "VN", only used as a dummy, not connected
// PPM signal pin (multiple channel input with only one wire) -----
#define PPM_PIN 36
// PWM RC signal pins (active, if no other communications profile is enabled) -----
// Channel numbers may be different on your recveiver!
//CH1: (steering)
//CH2: (gearbox) (left throttle in TRACKED_MODE)
//CH3: (throttle) (right throttle in TRACKED_MODE)
//CH4: (horn and bluelight / siren)
//CH5: (high / low beam, transmission neutral, jake brake etc.)
//CH6: (indicators, hazards)
#define PWM_CHANNELS_NUM 6 // Number of PWM signal input pins
const uint8_t PWM_CHANNELS[PWM_CHANNELS_NUM] = { 1, 2, 3, 4, 5, 6}; // Channel numbers
const uint8_t PWM_PINS[PWM_CHANNELS_NUM] = { 13, 12, 14, 27, 35, 34 }; // Input pin numbers
#define ESC_OUT_PIN 33 // connect crawler type ESC here (working fine, but use it at your own risk! Not supported in TRACKED_MODE) -----
#define STEERING_PIN 13 // CH1 output for steering servo (bus communication only)
#define SHIFTING_PIN 12 // CH2 output for shifting servo (bus communication only)
#define WINCH_PIN 14 // CH3 output for winch servo (bus communication only)
#define COUPLER_PIN 27 // CH4 output for coupler (5th. wheel) servo (bus communication only)
#ifdef PROTOTYPE_36 // switching headlight pin depending on the board variant (do not uncomment it, or it will cause boot issues!)
#define HEADLIGHT_PIN 0 // White headllights connected to pin D0, which only exists on the 36 pin ESP32 board (causes boot issues, if used!)
#else
#define HEADLIGHT_PIN 3 // 3 = RX0 pin, (1 = TX0 is not usable) white headllights
#endif
#define TAILLIGHT_PIN 15 // Red tail- & brake-lights (combined)
#define INDICATOR_LEFT_PIN 2 // Orange left indicator (turn signal) light
#define INDICATOR_RIGHT_PIN 4 // Orange right indicator (turn signal) light
#define FOGLIGHT_PIN 16 // (16 = RX2) Fog lights
#define REVERSING_LIGHT_PIN 17 // (TX2) White reversing light
#define ROOFLIGHT_PIN 5 // Roof lights (high beam, if "define SEPARATE_FULL_BEAM")
#define SIDELIGHT_PIN 18 // Side lights (connect roof ligthts here, if "define SEPARATE_FULL_BEAM")
#define BEACON_LIGHT2_PIN 19 // Blue beacons light
#define BEACON_LIGHT1_PIN 21 // Blue beacons light
#define CABLIGHT_PIN 22 // Cabin lights
#define RGB_LEDS_PIN 0 // Pin is used for WS2812 LED control
#if defined THIRD_BRAKLELIGHT
#define BRAKELIGHT_PIN 32 // Upper brake lights
#else
#define COUPLER_SWITCH_PIN 32 // switch for trailer coupler sound
#endif
#define SHAKER_MOTOR_PIN 23 // Shaker motor (shaking truck while idling and engine start / stop)
#define DAC1 25 // connect pin25 (do not change the pin) to a 10kOhm resistor
#define DAC2 26 // connect pin26 (do not change the pin) to a 10kOhm resistor
// both outputs of the resistors above are connected together and then to the outer leg of a
// 10kOhm potentiometer. The other outer leg connects to GND. The middle leg connects to both inputs
// of a PAM8403 amplifier and allows to adjust the volume. This way, two speakers can be used.
// Objects *************************************************************************************
// Status LED objects (also used for PWM shaker motor and ESC control) -----
statusLED headLight(false); // "false" = output not inversed
statusLED tailLight(false);
statusLED indicatorL(false);
statusLED indicatorR(false);
statusLED fogLight(false);
statusLED reversingLight(false);
statusLED roofLight(false);
statusLED sideLight(false);
statusLED beaconLight1(false);
statusLED beaconLight2(false);
statusLED shakerMotor(false);
statusLED cabLight(false);
statusLED brakeLight(false);
statusLED escOut(false);
// rcTrigger objects -----
// Analog or 3 position switches (short / long pressed time)
rcTrigger functionR100u(200); // 200ms required!
rcTrigger functionR100d(100);
rcTrigger functionR75u(300); // 300ms required!
rcTrigger functionR75d(300); // 300ms required!
rcTrigger functionL100l(100);
rcTrigger functionL100r(100);
rcTrigger functionL75l(300); // 300ms required!
rcTrigger functionL75r(300); // 300ms required!
// Latching 2 position
rcTrigger mode1Trigger(100);
rcTrigger mode2Trigger(100);
// momentary buttons
rcTrigger momentary1Trigger(100);
// Flags
rcTrigger hazardsTrigger(100);
rcTrigger indicatorLTrigger(100);
rcTrigger indicatorRTrigger(100);
// Dashboard
Dashboard dashboard;
// Neopixel
#define RGB_LEDS_COUNT 1
CRGB rgbLEDs[RGB_LEDS_COUNT];
// Global variables **********************************************************************
// PWM processing variables
#define RMT_TICK_PER_US 1
// determines how many clock cycles one "tick" is
// [1..255], source is generally 80MHz APB clk
#define RMT_RX_CLK_DIV (80000000/RMT_TICK_PER_US/1000000)
// time before receiver goes idle (longer pulses will be ignored)
#define RMT_RX_MAX_US 3500
uint32_t maxPwmRpmPercentage = 380; // Limit required to prevent controller from crashing @ high engine RPM
// PPM signal processing variables
#define NUM_OF_PPM_CHL 8 // The number of channels inside our PPM signal (8 is the maximum!)
#define NUM_OF_PPM_AVG 1 // Number of averaging passes (usually one, more will be slow)
volatile int ppmInp[NUM_OF_PPM_CHL + 1] = {0}; // Input values
volatile int ppmBuf[16] = {0}; // Buffered values TODO, was [NUM_OF_PPM_CHL + 1]
volatile byte counter = NUM_OF_PPM_CHL;
volatile byte average = NUM_OF_PPM_AVG;
volatile boolean ready = false;
volatile unsigned long timelast;
unsigned long timelastloop;
uint32_t maxPpmRpmPercentage = 390; // Limit required to prevent controller from crashing @ high engine RPM
// SBUS signal processing variables
SBUS sBus(Serial2); // SBUS object on Serial 2 port
// channel, fail safe, and lost frames data
uint16_t SBUSchannels[16];
bool SBUSfailSafe;
bool SBUSlostFrame;
bool sbusInit;
uint32_t maxSbusRpmPercentage = 390; // Limit required to prevent controller from crashing @ high engine RPM
// SUMD signal processing variables
HardwareSerial serial(2);
SUMD sumd(serial); // SUMD object on Serial 2 port
// channel, fail safe, and lost frames data
uint16_t SUMDchannels[16]; // only 12 are usable!
bool SUMD_failsafe;
bool SUMD_frame_lost;
bool SUMD_init;
uint32_t maxSumdRpmPercentage = 390; // Limit required to prevent controller from crashing @ high engine RPM
// IBUS signal processing variables
IBusBM iBus; // IBUS object
bool ibusInit;
uint32_t maxIbusRpmPercentage = 340; // Limit required to prevent controller from crashing @ high engine RPM (was 350, but sometimes crashing)
// Interrupt latches
volatile boolean couplerSwitchInteruptLatch; // this is enabled, if the coupler switch pin change interrupt is detected
// Control input signals
#define PULSE_ARRAY_SIZE 14 // 13 channels (+ the unused CH0)
uint16_t pulseWidthRaw[PULSE_ARRAY_SIZE]; // Current RC signal RAW pulse width [X] = channel number
uint16_t pulseWidthRaw2[PULSE_ARRAY_SIZE]; // Current RC signal RAW pulse width with linearity compensation [X] = channel number
uint16_t pulseWidth[PULSE_ARRAY_SIZE]; // Current RC signal pulse width [X] = channel number
int16_t pulseOffset[PULSE_ARRAY_SIZE]; // Offset for auto zero adjustment
uint16_t pulseMaxNeutral[PULSE_ARRAY_SIZE]; // PWM input signal configuration storage variables
uint16_t pulseMinNeutral[PULSE_ARRAY_SIZE];
uint16_t pulseMax[PULSE_ARRAY_SIZE];
uint16_t pulseMin[PULSE_ARRAY_SIZE];
uint16_t pulseMaxLimit[PULSE_ARRAY_SIZE];
uint16_t pulseMinLimit[PULSE_ARRAY_SIZE];
uint16_t pulseZero[PULSE_ARRAY_SIZE]; // Usually 1500 (The mid point of 1000 - 2000 Microseconds)
uint16_t pulseLimit = 1100; // pulseZero +/- this value (1100)
uint16_t pulseMinValid = 700; // The minimum valid pulsewidth (was 950)
uint16_t pulseMaxValid = 2300; // The maximum valid pulsewidth (was 2050)
bool autoZeroDone; // Auto zero offset calibration done
#define NONE 16 // The non existing "Dummy" channel number (usually 16) TODO
volatile boolean failSafe = false; // Triggered in emergency situations like: throttle signal lost etc.
boolean mode1; // Signal state variables
boolean mode2;
boolean momentary1;
boolean hazard;
boolean left;
boolean right;
boolean unlock5thWheel;
boolean winchPull;
boolean winchRelease;
boolean winchEnabled;
// Sound
volatile boolean engineOn = false; // Signal for engine on / off
volatile boolean engineStart = false; // Active, if engine is starting up
volatile boolean engineRunning = false; // Active, if engine is running
volatile boolean engineStop = false; // Active, if engine is shutting down
volatile boolean jakeBrakeRequest = false; // Active, if engine jake braking is requested
volatile boolean engineJakeBraking = false; // Active, if engine is jake braking
volatile boolean wastegateTrigger = false; // Trigger wastegate (blowoff) after rapid throttle drop
volatile boolean blowoffTrigger = false; // Trigger jake brake sound (blowoff) after rapid throttle drop
volatile boolean dieselKnockTrigger = false; // Trigger Diesel ignition "knock"
volatile boolean dieselKnockTriggerFirst = false; // The first Diesel ignition "knock" per sequence
volatile boolean airBrakeTrigger = false; // Trigger for air brake noise
volatile boolean parkingBrakeTrigger = false; // Trigger for air parking brake noise
volatile boolean shiftingTrigger = false; // Trigger for shifting noise
volatile boolean hornTrigger = false; // Trigger for horn on / off
volatile boolean sirenTrigger = false; // Trigger for siren on / off
volatile boolean sound1trigger = false; // Trigger for sound1 on / off
volatile boolean couplingTrigger = false; // Trigger for trailer coupling sound
volatile boolean uncouplingTrigger = false; // Trigger for trailer uncoupling sound
volatile boolean indicatorSoundOn = false; // active, if indicator bulb is on
// Sound latches
volatile boolean hornLatch = false; // Horn latch bit
volatile boolean sirenLatch = false; // Siren latch bit
// Sound volumes
volatile uint16_t throttleDependentVolume = 0; // engine volume according to throttle position
volatile uint16_t throttleDependentRevVolume = 0; // engine rev volume according to throttle position
volatile uint16_t rpmDependentJakeBrakeVolume = 0; // Engine rpm dependent jake brake volume
volatile uint16_t throttleDependentKnockVolume = 0; // engine Diesel knock volume according to throttle position
volatile uint16_t rpmDependentKnockVolume = 0; // engine Diesel knock volume according to engine RPM
volatile uint16_t throttleDependentTurboVolume = 0; // turbo volume according to rpm
volatile uint16_t throttleDependentFanVolume = 0; // cooling fan volume according to rpm
volatile uint16_t throttleDependentChargerVolume = 0; // cooling fan volume according to rpm
volatile uint16_t rpmDependentWastegateVolume = 0; // wastegate volume according to rpm
volatile int16_t masterVolume = 100; // Master volume percentage
volatile uint8_t dacOffset = 0; // 128, but needs to be ramped up slowly to prevent popping noise, if switched on
// Throttle
int16_t currentThrottle = 0; // 0 - 500 (Throttle trigger input)
int16_t currentThrottleFaded = 0; // faded throttle for volume calculations etc.
// Engine
const int16_t maxRpm = 500; // always 500
const int16_t minRpm = 0; // always 0
int32_t currentRpm = 0; // 0 - 500 (signed required!)
volatile uint8_t engineState = 0; // Engine state
enum EngineState // Engine state enum
{
OFF,
STARTING,
RUNNING,
STOPPING,
PARKING_BRAKE
};
int16_t engineLoad = 0; // 0 - 500
volatile uint16_t engineSampleRate = 0; // Engine sample rate
int32_t speedLimit = maxRpm; // The speed limit, depending on selected virtual gear
// Clutch
boolean clutchDisengaged = true; // Active while clutch is disengaged
// Transmission
uint8_t selectedGear = 1; // The currently used gear of our shifting gearbox
uint8_t selectedAutomaticGear = 1; // The currently used gear of our automatic gearbox
boolean gearUpShiftingInProgress; // Active while shifting upwards
boolean gearDownShiftingInProgress; // Active while shifting downwards
boolean gearUpShiftingPulse; // Active, if shifting upwards begins
boolean gearDownShiftingPulse; // Active, if shifting downwards begins
volatile boolean neutralGear = false; // Transmission in neutral
// ESC
volatile boolean escIsBraking = false; // ESC is in a braking state
volatile boolean escIsDriving = false; // ESC is in a driving state
volatile boolean escInReverse = false; // ESC is driving or braking backwards
int8_t driveState = 0; // for ESC state machine
int16_t escPulseMax; // ESC calibration variables
int16_t escPulseMin;
int16_t escPulseMaxNeutral;
int16_t escPulseMinNeutral;
uint16_t currentSpeed = 0; // 0 - 500 (current ESC power)
// Lights
int8_t lightsState = 0; // for lights state machine
volatile boolean lightsOn = false; // Lights on
volatile boolean headLightsFlasherOn = false; // Headlights flasher impulse (Lichthupe)
volatile boolean headLightsHighBeamOn = false; // Headlights high beam (Fernlicht)
volatile boolean blueLightTrigger = false; // Bluelight on (Blaulicht)
boolean indicatorLon = false; // Left indicator (Blinker links)
boolean indicatorRon = false; // Right indicator (Blinker rechts)
boolean fogLightOn = false; // Fog light is on
boolean cannonFlash = false; // Flashing cannon fire
// Our main tasks
TaskHandle_t Task1;
// Loop time (for debug)
uint16_t loopTime;
// Sampling intervals for interrupt timer (adjusted according to your sound file sampling rate)
uint32_t maxSampleInterval = 4000000 / sampleRate;
uint32_t minSampleInterval = 4000000 / sampleRate * 100 / MAX_RPM_PERCENTAGE;
// Interrupt timer for variable sample rate playback (engine sound)
hw_timer_t * variableTimer = NULL;
portMUX_TYPE variableTimerMux = portMUX_INITIALIZER_UNLOCKED;
volatile uint32_t variableTimerTicks = maxSampleInterval;
// Interrupt timer for fixed sample rate playback (horn etc., playing in parallel with engine sound)
hw_timer_t * fixedTimer = NULL;
portMUX_TYPE fixedTimerMux = portMUX_INITIALIZER_UNLOCKED;
volatile uint32_t fixedTimerTicks = maxSampleInterval;
//
// =======================================================================================================
// INTERRUPT FOR VARIABLE SPEED PLAYBACK (Engine sound, turbo sound)
// =======================================================================================================
//
void IRAM_ATTR variablePlaybackTimer() {
static uint32_t attenuatorMillis = 0;
static uint32_t curEngineSample = 0; // Index of currently loaded engine sample
static uint32_t curRevSample = 0; // Index of currently loaded engine rev sample
static uint32_t curTurboSample = 0; // Index of currently loaded turbo sample
static uint32_t curFanSample = 0; // Index of currently loaded fan sample
static uint32_t curChargerSample = 0; // Index of currently loaded charger sample
static uint32_t curStartSample = 0; // Index of currently loaded start sample
static uint32_t curJakeBrakeSample = 0; // Index of currently loaded jake brake sample
static uint32_t lastDieselKnockSample = 0; // Index of last Diesel knock sample
static uint16_t attenuator = 0; // Used for volume adjustment during engine switch off
static uint16_t speedPercentage = 0; // slows the engine down during shutdown
static int32_t a, a1, a2, a3, b, c, d, e = 0; // Input signals for mixer: a = engine, b = additional sound, c = turbo sound, d = fan sound, e = supercharger sound
uint8_t a1Multi = 0; // Volume multipliers
//portENTER_CRITICAL_ISR(&variableTimerMux);
switch (engineState) {
case OFF: // Engine off -----------------------------------------------------------------------
variableTimerTicks = 4000000 / startSampleRate; // our fixed sampling rate
timerAlarmWrite(variableTimer, variableTimerTicks, true); // // change timer ticks, autoreload true
a = 0; // volume = zero
if (engineOn) {
engineState = STARTING;
engineStart = true;
}
break;
case STARTING: // Engine start --------------------------------------------------------------------
variableTimerTicks = 4000000 / startSampleRate; // our fixed sampling rate
timerAlarmWrite(variableTimer, variableTimerTicks, true); // // change timer ticks, autoreload true
if (curStartSample < startSampleCount - 1) {
a = (startSamples[curStartSample] * throttleDependentVolume / 100 * startVolumePercentage / 100);
curStartSample ++;
}
else {
curStartSample = 0;
engineState = RUNNING;
engineStart = false;
engineRunning = true;
airBrakeTrigger = true;
}
break;
case RUNNING: // Engine running ------------------------------------------------------------------
// Engine idle & revving sounds (mixed together according to engine rpm, new in v5.0)
variableTimerTicks = engineSampleRate; // our variable idle sampling rate!
timerAlarmWrite(variableTimer, variableTimerTicks, true); // // change timer ticks, autoreload true
if (!engineJakeBraking && !blowoffTrigger) {
if (curEngineSample < sampleCount - 1) {
a1 = (samples[curEngineSample] * throttleDependentVolume / 100 * idleVolumePercentage / 100); // Idle sound
a3 = 0;
curEngineSample ++;
// Optional rev sound, recorded at medium rpm. Note, that it needs to represent the same number of ignition cycles as the
// idle sound. For example 4 or 8 for a V8 engine. It also needs to have about the same length. In order to adjust the length
// or "revSampleCount", change the "Rate" setting in Audacity until it is about the same.
#ifdef REV_SOUND
a2 = (revSamples[curRevSample] * throttleDependentRevVolume / 100 * revVolumePercentage / 100); // Rev sound
if (curRevSample < revSampleCount) curRevSample ++;
#endif
// Trigger throttle dependent Diesel ignition "knock" sound (played in the fixed sample rate interrupt)
if (curEngineSample - lastDieselKnockSample > (sampleCount / dieselKnockInterval)) {
dieselKnockTrigger = true;
dieselKnockTriggerFirst = false;
lastDieselKnockSample = curEngineSample;
}
}
else {
curEngineSample = 0;
if (jakeBrakeRequest) engineJakeBraking = true;
#ifdef REV_SOUND
curRevSample = 0;
#endif
lastDieselKnockSample = 0;
dieselKnockTrigger = true;
dieselKnockTriggerFirst = true;
}
curJakeBrakeSample = 0;
}
else { // Jake brake sound ----
#ifdef JAKE_BRAKE_SOUND
a3 = (jakeBrakeSamples[curJakeBrakeSample] * rpmDependentJakeBrakeVolume / 100 * jakeBrakeVolumePercentage / 100); // Jake brake sound
a2 = 0;
a1 = 0;
if (curJakeBrakeSample < jakeBrakeSampleCount - 1) curJakeBrakeSample ++;
else {
curJakeBrakeSample = 0;
if (!jakeBrakeRequest) engineJakeBraking = false;
}
curEngineSample = 0;
curRevSample = 0;
#endif
}
// Engine sound mixer ----
#ifdef REV_SOUND
// Mixing the idle and rev sounds together, according to engine rpm
// Below the "revSwitchPoint" target, the idle volume precentage is 90%, then falling to 0% @ max. rpm.
// The total of idle and rev volume percentage is always 100%
if (currentRpm > revSwitchPoint) a1Multi = map(currentRpm, idleEndPoint, revSwitchPoint, 0, idleVolumeProportionPercentage);
else a1Multi = idleVolumeProportionPercentage; // 90 - 100% proportion
if (currentRpm > idleEndPoint) a1Multi = 0;
a1 = a1 * a1Multi / 100; // Idle volume
a2 = a2 * (100 - a1Multi) / 100; // Rev volume
a = a1 + a2 + a3; // Idle and rev sounds mixed together
#else
a = a1 + a3; // Idle sound only
#endif
// Turbo sound ----------------------------------
if (curTurboSample < turboSampleCount - 1) {
c = (turboSamples[curTurboSample] * throttleDependentTurboVolume / 100 * turboVolumePercentage / 100);
curTurboSample ++;
}
else {
curTurboSample = 0;
}
// Fan sound -----------------------------------
if (curFanSample < fanSampleCount - 1) {
d = (fanSamples[curFanSample] * throttleDependentFanVolume / 100 * fanVolumePercentage / 100);
curFanSample ++;
}
else {
curFanSample = 0;
}
#if defined GEARBOX_WHINING
if (neutralGear) d = 0; // used for gearbox whining simulation, so not active in gearbox neutral
#endif
// Supercharger sound --------------------------
if (curChargerSample < chargerSampleCount - 1) {
e = (chargerSamples[curChargerSample] * throttleDependentChargerVolume / 100 * chargerVolumePercentage / 100);
curChargerSample ++;
}
else {
curChargerSample = 0;
}
if (!engineOn) {
speedPercentage = 100;
attenuator = 1;
engineState = STOPPING;
engineStop = true;
engineRunning = false;
}
break;
case STOPPING: // Engine stop --------------------------------------------------------------------
variableTimerTicks = 4000000 / sampleRate * speedPercentage / 100; // our fixed sampling rate
timerAlarmWrite(variableTimer, variableTimerTicks, true); // // change timer ticks, autoreload true
if (curEngineSample < sampleCount - 1) {
a = (samples[curEngineSample] * throttleDependentVolume / 100 * idleVolumePercentage / 100 / attenuator);
curEngineSample ++;
}
else {
curEngineSample = 0;
}
// fade engine sound out
if (millis() - attenuatorMillis > 100) { // Every 50ms
attenuatorMillis = millis();
attenuator ++; // attenuate volume
speedPercentage += 20; // make it slower (10)
}
if (attenuator >= 50 || speedPercentage >= 500) { // 50 & 500
a = 0;
speedPercentage = 100;
parkingBrakeTrigger = true;
engineState = PARKING_BRAKE;
engineStop = false;
}
break;
case PARKING_BRAKE: // parking brake bleeding air sound after engine is off ----------------------------
if (!parkingBrakeTrigger) {
engineState = OFF;
}
break;
} // end of switch case
// DAC output (groups a, b, c mixed together) ************************************************************************
dacWrite(DAC1, constrain(((a * 8 / 10) + (b / 2) + (c / 5) + (d / 5) + (e / 5)) * masterVolume / 100 + dacOffset, 0, 255)); // Mix signals, add 128 offset, write result to DAC
//dacWrite(DAC1, constrain(a * masterVolume / 100 + dacOffset, 0, 255));
//dacWrite(DAC1, constrain(a + 128, 0, 255));
//portEXIT_CRITICAL_ISR(&variableTimerMux);
}
//
// =======================================================================================================
// INTERRUPT FOR FIXED SPEED PLAYBACK (Horn etc., played in parallel with engine sound)
// =======================================================================================================
//
void IRAM_ATTR fixedPlaybackTimer() {
static uint32_t curHornSample = 0; // Index of currently loaded horn sample
static uint32_t curSirenSample = 0; // Index of currently loaded siren sample
static uint32_t curSound1Sample = 0; // Index of currently loaded sound1 sample
static uint32_t curReversingSample = 0; // Index of currently loaded reversing beep sample
static uint32_t curIndicatorSample = 0; // Index of currently loaded indicator tick sample
static uint32_t curWastegateSample = 0; // Index of currently loaded wastegate sample
static uint32_t curBrakeSample = 0; // Index of currently loaded brake sound sample
static uint32_t curParkingBrakeSample = 0; // Index of currently loaded brake sound sample
static uint32_t curShiftingSample = 0; // Index of currently loaded shifting sample
static uint32_t curDieselKnockSample = 0; // Index of currently loaded Diesel knock sample
static uint32_t curCouplingSample = 0; // Index of currently loaded trailer coupling sample
static uint32_t curUncouplingSample = 0; // Index of currently loaded trailer uncoupling sample
static int32_t a, a1, a2 = 0; // Input signals "a" for mixer
static int32_t b, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9 = 0;// Input signals "b" for mixer
static boolean knockSilent = 0; // This knock will be more silent
static boolean knockMedium = 0; // This knock will be medium
static uint8_t curKnockCylinder = 0; // Index of currently ignited zylinder
//portENTER_CRITICAL_ISR(&fixedTimerMux);
// Group "a" (horn & siren) ******************************************************************
if (hornTrigger || hornLatch) {
fixedTimerTicks = 4000000 / hornSampleRate; // our fixed sampling rate
timerAlarmWrite(fixedTimer, fixedTimerTicks, true); // // change timer ticks, autoreload true
if (curHornSample < hornSampleCount - 1) {
a1 = (hornSamples[curHornSample] * hornVolumePercentage / 100);
curHornSample ++;
#ifdef HORN_LOOP // Optional "endless loop" (points to be defined manually in horn file)
if (hornTrigger && curHornSample == hornLoopEnd) curHornSample = hornLoopBegin; // Loop, if trigger still present
#endif
}
else { // End of sample
curHornSample = 0;
a1 = 0;
hornLatch = false;
}
}
if (sirenTrigger || sirenLatch) {
fixedTimerTicks = 4000000 / sirenSampleRate; // our fixed sampling rate
timerAlarmWrite(fixedTimer, fixedTimerTicks, true); // // change timer ticks, autoreload true
if (curSirenSample < sirenSampleCount - 1) {
a2 = (sirenSamples[curSirenSample] * sirenVolumePercentage / 100);
curSirenSample ++;
#ifdef SIREN_LOOP // Optional "endless loop" (points to be defined manually in siren file)
if (sirenTrigger && curSirenSample == sirenLoopEnd) curSirenSample = sirenLoopBegin; // Loop, if trigger still present
#endif
}
else { // End of sample
curSirenSample = 0;
a2 = 0;
sirenLatch = false;
}
}
if (curSirenSample > 10 && curSirenSample < 500) cannonFlash = true; // Tank cannon flash triggering in TRACKED_MODE
else cannonFlash = false;
// Group "b" (other sounds) **********************************************************************
// Sound 1 "b0" ----
if (sound1trigger) {
fixedTimerTicks = 4000000 / sound1SampleRate; // our fixed sampling rate
timerAlarmWrite(fixedTimer, fixedTimerTicks, true); // // change timer ticks, autoreload true
if (curSound1Sample < sound1SampleCount - 1) {
b0 = (sound1Samples[curSound1Sample] * sound1VolumePercentage / 100);
curSound1Sample ++;
}
else {
sound1trigger = false;
}
}
else {
curSound1Sample = 0; // ensure, next sound will start @ first sample
b0 = 0;
}
// Reversing beep sound "b1" ----
if (engineRunning && escInReverse) {
fixedTimerTicks = 4000000 / reversingSampleRate; // our fixed sampling rate
timerAlarmWrite(fixedTimer, fixedTimerTicks, true); // // change timer ticks, autoreload true
if (curReversingSample < reversingSampleCount - 1) {
b1 = (reversingSamples[curReversingSample] * reversingVolumePercentage / 100);
curReversingSample ++;
}
else {
curReversingSample = 0;
}
}
else {
curReversingSample = 0; // ensure, next sound will start @ first sample
b1 = 0;
}
// Indicator tick sound "b2" ----------------------------------------------------------------------
if (indicatorSoundOn) {
fixedTimerTicks = 4000000 / indicatorSampleRate; // our fixed sampling rate
timerAlarmWrite(fixedTimer, fixedTimerTicks, true); // // change timer ticks, autoreload true
if (curIndicatorSample < indicatorSampleCount - 1) {
b2 = (indicatorSamples[curIndicatorSample] * indicatorVolumePercentage / 100);
curIndicatorSample ++;
}
else {
indicatorSoundOn = false;
}
}
else {
curIndicatorSample = 0; // ensure, next sound will start @ first sample
b2 = 0;
}
// Wastegate (blowoff) sound, triggered after rapid throttle drop -----------------------------------
if (wastegateTrigger) {
if (curWastegateSample < wastegateSampleCount - 1) {
b3 = (wastegateSamples[curWastegateSample] * rpmDependentWastegateVolume / 100 * wastegateVolumePercentage / 100);
curWastegateSample ++;
}
else {
wastegateTrigger = false;
}
}
else {
b3 = 0;
curWastegateSample = 0; // ensure, next sound will start @ first sample
}
// Air brake release sound, triggered after stop -----------------------------------------------
if (airBrakeTrigger) {
if (curBrakeSample < brakeSampleCount - 1) {
b4 = (brakeSamples[curBrakeSample] * brakeVolumePercentage / 100);
curBrakeSample ++;
}
else {
airBrakeTrigger = false;
}
}
else {
b4 = 0;
curBrakeSample = 0; // ensure, next sound will start @ first sample
}
// Air parking brake attaching sound, triggered after engine off --------------------------------
if (parkingBrakeTrigger) {
if (curParkingBrakeSample < parkingBrakeSampleCount - 1) {
b5 = (parkingBrakeSamples[curParkingBrakeSample] * parkingBrakeVolumePercentage / 100);
curParkingBrakeSample ++;
}
else {
parkingBrakeTrigger = false;
}
}
else {
b5 = 0;
curParkingBrakeSample = 0; // ensure, next sound will start @ first sample
}
// Pneumatic gear shifting sound, triggered while shifting the TAMIYA 3 speed transmission ------
if (shiftingTrigger && engineRunning && !automatic && !doubleClutch) {
if (curShiftingSample < shiftingSampleCount - 1) {
b6 = (shiftingSamples[curShiftingSample] * shiftingVolumePercentage / 100);
curShiftingSample ++;
}
else {
shiftingTrigger = false;
}
}
else {
b6 = 0;
curShiftingSample = 0; // ensure, next sound will start @ first sample
}
// Diesel ignition "knock" is played in fixed sample rate section, because we don't want changing pitch! ------
if (dieselKnockTriggerFirst) {
dieselKnockTriggerFirst = false;
curKnockCylinder = 0;
}
if (dieselKnockTrigger) {
dieselKnockTrigger = false;
curKnockCylinder ++; // Count ignition sequence
curDieselKnockSample = 0;
}
#ifdef V8 // (former ADAPTIVE_KNOCK_VOLUME, rename it in your config file!)
// Ford or Scania V8 ignition sequence: 1 - 5 - 4 - 2* - 6 - 3 - 7 - 8* (* = louder knock pulses, because 2nd exhaust in same manifold after 90°)
if (curKnockCylinder == 4 || curKnockCylinder == 8) knockSilent = false;
else knockSilent = true;
#endif
#ifdef V8_MEDIUM // (former ADAPTIVE_KNOCK_VOLUME, rename it in your config file!)
// This is EXPERIMENTAL!! TODO
if (curKnockCylinder == 5 || curKnockCylinder == 1) knockMedium = false;
else knockMedium = true;
#endif
#ifdef V8_468 // (Chevy 468, containing 16 ignition pulses)
// 1th, 5th, 9th and 13th are the loudest
// Ignition sequence: 1 - 8 - 4* - 3 - 6 - 5 - 7* - 2
if (curKnockCylinder == 1 || curKnockCylinder == 5 || curKnockCylinder == 9 || curKnockCylinder == 13) knockSilent = false;
else knockSilent = true;
#endif
#ifdef V2
// V2 engine: 1st and 2nd knock pulses (of 4) will be louder
if (curKnockCylinder == 1 || curKnockCylinder == 2) knockSilent = false;
else knockSilent = true;
#endif
#ifdef R6
// R6 inline 6 engine: 6th knock pulse (of 6) will be louder
if (curKnockCylinder == 6) knockSilent = false;
else knockSilent = true;
#endif
if (curDieselKnockSample < knockSampleCount) {
#ifdef RPM_DEPENDENT_KNOCK // knock volume also depending on engine rpm
b7 = (knockSamples[curDieselKnockSample] * dieselKnockVolumePercentage / 100 * throttleDependentKnockVolume / 100 * rpmDependentKnockVolume / 100);
#else // Just depending on throttle
b7 = (knockSamples[curDieselKnockSample] * dieselKnockVolumePercentage / 100 * throttleDependentKnockVolume / 100);
#endif
curDieselKnockSample ++;
if (knockSilent && ! knockMedium) b7 = b7 * dieselKnockAdaptiveVolumePercentage / 100; // changing knock volume according to engine type and cylinder!
if (knockMedium) b7 = b7 * dieselKnockAdaptiveVolumePercentage / 75;
}
// Trailer coupling sound, triggered by switch -----------------------------------------------
#ifdef COUPLING_SOUND
if (couplingTrigger) {
if (curCouplingSample < couplingSampleCount - 1) {
b8 = (couplingSamples[curCouplingSample] * couplingVolumePercentage / 100);
curCouplingSample ++;
}
else {
couplingTrigger = false;
}
}
else {
b8 = 0;
curCouplingSample = 0; // ensure, next sound will start @ first sample
}
// Trailer uncoupling sound, triggered by switch -----------------------------------------------
if (uncouplingTrigger) {
if (curUncouplingSample < uncouplingSampleCount - 1) {
b9 = (uncouplingSamples[curUncouplingSample] * couplingVolumePercentage / 100);
curUncouplingSample ++;
}
else {
uncouplingTrigger = false;
}
}
else {
b9 = 0;
curUncouplingSample = 0; // ensure, next sound will start @ first sample
}
#endif
// Mixing sounds together ----
a = a1 + a2; // Horn & siren
b = b0 * 5 + b1 + b2 / 2 + b3 + b4 + b5 + b6 + b7 + b8 + b9; // Other sounds
// DAC output (groups a + b mixed together) ****************************************************************************
dacWrite(DAC2, constrain(((a * 8 / 10) + (b * 2 / 10)) * masterVolume / 100 + dacOffset, 0, 255)); // Mix signals, add 128 offset, write result to DAC
//dacWrite(DAC2, 0);
//portEXIT_CRITICAL_ISR(&fixedTimerMux);
}
//
// =======================================================================================================
// PWM SIGNAL READ INTERRUPT
// =======================================================================================================
//
// Reference https://esp-idf.readthedocs.io/en/v1.0/api/rmt.html
static void IRAM_ATTR rmt_isr_handler(void* arg) {
uint32_t intr_st = RMT.int_st.val;
uint8_t i;
for (i = 0; i < PWM_CHANNELS_NUM; i++) {
uint8_t channel = PWM_CHANNELS[i];
uint32_t channel_mask = BIT(channel * 3 + 1);
if (!(intr_st & channel_mask)) continue;
RMT.conf_ch[channel].conf1.rx_en = 0;
RMT.conf_ch[channel].conf1.mem_owner = RMT_MEM_OWNER_TX;
volatile rmt_item32_t* item = RMTMEM.chan[channel].data32;
if (item) {
pulseWidthRaw[i + 1] = item->duration0;
}
RMT.conf_ch[channel].conf1.mem_wr_rst = 1;
RMT.conf_ch[channel].conf1.mem_owner = RMT_MEM_OWNER_RX;
RMT.conf_ch[channel].conf1.rx_en = 1;
//clear RMT interrupt status.
RMT.int_clr.val = channel_mask;
}
}
//
// =======================================================================================================
// PPM SIGNAL READ INTERRUPT
// =======================================================================================================
//
void IRAM_ATTR readPpm() {
unsigned long timenew = micros();
unsigned long timediff = timenew - timelast;
timelast = timenew;
if (timediff > 2500) { // Synch gap detected:
ppmInp[NUM_OF_PPM_CHL] = ppmInp[NUM_OF_PPM_CHL] + timediff; // add time
counter = 0;
if (average == NUM_OF_PPM_AVG) {
for (int i = 0; i < NUM_OF_PPM_CHL + 1; i++) {
ppmBuf[i] = ppmInp[i] / average;
ppmInp[i] = 0;
}
average = 0;
ready = true;
}
average++;
}
else {
if (counter < NUM_OF_PPM_CHL) {
ppmInp[counter] = ppmInp[counter] + timediff;
counter++;
}
}
}
//
// =======================================================================================================
// TRAILER PRESENCE SWITCH INTERRUPT
// =======================================================================================================
//
#if not defined THIRD_BRAKLELIGHT
void trailerPresenceSwitchInterrupt() {
couplerSwitchInteruptLatch = true;
}
#endif
//
// =======================================================================================================
// mcpwm SETUP (1x during startup)
// =======================================================================================================
//
// See: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/mcpwm.html#configure
void setupMcpwm() {
// 1. set our servo output pins
mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0A, STEERING_PIN); //Set steering as PWM0A
mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0B, SHIFTING_PIN); //Set shifting as PWM0B
mcpwm_gpio_init(MCPWM_UNIT_1, MCPWM1A, COUPLER_PIN); //Set coupling as PWM1A
mcpwm_gpio_init(MCPWM_UNIT_1, MCPWM1B, WINCH_PIN); //Set winch as PWM1B
// 2. configure MCPWM parameters
mcpwm_config_t pwm_config;
pwm_config.frequency = SERVO_FREQUENCY; //frequency usually = 50Hz, some servos may run smoother @ 100Hz
pwm_config.cmpr_a = 0; //duty cycle of PWMxa = 0
pwm_config.cmpr_b = 0; //duty cycle of PWMxb = 0
pwm_config.counter_mode = MCPWM_UP_COUNTER;
pwm_config.duty_mode = MCPWM_DUTY_MODE_0; // 0 = not inverted, 1 = inverted
// 3. configure channels with settings above
mcpwm_init(MCPWM_UNIT_0, MCPWM_TIMER_0, &pwm_config); //Configure PWM0A & PWM0B
mcpwm_init(MCPWM_UNIT_1, MCPWM_TIMER_1, &pwm_config); //Configure PWM1A & PWM1B
}