forked from Arduino-IRremote/Arduino-IRremote
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIRReceive.hpp
1977 lines (1791 loc) · 71.5 KB
/
IRReceive.hpp
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
/*
* IRReceive.hpp
* This file is exclusively included by IRremote.h to enable easy configuration of library switches
*
* Contains all IRrecv class functions as well as other receiver related functions.
*
* This file is part of Arduino-IRremote https://github.com/Arduino-IRremote/Arduino-IRremote.
*
************************************************************************************
* MIT License
*
* Copyright (c) 2009-2023 Ken Shirriff, Rafi Khan, Armin Joachimsmeyer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
************************************************************************************
*/
#ifndef _IR_RECEIVE_HPP
#define _IR_RECEIVE_HPP
#if defined(DEBUG) && !defined(LOCAL_DEBUG)
//#define LOCAL_DEBUG //
#else
//#define LOCAL_DEBUG // This enables debug output only for this file
#endif
#if defined(TRACE) && !defined(LOCAL_TRACE)
#define LOCAL_TRACE
#else
//#define LOCAL_TRACE // This enables debug output only for this file
#endif
/*
* Low level hardware timing measurement
*/
//#define _IR_MEASURE_TIMING // for ISR
//#define _IR_TIMING_TEST_PIN 7 // "pinModeFast(_IR_TIMING_TEST_PIN, OUTPUT);" is executed at start()
//
/** \addtogroup Receiving Receiving IR data for multiple protocols
* @{
*/
/**
* The receiver instance
*/
IRrecv IrReceiver;
/*
* The control structure instance
*/
struct irparams_struct irparams; // the irparams instance
unsigned long sMicrosAtLastStopTimer = 0; // Used to adjust TickCounterForISR with uncounted ticks between stopTimer() and restartTimer()
/**
* Instantiate the IRrecv class. Multiple instantiation is not supported.
* @param IRReceivePin Arduino pin to use. No sanity check is made.
*/
IRrecv::IRrecv() {
decodedIRData.rawDataPtr = &irparams; // for decodePulseDistanceData() etc.
setReceivePin(0);
#if !defined(NO_LED_FEEDBACK_CODE)
setLEDFeedback(0, DO_NOT_ENABLE_LED_FEEDBACK);
#endif
}
IRrecv::IRrecv(uint_fast8_t aReceivePin) {
decodedIRData.rawDataPtr = &irparams; // for decodePulseDistanceData() etc.
setReceivePin(aReceivePin);
#if !defined(NO_LED_FEEDBACK_CODE)
setLEDFeedback(0, DO_NOT_ENABLE_LED_FEEDBACK);
#endif
}
/**
* Instantiate the IRrecv class. Multiple instantiation is not supported.
* @param aReceivePin Arduino pin to use, where a demodulating IR receiver is connected.
* @param aFeedbackLEDPin if 0, then take board specific FEEDBACK_LED_ON() and FEEDBACK_LED_OFF() functions
*/
IRrecv::IRrecv(uint_fast8_t aReceivePin, uint_fast8_t aFeedbackLEDPin) {
decodedIRData.rawDataPtr = &irparams; // for decodePulseDistanceData() etc.
setReceivePin(aReceivePin);
#if !defined(NO_LED_FEEDBACK_CODE)
setLEDFeedback(aFeedbackLEDPin, DO_NOT_ENABLE_LED_FEEDBACK);
#else
(void) aFeedbackLEDPin;
#endif
}
/**********************************************************************************************************************
* Interrupt Service Routine - Called every 50 us
*
* Duration in ticks of 50 us of alternating SPACE, MARK are recorded in irparams.rawbuf array.
* 'rawlen' counts the number of entries recorded so far.
* First entry is the SPACE between transmissions.
*
* As soon as one SPACE entry gets longer than RECORD_GAP_TICKS, state switches to STOP (frame received). Timing of SPACE continues.
* A call of resume() switches from STOP to IDLE.
* As soon as first MARK arrives in IDLE, gap width is recorded and new logging starts.
*
* With digitalRead and Feedback LED
* 15 pushs, 1 in, 1 eor before start of code = 2 us @16MHz + * 7.2 us computation time (6us idle time) + * pop + reti = 2.25 us @16MHz => 10.3 to 11.5 us @16MHz
* With portInputRegister and mask and Feedback LED code commented
* 9 pushs, 1 in, 1 eor before start of code = 1.25 us @16MHz + * 2.25 us computation time + * pop + reti = 1.5 us @16MHz => 5 us @16MHz
* => Minimal CPU frequency is 4 MHz
*
**********************************************************************************************************************/
#if defined(ESP8266) || defined(ESP32)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wvolatile"
IRAM_ATTR
#endif
void IRReceiveTimerInterruptHandler() {
#if defined(_IR_MEASURE_TIMING) && defined(_IR_TIMING_TEST_PIN)
digitalWriteFast(_IR_TIMING_TEST_PIN, HIGH); // 2 clock cycles
#endif
// 7 - 8.5 us for ISR body (without pushes and pops) for ATmega328 @16MHz
#if defined(TIMER_REQUIRES_RESET_INTR_PENDING)
timerResetInterruptPending(); // reset TickCounterForISR interrupt flag if required (currently only for Teensy and ATmega4809)
#endif
// Read if IR Receiver -> SPACE [xmt LED off] or a MARK [xmt LED on]
#if defined(__AVR__)
uint8_t tIRInputLevel = *irparams.IRReceivePinPortInputRegister & irparams.IRReceivePinMask;
#else
uint_fast8_t tIRInputLevel = (uint_fast8_t) digitalReadFast(irparams.IRReceivePin);
#endif
/*
* Increase TickCounter and clip it at maximum 0xFFFF / 3.2 seconds at 50 us ticks
*/
if (irparams.TickCounterForISR < UINT16_MAX) {
irparams.TickCounterForISR++; // One more 50uS tick
}
/*
* Due to a ESP32 compiler bug https://github.com/espressif/esp-idf/issues/1552 no switch statements are possible for ESP32
* So we change the code to if / else if
*/
// switch (irparams.StateForISR) {
//
if (irparams.StateForISR == IR_REC_STATE_IDLE) {
/*
* Here we are just resumed and maybe in the middle of a transmission
*/
if (tIRInputLevel == INPUT_MARK) {
// check if we did not start in the middle of a transmission by checking the minimum length of leading space
if (irparams.TickCounterForISR > RECORD_GAP_TICKS) {
#if defined(_IR_MEASURE_TIMING) && defined(_IR_TIMING_TEST_PIN)
// digitalWriteFast(_IR_TIMING_TEST_PIN, HIGH); // 2 clock cycles
#endif
/*
* Gap between two transmissions just ended; Record gap duration + start recording transmission
* Initialize all state machine variables
*/
irparams.OverflowFlag = false;
// irparams.rawbuf[0] = irparams.TickCounterForISR;
irparams.initialGapTicks = irparams.TickCounterForISR; // Enabling 8 bit buffer since 4.4
irparams.rawlen = 1;
irparams.StateForISR = IR_REC_STATE_MARK;
} // otherwise stay in idle state
irparams.TickCounterForISR = 0; // reset counter in both cases
}
} else if (irparams.StateForISR == IR_REC_STATE_MARK) { // Timing mark
if (tIRInputLevel != INPUT_MARK) {
/*
* Mark ended here. Record mark time in rawbuf array
*/
#if defined(_IR_MEASURE_TIMING) && defined(_IR_TIMING_TEST_PIN)
// digitalWriteFast(_IR_TIMING_TEST_PIN, HIGH); // 2 clock cycles
#endif
irparams.rawbuf[irparams.rawlen++] = irparams.TickCounterForISR; // record mark
irparams.StateForISR = IR_REC_STATE_SPACE;
irparams.TickCounterForISR = 0; // This resets the tick counter also at end of frame :-)
}
} else if (irparams.StateForISR == IR_REC_STATE_SPACE) { // Timing space
if (tIRInputLevel == INPUT_MARK) {
/*
* Space ended here. Check for overflow and record space time in rawbuf array
*/
if (irparams.rawlen >= RAW_BUFFER_LENGTH) {
// Flag up a read OverflowFlag; Stop the state machine
irparams.OverflowFlag = true;
irparams.StateForISR = IR_REC_STATE_STOP;
#if !defined(IR_REMOTE_DISABLE_RECEIVE_COMPLETE_CALLBACK)
/*
* Call callback if registered (not NULL)
*/
if (irparams.ReceiveCompleteCallbackFunction != NULL) {
irparams.ReceiveCompleteCallbackFunction();
}
#endif
} else {
#if defined(_IR_MEASURE_TIMING) && defined(_IR_TIMING_TEST_PIN)
// digitalWriteFast(_IR_TIMING_TEST_PIN, HIGH); // 2 clock cycles
#endif
irparams.rawbuf[irparams.rawlen++] = irparams.TickCounterForISR; // record space
irparams.StateForISR = IR_REC_STATE_MARK;
}
irparams.TickCounterForISR = 0;
} else if (irparams.TickCounterForISR > RECORD_GAP_TICKS) {
/*
* Maximum space duration reached here.
* Current code is ready for processing!
* We received a long space, which indicates gap between codes.
* Switch to IR_REC_STATE_STOP
* Don't reset TickCounterForISR; keep counting width of next leading space
*/
/*
* These 2 variables allow to call resume() directly after decode.
* After resume(), decodedIRData.rawDataPtr->initialGapTicks and decodedIRData.rawDataPtr->rawlen are
* the first variables, which are overwritten by the next received frame.
* since 4.3.0.
* For backward compatibility, there are the same 2 statements in decode() if IrReceiver is not used.
*/
IrReceiver.decodedIRData.initialGapTicks = irparams.initialGapTicks;
IrReceiver.decodedIRData.rawlen = irparams.rawlen;
irparams.StateForISR = IR_REC_STATE_STOP; // This signals the decode(), that a complete frame was received
#if !defined(IR_REMOTE_DISABLE_RECEIVE_COMPLETE_CALLBACK)
/*
* Call callback if registered (not NULL)
*/
if (irparams.ReceiveCompleteCallbackFunction != NULL) {
irparams.ReceiveCompleteCallbackFunction();
}
#endif
}
} else if (irparams.StateForISR == IR_REC_STATE_STOP) {
/*
* Complete command received
* stay here until resume() is called, which switches state to IR_REC_STATE_IDLE
*/
#if defined(_IR_MEASURE_TIMING) && defined(_IR_TIMING_TEST_PIN)
// digitalWriteFast(_IR_TIMING_TEST_PIN, HIGH); // 2 clock cycles
#endif
if (tIRInputLevel == INPUT_MARK) {
// Reset gap TickCounterForISR, to prepare for detection if we are in the middle of a transmission after call of resume()
irparams.TickCounterForISR = 0;
}
}
#if !defined(NO_LED_FEEDBACK_CODE)
if (FeedbackLEDControl.LedFeedbackEnabled & LED_FEEDBACK_ENABLED_FOR_RECEIVE) {
setFeedbackLED(tIRInputLevel == INPUT_MARK);
}
#endif
#ifdef _IR_MEASURE_TIMING
digitalWriteFast(_IR_TIMING_TEST_PIN, LOW); // 2 clock cycles
#endif
}
/*
* The ISR, which calls the interrupt handler
*/
#if defined(TIMER_INTR_NAME) || defined(ISR)
# if defined(TIMER_INTR_NAME)
ISR (TIMER_INTR_NAME) // for ISR definitions
# elif defined(ISR)
ISR()
// for functions definitions which are called by separate (board specific) ISR
# endif
{
IRReceiveTimerInterruptHandler();
}
#endif
/**********************************************************************************************************************
* Stream like API
**********************************************************************************************************************/
/**
* Initializes the receive and feedback pin
* @param aReceivePin The Arduino pin number, where a demodulating IR receiver is connected.
* @param aEnableLEDFeedback if true / ENABLE_LED_FEEDBACK, then let the feedback led blink on receiving IR signal
* @param aFeedbackLEDPin if 0 / USE_DEFAULT_FEEDBACK_LED_PIN, then take board specific FEEDBACK_LED_ON() and FEEDBACK_LED_OFF() functions
*/
void IRrecv::begin(uint_fast8_t aReceivePin, bool aEnableLEDFeedback, uint_fast8_t aFeedbackLEDPin) {
setReceivePin(aReceivePin);
#if !defined(NO_LED_FEEDBACK_CODE)
uint_fast8_t tEnableLEDFeedback = DO_NOT_ENABLE_LED_FEEDBACK;
if (aEnableLEDFeedback) {
tEnableLEDFeedback = LED_FEEDBACK_ENABLED_FOR_RECEIVE;
}
setLEDFeedback(aFeedbackLEDPin, tEnableLEDFeedback);
#else
(void) aEnableLEDFeedback;
(void) aFeedbackLEDPin;
#endif
#if defined(_IR_MEASURE_TIMING) && defined(_IR_TIMING_TEST_PIN)
pinModeFast(_IR_TIMING_TEST_PIN, OUTPUT);
#endif
start();
}
/**
* Sets / changes the receiver pin number
*/
void IRrecv::setReceivePin(uint_fast8_t aReceivePinNumber) {
irparams.IRReceivePin = aReceivePinNumber;
#if defined(__AVR__)
# if defined(__digitalPinToBit)
if (__builtin_constant_p(aReceivePinNumber)) {
irparams.IRReceivePinMask = 1UL << (__digitalPinToBit(aReceivePinNumber));
} else {
irparams.IRReceivePinMask = digitalPinToBitMask(aReceivePinNumber); // requires 10 bytes PGM, even if not referenced (?because it is assembler code?)
}
# else
irparams.IRReceivePinMask = digitalPinToBitMask(aReceivePinNumber); // requires 10 bytes PGM, even if not referenced (?because it is assembler code?)
# endif
# if defined(__digitalPinToPINReg)
/*
* This code is 54 bytes smaller, if aReceivePinNumber is a constant :-), but 38 byte longer if it is not constant (,which is not likely).
*/
if (__builtin_constant_p(aReceivePinNumber)) {
irparams.IRReceivePinPortInputRegister = __digitalPinToPINReg(aReceivePinNumber);
} else {
irparams.IRReceivePinPortInputRegister = portInputRegister(digitalPinToPort(aReceivePinNumber)); // requires 44 bytes PGM, even if not referenced
}
# else
irparams.IRReceivePinPortInputRegister = portInputRegister(digitalPinToPort(aReceivePinNumber)); // requires 44 bytes PGM, even if not referenced
# endif
#endif
// Set pin mode once. pinModeFast makes no difference if used, but saves 224 if not referenced :-(
pinModeFast(aReceivePinNumber, INPUT); // Seems to be at least required by ESP32
}
#if !defined(IR_REMOTE_DISABLE_RECEIVE_COMPLETE_CALLBACK)
/**
* Sets the function to call if a protocol message has arrived
*/
void IRrecv::registerReceiveCompleteCallback(void (*aReceiveCompleteCallbackFunction)(void)) {
irparams.ReceiveCompleteCallbackFunction = aReceiveCompleteCallbackFunction;
}
#endif
/**
* Start the receiving process.
* This configures the timer and the state machine for IR reception
* and enables the receive sample timer interrupt which consumes a small amount of CPU every 50 us.
*/
void IRrecv::start() {
// Setup for cyclic 50 us interrupt
timerConfigForReceive(); // no interrupts enabled here!
// Initialize state machine state
resume();
// Timer interrupt is enabled after state machine reset
timerEnableReceiveInterrupt(); // Enables the receive sample timer interrupt which consumes a small amount of CPU every 50 us.
#ifdef _IR_MEASURE_TIMING
pinModeFast(_IR_TIMING_TEST_PIN, OUTPUT);
#endif
}
/*
* Do not resume() reading of IR data
*/
void IRrecv::restartTimer() {
// Setup for cyclic 50 us interrupt
timerConfigForReceive(); // no interrupts enabled here!
// Timer interrupt is enabled after state machine reset
if (sMicrosAtLastStopTimer != 0) {
irparams.TickCounterForISR += (micros() - sMicrosAtLastStopTimer) / MICROS_PER_TICK; // adjust TickCounterForISR for correct gap value, which is used for repeat detection
sMicrosAtLastStopTimer = 0;
}
timerEnableReceiveInterrupt(); // Enables the receive sample timer interrupt which consumes a small amount of CPU every 50 us.
#ifdef _IR_MEASURE_TIMING
pinModeFast(_IR_TIMING_TEST_PIN, OUTPUT);
#endif
}
/**
* Alias for start().
*/
void IRrecv::enableIRIn() {
start();
}
/**
* Configures the timer and the state machine for IR reception.
* We assume, that timer interrupts are disabled here, otherwise it makes no sense to use this functions.
* Therefore we do not need to guard the change of the volatile TickCounterForISR here :-).
* The tick counter value is already at 100 when decode() gets true, because of the 5000 us minimal gap defined in RECORD_GAP_MICROS.
* If TickCounterForISR is not adjusted with the value of the microseconds, the timer was stopped,
* it can happen, that a new IR frame is recognized as a repeat, because the value of RECORD_GAP_MICROS
* was not reached by TickCounterForISR counter before receiving the new IR frame.
* @param aMicrosecondsToAddToGapCounter To compensate for the amount of microseconds the timer was stopped / disabled.
*/
void IRrecv::restartTimer(uint32_t aMicrosecondsToAddToGapCounter) {
irparams.TickCounterForISR += aMicrosecondsToAddToGapCounter / MICROS_PER_TICK;
timerConfigForReceive(); // no interrupts enabled here!
timerEnableReceiveInterrupt(); // Enables the receive sample timer interrupt which consumes a small amount of CPU every 50 us.
#ifdef _IR_MEASURE_TIMING
pinModeFast(_IR_TIMING_TEST_PIN, OUTPUT);
#endif
}
void IRrecv::restartTimerWithTicksToAdd(uint16_t aTicksToAddToGapCounter) {
irparams.TickCounterForISR += aTicksToAddToGapCounter;
timerConfigForReceive(); // no interrupts enabled here!
timerEnableReceiveInterrupt(); // Enables the receive sample timer interrupt which consumes a small amount of CPU every 50 us.
#ifdef _IR_MEASURE_TIMING
pinModeFast(_IR_TIMING_TEST_PIN, OUTPUT);
#endif
}
#if defined(ESP8266) || defined(ESP32)
#pragma GCC diagnostic push
#endif
/**
* Restarts receiver after send. Is a NOP if sending does not require a timer.
*/
void IRrecv::restartAfterSend() {
#if defined(SEND_PWM_BY_TIMER) && !defined(SEND_PWM_DOES_NOT_USE_RECEIVE_TIMER)
start();
#endif
}
/**
* Disables the timer for IR reception.
*/
void IRrecv::stop() {
timerDisableReceiveInterrupt();
}
/*
* Stores microseconds of stop, to adjust TickCounterForISR in restartTimer()
*/
void IRrecv::stopTimer() {
timerDisableReceiveInterrupt();
sMicrosAtLastStopTimer = micros();
}
/**
* Alias for stop().
*/
void IRrecv::disableIRIn() {
stop();
}
/**
* Alias for stop().
*/
void IRrecv::end() {
stop();
}
/**
* Returns status of reception
* @return true if no reception is on-going.
*/
bool IRrecv::isIdle() {
return (irparams.StateForISR == IR_REC_STATE_IDLE || irparams.StateForISR == IR_REC_STATE_STOP) ? true : false;
}
/**
* Restart the ISR (Interrupt Service Routine) state machine, to enable receiving of the next IR frame.
* Internal counting of gap timing is independent of StateForISR and therefore independent of call time of resume().
*/
void IRrecv::resume() {
// This check allows to call resume at arbitrary places or more than once
if (irparams.StateForISR == IR_REC_STATE_STOP) {
irparams.StateForISR = IR_REC_STATE_IDLE;
}
}
/**
* Is internally called by decode before calling decoders.
* Must be used to setup data, if you call decoders manually.
*/
void IRrecv::initDecodedIRData() {
if (irparams.OverflowFlag) {
decodedIRData.flags = IRDATA_FLAGS_WAS_OVERFLOW;
#if defined(LOCAL_DEBUG)
Serial.print(F("Overflow happened, try to increase the \"RAW_BUFFER_LENGTH\" value of "));
Serial.print(RAW_BUFFER_LENGTH);
Serial.println(F(" with #define RAW_BUFFER_LENGTH=<biggerValue>"));
#endif
} else {
decodedIRData.flags = IRDATA_FLAGS_EMPTY;
// save last protocol, command and address for repeat handling (where they are compared or copied back :-))
lastDecodedProtocol = decodedIRData.protocol; // repeat patterns can be equal between protocols (e.g. NEC, Samsung and LG), so we must keep the original one
lastDecodedCommand = decodedIRData.command;
lastDecodedAddress = decodedIRData.address;
}
decodedIRData.protocol = UNKNOWN;
decodedIRData.command = 0;
decodedIRData.address = 0;
decodedIRData.decodedRawData = 0;
decodedIRData.numberOfBits = 0;
}
/**
* Returns true if IR receiver data is available.
*/
bool IRrecv::available() {
return (irparams.StateForISR == IR_REC_STATE_STOP);
}
/**
* If IR receiver data is available, returns pointer to IrReceiver.decodedIRData, else NULL.
*/
IRData* IRrecv::read() {
if (irparams.StateForISR != IR_REC_STATE_STOP) {
return NULL;
}
if (decode()) {
return &decodedIRData;
} else {
return NULL;
}
}
/**
* The main decode function, attempts to decode the recently receive IR signal.
* The set of decoders used is determined by active definitions of the DECODE_<PROTOCOL> macros.
* Results of decoding are stored in IrReceiver.decodedIRData.* like e.g. IrReceiver.decodedIRData.command.
* @return false if no IR receiver data available, true if data available.
*/
bool IRrecv::decode() {
if (irparams.StateForISR != IR_REC_STATE_STOP) {
return false;
}
/*
* Support for old examples, which do not use the default IrReceiver instance
*/
if (this != &IrReceiver) {
decodedIRData.initialGapTicks = irparams.initialGapTicks;
decodedIRData.rawlen = irparams.rawlen;
}
initDecodedIRData(); // sets IRDATA_FLAGS_WAS_OVERFLOW
if (decodedIRData.flags & IRDATA_FLAGS_WAS_OVERFLOW) {
/*
* Set OverflowFlag flag and return true here, to let the loop call resume or print raw data.
*/
decodedIRData.protocol = UNKNOWN;
return true;
}
#if defined(DECODE_NEC) || defined(DECODE_ONKYO)
IR_TRACE_PRINTLN(F("Attempting NEC/Onkyo decode"));
if (decodeNEC()) {
return true;
}
#endif
#if defined(DECODE_PANASONIC) || defined(DECODE_KASEIKYO)
IR_TRACE_PRINTLN(F("Attempting Panasonic/Kaseikyo decode"));
if (decodeKaseikyo()) {
return true;
}
#endif
#if defined(DECODE_DENON)
IR_TRACE_PRINTLN(F("Attempting Denon/Sharp decode"));
if (decodeDenon()) {
return true;
}
#endif
#if defined(DECODE_SONY)
IR_TRACE_PRINTLN(F("Attempting Sony decode"));
if (decodeSony()) {
return true;
}
#endif
#if defined(DECODE_RC5)
IR_TRACE_PRINTLN(F("Attempting RC5 decode"));
if (decodeRC5()) {
return true;
}
#endif
#if defined(DECODE_RC6)
IR_TRACE_PRINTLN(F("Attempting RC6 decode"));
if (decodeRC6()) {
return true;
}
#endif
#if defined(DECODE_LG)
IR_TRACE_PRINTLN(F("Attempting LG decode"));
if (decodeLG()) {
return true;
}
#endif
#if defined(DECODE_JVC)
IR_TRACE_PRINTLN(F("Attempting JVC decode"));
if (decodeJVC()) {
return true;
}
#endif
#if defined(DECODE_SAMSUNG)
IR_TRACE_PRINTLN(F("Attempting Samsung decode"));
if (decodeSamsung()) {
return true;
}
#endif
/*
* Start of the exotic protocols
*/
#if defined(DECODE_BEO)
IR_TRACE_PRINTLN(F("Attempting Bang & Olufsen decode"));
if (decodeBangOlufsen()) {
return true;
}
#endif
#if defined(DECODE_FAST)
IR_TRACE_PRINTLN(F("Attempting FAST decode"));
if (decodeFAST()) {
return true;
}
#endif
#if defined(DECODE_WHYNTER)
IR_TRACE_PRINTLN(F("Attempting Whynter decode"));
if (decodeWhynter()) {
return true;
}
#endif
#if defined(DECODE_LEGO_PF)
IR_TRACE_PRINTLN(F("Attempting Lego Power Functions"));
if (decodeLegoPowerFunctions()) {
return true;
}
#endif
#if defined(DECODE_BOSEWAVE)
IR_TRACE_PRINTLN(F("Attempting Bosewave decode"));
if (decodeBoseWave()) {
return true;
}
#endif
#if defined(DECODE_MAGIQUEST)
IR_TRACE_PRINTLN(F("Attempting MagiQuest decode"));
if (decodeMagiQuest()) {
return true;
}
#endif
/*
* Try the universal decoder for pulse distance protocols
*/
#if defined(DECODE_DISTANCE_WIDTH)
IR_TRACE_PRINTLN(F("Attempting universal Distance Width decode"));
if (decodeDistanceWidth()) {
return true;
}
#endif
/*
* Last resort is the universal hash decode which always return true
*/
#if defined(DECODE_HASH)
IR_TRACE_PRINTLN(F("Hash decode"));
// decodeHash returns a hash on any input.
// Thus, it needs to be last in the list.
// If you add any decodes, add them before this.
if (decodeHash()) {
return true;
}
#endif
/*
* Return true here, to let the loop decide to call resume or to print raw data.
*/
return true;
}
/**********************************************************************************************************************
* Common decode functions
**********************************************************************************************************************/
/**
* Decode pulse distance width protocols. We only check the mark or space length of a 1, otherwise we always assume a 0!
*
* We can have the following protocol timings
* PULSE_DISTANCE: Pause/spaces have different length and determine the bit value, longer space is 1. Pulses/marks can be constant, like NEC.
* PULSE_WIDTH: Pulses/marks have different length and determine the bit value, longer mark is 1. Pause/spaces can be constant, like Sony.
* PULSE_DISTANCE_WIDTH: Pulses/marks and pause/spaces have different length, often the bit length is constant, like MagiQuest. Can be decoded by PULSE_DISTANCE decoder.
*
* Input is IrReceiver.decodedIRData.rawDataPtr->rawbuf[]
* Output is IrReceiver.decodedIRData.decodedRawData
*
* Assume PULSE_DISTANCE if aOneMarkMicros == aZeroMarkMicros
*
* @param aNumberOfBits Number of bits to decode from decodedIRData.rawDataPtr->rawbuf[] array.
* @param aStartOffset Offset in decodedIRData.rawDataPtr->rawbuf[] to start decoding. Must point to a mark.
* @param aOneMarkMicros Checked if PULSE_WIDTH
* @param aZeroMarkMicros Required for deciding if we have PULSE_DISTANCE.
* @param aOneSpaceMicros Checked if PULSE_DISTANCE.
* @param aMSBfirst If true send Most Significant Bit first, else send Least Significant Bit (lowest bit) first.
* @return true If decoding was successful
*/
bool IRrecv::decodePulseDistanceWidthData(uint_fast8_t aNumberOfBits, IRRawlenType aStartOffset, uint16_t aOneMarkMicros,
uint16_t aOneSpaceMicros, uint16_t aZeroMarkMicros, bool aMSBfirst) {
auto *tRawBufPointer = &decodedIRData.rawDataPtr->rawbuf[aStartOffset];
bool isPulseDistanceProtocol = (aOneMarkMicros == aZeroMarkMicros); // If true, we check aOneSpaceMicros -> pulse distance protocol
IRRawDataType tDecodedData = 0; // For MSB first tDecodedData is shifted left each loop
IRRawDataType tMask = 1UL; // Mask is only used for LSB first
for (uint_fast8_t i = aNumberOfBits; i > 0; i--) {
// get one mark and space pair
unsigned int tMarkTicks;
unsigned int tSpaceTicks;
bool tBitValue;
if (isPulseDistanceProtocol) {
/*
* PULSE_DISTANCE -including PULSE_DISTANCE_WIDTH- here.
* !!!We only check variable length space indicating a 1 or 0!!!
*/
tRawBufPointer++;
tSpaceTicks = *tRawBufPointer++; // maybe buffer overflow for last bit, but we do not evaluate this value :-)
tBitValue = matchSpace(tSpaceTicks, aOneSpaceMicros); // Check for variable length space indicating a 1 or 0
} else {
/*
* PULSE_WIDTH here.
* !!!We only check variable length mark indicating a 1 or 0!!!
*/
tMarkTicks = *tRawBufPointer++;
tBitValue = matchMark(tMarkTicks, aOneMarkMicros); // Check for variable length mark indicating a 1 or 0
tRawBufPointer++;
}
if (aMSBfirst) {
tDecodedData <<= 1;
}
if (tBitValue) {
// It's a 1 -> set the bit
if (aMSBfirst) {
tDecodedData |= 1;
} else {
tDecodedData |= tMask;
}
IR_TRACE_PRINTLN(F("=> 1"));
} else {
// do not set the bit
IR_TRACE_PRINTLN(F("=> 0"));
}
tMask <<= 1;
}
decodedIRData.decodedRawData = tDecodedData;
return true;
}
/*
* Old deprecated version with 7 parameters and unused aZeroSpaceMicros parameter
*/
bool IRrecv::decodePulseDistanceWidthData(uint_fast8_t aNumberOfBits, IRRawlenType aStartOffset, uint16_t aOneMarkMicros,
uint16_t aZeroMarkMicros, uint16_t aOneSpaceMicros, uint16_t aZeroSpaceMicros, bool aMSBfirst) {
(void) aZeroSpaceMicros;
auto *tRawBufPointer = &decodedIRData.rawDataPtr->rawbuf[aStartOffset];
bool isPulseDistanceProtocol = (aOneMarkMicros == aZeroMarkMicros); // If true, we have a constant mark -> pulse distance protocol
IRRawDataType tDecodedData = 0; // For MSB first tDecodedData is shifted left each loop
IRRawDataType tMask = 1UL; // Mask is only used for LSB first
for (uint_fast8_t i = aNumberOfBits; i > 0; i--) {
// get one mark and space pair
unsigned int tMarkTicks;
unsigned int tSpaceTicks;
bool tBitValue;
if (isPulseDistanceProtocol) {
/*
* Pulse distance here, it is not required to check constant mark duration (aOneMarkMicros) and zero space duration.
*/
(void) aZeroSpaceMicros;
tRawBufPointer++;
tSpaceTicks = *tRawBufPointer++; // maybe buffer overflow for last bit, but we do not evaluate this value :-)
tBitValue = matchSpace(tSpaceTicks, aOneSpaceMicros); // Check for variable length space indicating a 1 or 0
} else {
/*
* Pulse width here, it is not required to check (constant) space duration and zero mark duration.
*/
tMarkTicks = *tRawBufPointer++;
tBitValue = matchMark(tMarkTicks, aOneMarkMicros); // Check for variable length mark indicating a 1 or 0
tRawBufPointer++;
}
if (aMSBfirst) {
tDecodedData <<= 1;
}
if (tBitValue) {
// It's a 1 -> set the bit
if (aMSBfirst) {
tDecodedData |= 1;
} else {
tDecodedData |= tMask;
}
IR_TRACE_PRINTLN(F("=> 1"));
} else {
// do not set the bit
IR_TRACE_PRINTLN(F("=> 0"));
}
tMask <<= 1;
}
decodedIRData.decodedRawData = tDecodedData;
return true;
}
/*
* Check for additional required characteristics of timing like length of mark for a constant mark protocol,
* where space length determines the bit value. Requires up to 194 additional bytes of program memory.
* Only sensible for development or very exotic requirements.
* @param aZeroMarkMicros For strict checks
* @param aZeroSpaceMicros For strict checks
*
* Not used yet
*/
bool IRrecv::decodePulseDistanceWidthDataStrict(uint_fast8_t aNumberOfBits, IRRawlenType aStartOffset, uint16_t aOneMarkMicros,
uint16_t aZeroMarkMicros, uint16_t aOneSpaceMicros, uint16_t aZeroSpaceMicros, bool aMSBfirst) {
auto *tRawBufPointer = &decodedIRData.rawDataPtr->rawbuf[aStartOffset];
bool isPulseDistanceProtocol = (aOneMarkMicros == aZeroMarkMicros); // If true, we have a constant mark -> pulse distance protocol
IRRawDataType tDecodedData = 0; // For MSB first tDecodedData is shifted left each loop
IRRawDataType tMask = 1UL; // Mask is only used for LSB first
for (uint_fast8_t i = aNumberOfBits; i > 0; i--) {
// get one mark and space pair
unsigned int tMarkTicks;
unsigned int tSpaceTicks;
bool tBitValue;
if (isPulseDistanceProtocol) {
/*
* PULSE_DISTANCE here, it is not required to check constant mark duration (aOneMarkMicros) and zero space duration.
*/
tMarkTicks = *tRawBufPointer++;
tSpaceTicks = *tRawBufPointer++; // maybe buffer overflow for last bit, but we do not evaluate this value :-)
tBitValue = matchSpace(tSpaceTicks, aOneSpaceMicros); // Check for variable length space indicating a 1 or 0
// Check for constant length mark
if (!matchMark(tMarkTicks, aOneMarkMicros)) {
#if defined(LOCAL_DEBUG)
Serial.print(F("Mark="));
Serial.print(tMarkTicks * MICROS_PER_TICK);
Serial.print(F(" is not "));
Serial.print(aOneMarkMicros);
Serial.print(F(". Index="));
Serial.print(aNumberOfBits - i);
Serial.print(' ');
#endif
return false;
}
} else {
/*
* PULSE_DISTANCE -including PULSE_DISTANCE_WIDTH- here.
* !!!We only check variable length mark indicating a 1 or 0!!!
* It is not required to check space duration and zero mark duration.
*/
tMarkTicks = *tRawBufPointer++;
tBitValue = matchMark(tMarkTicks, aOneMarkMicros); // Check for variable length mark indicating a 1 or 0
tSpaceTicks = *tRawBufPointer++; // maybe buffer overflow for last bit, but we do not evaluate this value :-)
}
if (aMSBfirst) {
tDecodedData <<= 1;
}
if (tBitValue) {
// It's a 1 -> set the bit
if (aMSBfirst) {
tDecodedData |= 1;
} else {
tDecodedData |= tMask;
}
IR_TRACE_PRINTLN(F("=> 1"));
} else {
/*
* Additionally check length of tSpaceTicks parameter for PULSE_DISTANCE or tMarkTicks for PULSE_WIDTH
* which determine a zero
*/
if (isPulseDistanceProtocol) {
if (!matchSpace(tSpaceTicks, aZeroSpaceMicros)) {
#if defined(LOCAL_DEBUG)
Serial.print(F("Space="));
Serial.print(tSpaceTicks * MICROS_PER_TICK);
Serial.print(F(" is not "));
Serial.print(aOneSpaceMicros);
Serial.print(F(" or "));
Serial.print(aZeroSpaceMicros);
Serial.print(F(". Index="));
Serial.print(aNumberOfBits - i);
Serial.print(' ');
#endif
return false;
}
} else {
if (!matchMark(tMarkTicks, aZeroMarkMicros)) {
#if defined(LOCAL_DEBUG)
Serial.print(F("Mark="));
Serial.print(tMarkTicks * MICROS_PER_TICK);
Serial.print(F(" is not "));
Serial.print(aOneMarkMicros);
Serial.print(F(" or "));
Serial.print(aZeroMarkMicros);
Serial.print(F(". Index="));
Serial.print(aNumberOfBits - i);
Serial.print(' ');
#endif
return false;
}
}
// do not set the bit
IR_TRACE_PRINTLN(F("=> 0"));
}
// If we have no stop bit, assume that last space, which is not recorded, is correct, since we can not check it
if (aZeroSpaceMicros == aOneSpaceMicros
&& tRawBufPointer < &decodedIRData.rawDataPtr->rawbuf[decodedIRData.rawDataPtr->rawlen]) {
// Check for constant length space (of pulse width protocol) here
if (!matchSpace(tSpaceTicks, aOneSpaceMicros)) {
#if defined(LOCAL_DEBUG)
Serial.print(F("Space="));
Serial.print(tSpaceTicks * MICROS_PER_TICK);
Serial.print(F(" is not "));
Serial.print(aOneSpaceMicros);
Serial.print(F(". Index="));
Serial.print(aNumberOfBits - i);
Serial.print(' ');
#endif
return false;
}
}
tMask <<= 1;
}
decodedIRData.decodedRawData = tDecodedData;
return true;
}
/**
* Decode pulse distance protocols for PulseDistanceWidthProtocolConstants.
* @return true if decoding was successful
*/
bool IRrecv::decodePulseDistanceWidthData(PulseDistanceWidthProtocolConstants *aProtocolConstants, uint_fast8_t aNumberOfBits,
IRRawlenType aStartOffset) {
return decodePulseDistanceWidthData(aNumberOfBits, aStartOffset, aProtocolConstants->DistanceWidthTimingInfo.OneMarkMicros,
aProtocolConstants->DistanceWidthTimingInfo.OneSpaceMicros, aProtocolConstants->DistanceWidthTimingInfo.ZeroMarkMicros,
aProtocolConstants->Flags);
}
/*
* Static variables for the getBiphaselevel function
*/
uint_fast8_t sBiphaseDecodeRawbuffOffset; // Index into raw timing array
uint16_t sBiphaseCurrentTimingIntervals; // 1, 2 or 3. Number of aBiphaseTimeUnit intervals of the current rawbuf[sBiphaseDecodeRawbuffOffset] timing.
uint_fast8_t sBiphaseUsedTimingIntervals; // Number of already used intervals of sCurrentTimingIntervals.
uint16_t sBiphaseTimeUnit;
void IRrecv::initBiphaselevel(uint_fast8_t aRCDecodeRawbuffOffset, uint16_t aBiphaseTimeUnit) {
sBiphaseDecodeRawbuffOffset = aRCDecodeRawbuffOffset;
sBiphaseTimeUnit = aBiphaseTimeUnit;
sBiphaseUsedTimingIntervals = 0;
}
/**
* Gets the level of one time interval (aBiphaseTimeUnit) at a time from the raw buffer.
* The RC5/6 decoding is easier if the data is broken into time intervals.