-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSender6.ino
1561 lines (1396 loc) · 49.7 KB
/
Sender6.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
/*
* Project: Sender6 (Ding18)
* Description:
* - Send a message, when my washing machine is finished (when no shaking is detected for a longer period at my over 20 year old Gorenje WA1141 machine)
*
* License: 2-Clause BSD License
* Copyright (c) 2024 codingABI
* For details see: License.txt
*
* created by codingABI https://github.com/codingABI/SenderReceiver/#sender-6-433-mhz-lora
*
* Used external libraries from Arduino IDE Library Manager
* - LoRa (by Sandeep Mistry)
* - Adafruit MPU6050 (by Adafruit)
* - Adafruit SSD1306 (by Adafruit)
* - Adafruit Unified Sensor (by Adafruit)
* - TFT_eSPI (by Bodmer) for fonts
* Used external libraries from GitHub
* - KY040 (https://github.com/codingABI/KY040 by codingABI)
*
* Hardware:
* - Microcontroller ESP32 LOLIN32
* - MPU6050 accelerometer and gyroscope
* - SSD1306 OLED 128x32 pixel
* - KY-040 rotary encoder
* - SX1278 LoRa Ra-02
* - 3.7V 330mAh Li-Ion battery
* - Two resistors (47k, 100k) for a voltage divider
*
* Current consumption (measured on battery, LED from gyro sensor was removed):
* a) 21 mA in menu selection
* b) 4mA in minimal display mode while waiting for motions
* c) 26 mA in maximal display mode while waiting for motions
* d) 140 mA for the short time, while sending the LoRa signal
* e) In a), c) and d) +20mA, if Serial is enabled (because cpu clock must be higher)
*
* Keep in mind: The ESP32 LOLIN32 (at least mine) has
* - no overdischarge protection! Charge battery or switch off the device when battery is low
* or use a battery with builtin overdischarge protection
* - no voltage step up converter and only a 3.3V linear voltage regulator => Only the battery voltage ~3.4-4.1V can be used
* => Runtime with 3.7V/330mAh battery ~5-10h
*
* Buzzer-Codes
* - 1xShort beep = A button was pressed
* - 1xStandard beep = User input timed out
* - 1xLaser beep = Begin of normal device start/power on
* - 1xLong beep = Error (If critical, the device will be reset)
* - 2xLong beep = A previous WDT reset was detected
* - 1xHigh short beep = LoRa-Signal sent, but no response from receiver
*
* History:
* 20230510, Initial version
* 20230519, Add language strings for EN
* 20230521, Do not goto deep sleep, if motions are continuous
* 20230622, Fix wrong timeout caused by 20230521
* 20230706, Fix bug where device does not store threshold and timeout in EEPROM
* 20231030, Adjust low battery warning level and improve full charge detection
* 20231102, Use spare pin 27 to detect switched off battery
* 20241013, Update arduino-esp32 from 2.0.16 to 3.0.5 (IDF 5.1.4) => Changes needed for WDT and ledc
* 20241013, Replace NewEncoder-Library with KY040
*/
#include <KY040.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_SSD1306.h>
#include <Wire.h>
#include <Fonts/FreeSans18pt7b.h>
#include <Fonts/FreeSans12pt7b.h>
#include <Fonts/FreeSans9pt7b.h>
#include <EEPROM.h>
#include <LoRa.h>
#include <esp_task_wdt.h>
#include <rom/rtc.h>
#define RCSIGNATURE 0b00111000000000000000000000000000UL // Signature for signals (only the first 5 bits are the signature)
#define ID 6
/* Signal (32-bit):
* 5 bit: Signature
* 3 bit: ID
* 1 bit: Low battery
* 6 bit: Vcc (0-63)
* 9 bit: unused
* 8 bit: type of message (0=STARTMESSAGE, 1=ENDMESSAGE, 2=TESTMESSAGE)
*/
// Set display language to DE or EN
//#define DISPLAYLANGUAGE_DE
#define DISPLAYLANGUAGE_EN
#include "displayLanguage.h"
#define EEPROM_SIGNATURE 18 // First byte at startaddress in EEPROM
#define EEPROM_VERSION 2 // Second byte at startaddress in EEPROM
#define EEPROM_STARTADDR 0 // Startaddress in EEPROM
#define EEPROM_SIZE 64 // Size of EEPROM area
/* Send low battery warning, when voltage <= this value
* Note: My ESP32 LOLIN32 has no battery overdischarge protection and
* only a 3.3V linear voltage regulator (Dropout voltage ~0.12V)
*/
#define LOWBATWARNING 3.6f
#define LOWBATWARNINGHYSTERESIS 0.02f
// I2C for OLED display and gyroscope
#define SDA_PIN 32
#define SCL_PIN 33
// MPU irq (used for deep sleep wake up)
#define MPU_IRQ 36
// Pin for passive buzzer
#define BUZZER_PIN 25
// Battery powerswitch pin (LOW if powerswitch is OFF, Floating if ON)
#define POWERSWITCH_PIN 27
// Rotary encoder
#define ROTARY_DT_PIN 17 // rotary DT
#define ROTARY_CLK_PIN 5 // rotary CLK
#define ROTARY_SW_PIN GPIO_NUM_39 // rotary button
// I use pollings for button pin 39 and no interrupt handling, because operations like analogRead or interrupts on pins 36 and 34 makes interrupt troubles
// (perhaps related "When the power switch which controls the temperature sensor, SARADC1 sensor, SARADC2 sensor, AMP sensor, or HALL sensor, is turned on, the inputs of GPIO36 and GPIO39 will be pulled down for about 80 ns" or https://esp32.com/viewtopic.php?t=14087)
// Analog pin to measure the battery/loader voltage
#define VBAT_PIN 34
// LoRa
#define MOSI_PIN 23 // SPI MOSI
#define MISO_PIN 19 // SPI MISO
#define SCK_PIN 18 // SPI SCK/CLK
#define LORA_RST_PIN 4
#define LORA_NSS_PIN 26
#define LORA_IRQ_PIN 35 // DIO0
// OLED display
#define OLED_RESET -1 // no reset pin
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
Adafruit_SSD1306 g_display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define OVERVIEWGAP 8 // Distance between overview dots
#define USERTIMEOUTMS 60000 // Set timeout in MS for user inputs
#define BUTTONDEBOUNCEMS 200 // Button debounce time in MS
#define WDTTIMEOUT 10 // WDT timeout in seconds
#define INVERTTIMEMS 500 // time range in MS to invert display after setting a value
// Menu items
enum menuItems { MENUSTART, MENUBATTERY, MENUTIMEOUT, MENUTHRESHOLD, MENUDISPLAY, MENUSOUND, MENUSERIAL, MENULORATEST, MENUINFOS, MENURESET, MENURESTART, MAXMENUITEMS};
// Display modes
enum displayModes { MODEMINIMAL, MODEMAXIMAL, MAXDISPLAYMODES};
// Pages for the information menu item
enum infoPages {
PAGEAPP,
PAGEMAC,
PAGECHIP,
PAGEIDF,
PAGECOMPILEDATE,
PAGECOMPILETIME,
PAGEUPTIME,
PAGEMPU,
PAGEANALOG,
PAGEFREEHEAP,
PAGETOP,
MAXINFOPAGES
};
/*
* Simple sprite to show waiting state or detecting a motion
* made with https://www.piskelapp.com/p/create/sprite
* and converted by https://javl.github.io/image2cpp/
*/
#define SPRITE_WIDTH 16
#define SPRITE_HEIGHT 16
#define MAXFRAMES 8
RTC_DATA_ATTR byte g_currentSpriteFrame = 0;
const byte g_sprite[MAXFRAMES][SPRITE_WIDTH*2] = {
{ 0x00, 0x00, 0x07, 0x00, 0x0f, 0x00, 0x18, 0x00, 0x30, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00,
0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x30, 0x00, 0x10, 0x00, 0x08, 0x40, 0x05, 0x00, 0x00, 0x00},
{ 0x00, 0x00, 0x07, 0xe0, 0x0f, 0xf0, 0x18, 0x10, 0x30, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00,
0x20, 0x00, 0x20, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00},
{ 0x00, 0x00, 0x07, 0xe0, 0x0f, 0xf0, 0x18, 0x18, 0x20, 0x0c, 0x40, 0x06, 0x00, 0x06, 0x40, 0x06,
0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{ 0x00, 0x00, 0x00, 0xe0, 0x03, 0xf0, 0x08, 0x18, 0x00, 0x0c, 0x20, 0x06, 0x00, 0x06, 0x00, 0x06,
0x00, 0x06, 0x00, 0x06, 0x00, 0x06, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{ 0x00, 0x00, 0x00, 0xa0, 0x02, 0x10, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x06, 0x00, 0x06, 0x00, 0x06,
0x00, 0x06, 0x00, 0x06, 0x00, 0x06, 0x00, 0x0c, 0x00, 0x18, 0x00, 0xf0, 0x00, 0xe0, 0x00, 0x00},
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04,
0x00, 0x06, 0x00, 0x06, 0x00, 0x06, 0x00, 0x0c, 0x08, 0x18, 0x0f, 0xf0, 0x07, 0xe0, 0x00, 0x00},
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
0x60, 0x02, 0x60, 0x00, 0x60, 0x02, 0x30, 0x04, 0x18, 0x18, 0x0f, 0xf0, 0x07, 0xe0, 0x00, 0x00},
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00,
0x60, 0x00, 0x60, 0x00, 0x60, 0x04, 0x30, 0x00, 0x18, 0x10, 0x0f, 0xc0, 0x07, 0x00, 0x00, 0x00}};
/*
* Simple icons
* made with https://www.piskelapp.com/p/create/sprite
* and converted by https://javl.github.io/image2cpp/
*/
#define ICON_WIDTH 16
#define ICON_HEIGHT 16
enum icons { ICONAUDIOON, ICONAUDIOOFF, ICONOK, MAXICONS};
const byte g_icon[MAXICONS][ICON_WIDTH*2] = {
{ 0x00, 0x00, 0x00, 0x30, 0x00, 0x70, 0x00, 0xf0, 0x01, 0xf0, 0x0f, 0xb0, 0x1f, 0x30, 0x18, 0x30,
0x18, 0x30, 0x1f, 0x30, 0x0f, 0xb0, 0x01, 0xf0, 0x00, 0xf0, 0x00, 0x70, 0x00, 0x30, 0x00, 0x00},
{ 0xc0, 0x01, 0x60, 0x33, 0x30, 0x76, 0x18, 0xec, 0x0d, 0xd8, 0x06, 0xb0, 0x1b, 0x60, 0x19, 0xd0,
0x19, 0xd0, 0x1b, 0x60, 0x06, 0xb0, 0x0d, 0xd8, 0x18, 0xec, 0x30, 0x76, 0x60, 0x33, 0xc0, 0x01},
{ 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x0c, 0x00, 0x0c, 0x00, 0x18, 0x00, 0x18, 0x00, 0x30,
0x00, 0x30, 0x00, 0x60, 0x18, 0x60, 0x0c, 0xc0, 0x06, 0xc0, 0x03, 0x80, 0x01, 0x80, 0x00, 0x00}
};
Adafruit_MPU6050 g_mpu; // MPU6050 accelerometer and gyroscope
byte g_motionThreshold; // Threshold for motion detection (1 = very sensible, 255 is minimal sensible)
unsigned long g_idleTimeTimeoutS; // Timeout in seconds after that the LoRa message will be sent, when no acceleration/motion is detected
byte g_displayMode; // 0 = Minimal/Default, 1 = Maximal/Debug
bool g_soundEnabled; // Enables the buzzer sound
bool g_serialEnabled; // Enables Serial... but need more power due higher cpu frequency
#define SERIALDEBUG if (g_serialEnabled) Serial
bool g_detectionActive = false; // Show detection of a acceleration/motion on screen
RTC_DATA_ATTR unsigned long g_lastIdleStartTimeS = 0; // Time of last idle time begin
bool g_wakeUpByButton = false; // Deep sleep wake up by button?
bool g_wakeUpByMPU = false; // Deep sleep wake up by mpu?
volatile bool v_loraReceived = false; // Lora IRQ triggered?
float g_vBat; // Current battery/loader voltage
RTC_DATA_ATTR bool g_firstBoot = true; // Used to distinguish between a normal device startup and deep sleep wake ups
KY040 g_rotaryEncoder(ROTARY_CLK_PIN,ROTARY_DT_PIN); // Rotary encoder
volatile int v_rotaryValue=0; // Rotary encoder value (will be set in ISR)
// List of longest idle times
#define MAXTIMEHISTORY 4
RTC_DATA_ATTR unsigned long g_idleTimeSHistory[MAXTIMEHISTORY]; // List of longest time in seconds without an acceleration
enum beepTypes { DEFAULTBEEP, SHORTBEEP, LONGBEEP, HIGHSHORTBEEP, LASER };
enum messageTypes { STARTMESSAGE, ENDMESSAGE, TESTMESSAGE };
// ISR for rotary encoder to handle the interrupts for CLK and DT
void ISR_rotaryEncoder() {
// Process pin states for CLK and DT
switch (g_rotaryEncoder.getRotation()) {
case KY040::CLOCKWISE:
v_rotaryValue++;
break;
case KY040::COUNTERCLOCKWISE:
v_rotaryValue--;
break;
}
}
// Draw current frame of sprite
void drawSprite(int x, int y, int speedDelayMS=50) {
static unsigned long lastSpriteChangeMS = 0;
// Draw sprite pixels
for (int i=0;i<SPRITE_HEIGHT;i++) { // every sprite line
for (int j=0;j<2;j++) { // every 8 pixel per line (<SPRITE_WIDTH/8)
byte value = g_sprite[g_currentSpriteFrame][(i<<1) + j];
for (int k=0;k<8;k++) { // check bits from msb to lsb
if (value & (0b10000000>>k)) {
g_display.drawPixel(x+(j<<3)+k,y+i,WHITE);
}
}
}
}
// Goto next frame, when needed
if ((lastSpriteChangeMS == 0) || (millis()-lastSpriteChangeMS > speedDelayMS)) {
g_currentSpriteFrame++;
if (g_currentSpriteFrame>=MAXFRAMES) g_currentSpriteFrame = 0;
lastSpriteChangeMS = millis();
}
}
// Draw current frame of sprite
void drawIcon(int x, int y, byte icon) {
if (icon >= MAXICONS) {
SERIALDEBUG.print("Unknown icon ");
SERIALDEBUG.println(icon);
return;
}
// Draw sprite pixels
for (int i=0;i<ICON_HEIGHT;i++) { // every sprite line
for (int j=0;j<2;j++) { // every 8 pixel per line
byte value = g_icon[icon][(i<<1) + j];
for (int k=0;k<8;k++) { // check bits from msb to lsb
if (value & (0b10000000>>k)) {
g_display.drawPixel(x+(j<<3)+k,y+i,WHITE);
}
}
}
}
}
// Call back for LoRa in receiver mode
void callbackLoraReceived(int packetSize) {
if (packetSize == 0) return;
v_loraReceived = true;
}
// Get deep sleep capable runtime
int64_t getRunTimeS() {
struct timeval current_time;
gettimeofday(¤t_time, NULL);
return (current_time.tv_sec);
}
// Buzzer
void beep(int type=DEFAULTBEEP) {
if (!g_soundEnabled) return;
// User PWM to improve quality
switch(type) {
case DEFAULTBEEP: // 500 Hz for 200ms
ledcAttach(BUZZER_PIN,500,8);
ledcWrite(BUZZER_PIN, 128);
delay(200);
ledcWrite(BUZZER_PIN, 0);
ledcDetach(BUZZER_PIN);
break;
case SHORTBEEP: // 1 kHz for 100ms
ledcAttach(BUZZER_PIN,1000,8);
ledcWrite(BUZZER_PIN, 128);
delay(100);
ledcWrite(BUZZER_PIN, 0);
ledcDetach(BUZZER_PIN);
break;
case LONGBEEP: // 250 Hz for 400ms
ledcAttach(BUZZER_PIN,250,8);
ledcWrite(BUZZER_PIN, 128);
delay(400);
ledcWrite(BUZZER_PIN, 0);
ledcDetach(BUZZER_PIN);
break;
case HIGHSHORTBEEP: { // High and short beep
ledcAttach(BUZZER_PIN,5000,8);
ledcWrite(BUZZER_PIN, 128);
delay(100);
ledcWrite(BUZZER_PIN, 0);
ledcDetach(BUZZER_PIN);
break;
}
case LASER: { // Laser like sound
int i = 5000; // Start frequency in Hz (goes down to 300 Hz)
int j = 300; // Start duration in microseconds (goes up to 5000 microseconds)
ledcAttach(BUZZER_PIN,i,8);
while (i>300) {
i -=50;
j +=50;
ledcWriteTone(BUZZER_PIN,i);
delayMicroseconds(j+1000);
}
ledcDetach(BUZZER_PIN);
break;
}
default: {
SERIALDEBUG.print("Unknown beep type ");
SERIALDEBUG.println(type);
}
}
esp_task_wdt_reset();
}
// Center text on screen
void centerText(char *strData, int offsetY=0, int offsetX=0) {
int16_t x, y;
uint16_t w, h;
g_display.getTextBounds(strData, 0, 0, &x, &y, &w, &h);
g_display.setCursor((SCREEN_WIDTH-w)/2+offsetX,(SCREEN_HEIGHT-y)/2+offsetY);
g_display.print(strData);
}
// Show current timeout value on the configuration screen
void showTimeout() {
#define MAXSTRDATALENGTH 80
char strData[MAXSTRDATALENGTH+1];
g_display.setFont();
g_display.setCursor(0,0);
g_display.print(STR_IDLETIMEINSECONDS);
g_display.setFont(&FreeSans12pt7b);
snprintf(strData,MAXSTRDATALENGTH+1,"%lu",g_idleTimeTimeoutS);
g_display.setCursor(0,SCREEN_HEIGHT-2);
g_display.print(strData);
}
// Show current sensor threshold value on the configuration screen
void showThreshold() {
#define MAXSTRDATALENGTH 80
char strData[MAXSTRDATALENGTH+1];
g_display.setFont();
g_display.setCursor(0,0);
g_display.print(STR_SENSORTHRESHOLD);
g_display.setFont(&FreeSans12pt7b);
snprintf(strData,MAXSTRDATALENGTH+1,"%i",g_motionThreshold);
g_display.setCursor(0,SCREEN_HEIGHT-2);
g_display.print(strData);
}
// Show device infos
void showInfos(byte page) {
static int lastVbat;
static unsigned long lastUpdateVbatMS=0;
sensors_event_t a, g, temp;
#define MAXSTRDATALENGTH 80
char strData[MAXSTRDATALENGTH+1];
if (page >= MAXINFOPAGES) {
SERIALDEBUG.print("Unknown info page ");
SERIALDEBUG.println(page);
return;
}
// Enable mpu, if needed
if (page == PAGEMPU) g_mpu.enableSleep(false); else g_mpu.enableSleep(true);
g_display.setFont();
g_display.setCursor(0,0);
switch (page) {
case PAGEAPP: {
g_display.print("Sender6 (Ding18)");
g_display.setFont(&FreeSans9pt7b);
g_display.setCursor(0,SCREEN_HEIGHT-8-1);
g_display.print("(c) codingABI");
break;
}
case PAGEMAC: {
g_display.print("Mac address");
g_display.setCursor(0,16);
for (int i=0;i<6;i++) { // Build mac from chip id
byte part = ((ESP.getEfuseMac() >> (i*8)) & 0xff);
snprintf(strData,MAXSTRDATALENGTH+1,"%02X",part);
g_display.print(strData);
if (i < 5) g_display.print(":");
}
break;
}
case PAGECHIP: {
g_display.print("Chip model");
g_display.setCursor(0,16);
g_display.print(ESP.getChipModel());
break;
}
case PAGEIDF: {
g_display.print("IDF");
g_display.setFont(&FreeSans9pt7b);
g_display.setCursor(0,SCREEN_HEIGHT-7);
g_display.print(ESP.getSdkVersion());
break;
}
case PAGECOMPILEDATE: {
g_display.print("Compile date");
g_display.setFont(&FreeSans9pt7b);
g_display.setCursor(0,SCREEN_HEIGHT-7);
g_display.print(__DATE__);
break;
}
case PAGECOMPILETIME: {
g_display.print("Compile time");
g_display.setFont(&FreeSans9pt7b);
g_display.setCursor(0,SCREEN_HEIGHT-7);
g_display.print(__TIME__);
break;
}
case PAGEUPTIME: {
g_display.print("Uptime");
g_display.setFont(&FreeSans9pt7b);
g_display.setCursor(0,SCREEN_HEIGHT-7);
g_display.print(getRunTimeS());
g_display.print("s");
break;
}
case PAGEMPU: {
g_display.setCursor(SCREEN_WIDTH-25,0);
g_display.print("MPU");
g_display.setCursor(0,0);
g_mpu.getEvent(&a, &g, &temp);
snprintf(strData,MAXSTRDATALENGTH+1,"X=%5.1f m/s%c",a.acceleration.x,char(252));
g_display.println(strData);
snprintf(strData,MAXSTRDATALENGTH+1,"Y=%5.1f m/s%c",a.acceleration.y,char(252));
g_display.println(strData);
snprintf(strData,MAXSTRDATALENGTH+1,"Z=%5.1f m/s%c",a.acceleration.z,char(252));
g_display.println(strData);
g_display.setCursor(SCREEN_WIDTH/2+16,16);
snprintf(strData,MAXSTRDATALENGTH+1,"T=%2i C%c",(int) round(temp.temperature),char(247));
g_display.println(strData);
break;
}
case PAGEANALOG: {
if (millis() - lastUpdateVbatMS > 500) { // Prevent too fast readings from analog pin
lastVbat = analogRead(VBAT_PIN);
lastUpdateVbatMS = millis();
}
g_display.print("Analog pin ");
g_display.print(VBAT_PIN);
g_display.setFont(&FreeSans9pt7b);
g_display.setCursor(0,SCREEN_HEIGHT-7);
g_display.print(lastVbat);
break;
}
case PAGEFREEHEAP: {
g_display.print("Free heap bytes");
g_display.setFont(&FreeSans9pt7b);
g_display.setCursor(0,SCREEN_HEIGHT-7);
g_display.print(ESP.getFreeHeap());
break;
}
case PAGETOP: {
g_display.print("Top idle times");
g_display.setCursor(0,12);
if (MAXTIMEHISTORY < 4) { // We need 4 history items for the info page
SERIALDEBUG.println("MAXTIMEHISTORY less than 4");
return;
}
#define DAYINSECS (3600*24)
if (g_idleTimeSHistory[0] > 10*DAYINSECS) {
snprintf(strData,MAXSTRDATALENGTH+1,"%i:%6lud %i:%6lud",1,g_idleTimeSHistory[0]/DAYINSECS,3,g_idleTimeSHistory[2]/DAYINSECS);
g_display.println(strData);
snprintf(strData,MAXSTRDATALENGTH+1,"%i:%6lud %i:%6lud",2,g_idleTimeSHistory[1]/DAYINSECS,4,g_idleTimeSHistory[3]/DAYINSECS);
g_display.print(strData);
} else {
snprintf(strData,MAXSTRDATALENGTH+1,"%i:%6lus %i:%6lus",1,g_idleTimeSHistory[0],3,g_idleTimeSHistory[2]);
g_display.println(strData);
snprintf(strData,MAXSTRDATALENGTH+1,"%i:%6lus %i:%6lus",2,g_idleTimeSHistory[1],4,g_idleTimeSHistory[3]);
g_display.print(strData);
}
break;
}
default:SERIALDEBUG.println("Unknown info page");return;
}
}
// Init device settings
void initSettings() {
g_motionThreshold = 5;
g_idleTimeTimeoutS = 120;
g_displayMode = 0;
g_serialEnabled = false;
g_soundEnabled = true;
}
// Save device settings to EEPROM
void saveSettings() {
SERIALDEBUG.println("Write settings to EEPROM");
int addr = EEPROM_STARTADDR;
// Save values in EEPROM
EEPROM.writeByte(addr,EEPROM_SIGNATURE);
addr+=sizeof(byte);
EEPROM.writeByte(addr,EEPROM_VERSION);
addr+=sizeof(byte);
EEPROM.writeByte(addr, g_motionThreshold);
addr+=sizeof(byte);
EEPROM.writeByte(addr, g_displayMode);
addr+=sizeof(byte);
EEPROM.writeByte(addr,(g_serialEnabled)?1:0);
addr+=sizeof(byte);
EEPROM.writeByte(addr,(g_soundEnabled)?1:0);
addr+=sizeof(byte);
EEPROM.writeULong(addr, g_idleTimeTimeoutS);
EEPROM.commit();
}
// Send LoRa signal
bool sendLoRa(unsigned long data) {
#define MAXSTRDATALENGTH 80
char strData[MAXSTRDATALENGTH+1];
unsigned long startWaitMS;
bool responseOK;
unsigned long received;
char* strPtr;
#define MAXRETRIES 3
#define RESPONSETIMEOUTMS 2000
SERIALDEBUG.print("Sending ");
SERIALDEBUG.println(data,BIN);
snprintf(strData,MAXSTRDATALENGTH+1,STR_LORAPACKET);
for (int i=0;i < MAXRETRIES;i++){
LoRa.beginPacket();
LoRa.print(data);
LoRa.endPacket();
// Wait for response
LoRa.receive();
startWaitMS = millis();
responseOK = false;
do {
esp_task_wdt_reset();
g_display.clearDisplay();
g_display.setFont(&FreeSans9pt7b);
centerText(strData,0,-SPRITE_WIDTH/2);
drawSprite(SCREEN_WIDTH-SPRITE_WIDTH-1,(SCREEN_HEIGHT-SPRITE_HEIGHT)/2-1);
g_display.display();
if (v_loraReceived) {
v_loraReceived = false;
while (LoRa.available()) {
String LoRaData = LoRa.readString();
received = strtoul (LoRaData.c_str(),&strPtr,10);
if ((0xfffffffful ^ received)== data) { // XOR response
SERIALDEBUG.println("Response received");
responseOK = true;
}
}
}
} while ((millis() - startWaitMS < RESPONSETIMEOUTMS) && !responseOK);
if (!responseOK) {
SERIALDEBUG.println("Response timeout");
beep(HIGHSHORTBEEP);
} else {
break; // Exit for loop
}
}
LoRa.sleep();
esp_task_wdt_reset();
return(responseOK);
}
// Low battery detection
bool isBatteryLow() {
static bool lowBat = false;
if (g_vBat <=LOWBATWARNING) lowBat = true;
if (g_vBat > LOWBATWARNING + LOWBATWARNINGHYSTERESIS) lowBat = false;
return lowBat;
}
/* Full battery detection
* This is not easy and 100% reliable because my ESP32 LOLIN32
* has no way to communicate with the battery loader
* => Try to detect full charge via voltage history
* My ESP32 LOLIN32 increases the charging voltage to 4.13V
* and when the battery is full the voltage drops down to ~4.08V
* Additionally assume full battery when voltage is ]4.0V,4.1V[
* for a longer period without significant changes
*/
bool isBatteryFull(bool reset=false) {
#define SAMPLEINTERVALMS 60000
#define MAXSAMPLES 5
static float samples[MAXSAMPLES]; // FIFO
static int currentSample = 0;
static unsigned long lastSampleMS = 0;
static float peakVoltage = 0.0f;
float maxSample;
float minSample;
if (reset) { // Reset voltage statistics
for (int i=0;i<MAXSAMPLES;i++) samples[i] = 0.0f;
currentSample = 0;
lastSampleMS = millis()-SAMPLEINTERVALMS-1;
peakVoltage = 0.0f;
}
if (g_vBat < 4.0f) peakVoltage = 0.0f;
if (g_vBat > peakVoltage) peakVoltage = g_vBat;
// While charging the voltage increased up to 4.13V
// and when the battery is full the voltage drops down to ~4.08V
if ((peakVoltage >= 4.1f) && (g_vBat < 4.1f) && (g_vBat > 4.0f)) return true;
if (millis()-lastSampleMS > SAMPLEINTERVALMS) {
// Fill FIFO voltage history
samples[currentSample] = g_vBat;
if (currentSample < MAXSAMPLES-1) currentSample++; else currentSample=0;
lastSampleMS = millis();
}
// Get min/max voltage values
#define INIT 99
maxSample = -INIT;
minSample = INIT;
for (int i=0;i<MAXSAMPLES;i++) {
if (samples[i] > maxSample) maxSample = samples[i];
if (samples[i] < minSample) minSample = samples[i];
}
if ((minSample != -INIT) && (maxSample != INIT)
&& (maxSample >= minSample)) {
// Assume full battery when voltage is ]4.0V,4.1V[ for a longer period without significant changes
if ((minSample > 4.0f) && (minSample < 4.1f) && (maxSample - minSample < 0.01f)) {
return true;
}
}
return false;
}
// Reset statistics for rough full battery detection
void resetBatteryFullStatistics() {
isBatteryFull(true);
}
// Send LoRa testsignal
void sendLoRaTest() {
#define MAXSTRDATALENGTH 80
char strData[MAXSTRDATALENGTH+1];
if (sendLoRa(RCSIGNATURE +
(((unsigned long) ID & 7) << 24) +
((unsigned long) (g_vBat <= LOWBATWARNING) << 23) +
((((unsigned long) round(g_vBat*10))&63) << 17) +
TESTMESSAGE)) {
snprintf(strData,MAXSTRDATALENGTH+1,STR_CONFIRMED);
} else {
snprintf(strData,MAXSTRDATALENGTH+1,STR_SENT);
}
g_display.clearDisplay();
g_display.setFont(&FreeSans9pt7b);
centerText(strData);
g_display.display();
delay(2000);
esp_task_wdt_reset();
}
// Show battery/loader voltage without input timeout
void batteryView() {
#define MAXSTRDATALENGTH 80
char strData[MAXSTRDATALENGTH+1];
bool exitLoop = false;
bool lowBatBeepDone = false;
// Enable powerswitch pin
pinMode(POWERSWITCH_PIN,INPUT_PULLUP);
updateVbat();
resetBatteryFullStatistics(); // Reset voltage statistics
do {
esp_task_wdt_reset();
updateVbat();
snprintf(strData,MAXSTRDATALENGTH+1,"%.2fV",g_vBat);
g_display.clearDisplay();
g_display.setFont();
g_display.setCursor(0,0);
g_display.print(STR_VBATLOADER);
if (digitalRead(POWERSWITCH_PIN)) { // Battery powerswitch: On
// Low battery warning
if (isBatteryLow()) {
if ((millis()/1000) & 1) { // Blinking text
g_display.setCursor(SCREEN_WIDTH-1-strlen(STR_EMPTY)*6,SCREEN_HEIGHT-1-8);
g_display.print(STR_EMPTY);
}
if (!lowBatBeepDone) { // Beep only once
beep(LONGBEEP);
lowBatBeepDone = true;
}
}
// Full battery
if (isBatteryFull()) {
g_display.setCursor(SCREEN_WIDTH-1-strlen(STR_FULL)*6,SCREEN_HEIGHT-1-8);
g_display.print(STR_FULL);
}
} else { // Battery powerswitch: Off
snprintf(strData,MAXSTRDATALENGTH+1,"%s",STR_OFF);
}
g_display.setFont(&FreeSans12pt7b);
g_display.setCursor(0,SCREEN_HEIGHT-1);
g_display.print(strData);
g_display.display();
if (digitalRead(ROTARY_SW_PIN)==LOW) {
g_display.clearDisplay();
g_display.display();
beep(SHORTBEEP);
while (digitalRead(ROTARY_SW_PIN)==LOW) esp_task_wdt_reset(); // Wait for button release
delay(BUTTONDEBOUNCEMS); // Debounce
exitLoop = true;
}
} while (!exitLoop);
// Disable powerswitch pin
pinMode(POWERSWITCH_PIN,INPUT);
}
// Change dualstate option
void changeSetting(byte menuItem) {
#define MAXSTRDATALENGTH 80
char strData[MAXSTRDATALENGTH+1];
enum options { OPTIONLEFT, OPTIONRIGHT, MAXOPTIONS };
unsigned long lastInteractMS; // Last interaction time to detect timeout
bool exitLoop = false;
bool selection = false;
int currentOption = 0;
int maxOptions;
int lastRotaryValue;
int rotaryValueBackup;
SERIALDEBUG.print("Selection mode for ");
SERIALDEBUG.println(menuItem);
if (menuItem == MENUINFOS) maxOptions = MAXINFOPAGES; else maxOptions = MAXOPTIONS;
switch(menuItem) {
case MENUDISPLAY:currentOption=g_displayMode;break;
case MENUSERIAL:currentOption=(g_serialEnabled)?1:0;break;
case MENURESET:currentOption=0;break;
case MENUSOUND:currentOption=(g_soundEnabled)?1:0;break;
case MENUINFOS:currentOption=0;break;
default: SERIALDEBUG.println("Unknown menu item"); return;
}
// Backup/set rotary encoder start value
cli();
rotaryValueBackup = v_rotaryValue;
currentOption = 0;
lastRotaryValue = v_rotaryValue;
sei();
lastInteractMS = millis();
do {
esp_task_wdt_reset();
// Get rotary value and check for under- or overflow
cli();
if (v_rotaryValue >= maxOptions) v_rotaryValue = 0;
if (v_rotaryValue < 0) v_rotaryValue = maxOptions-1;
if (v_rotaryValue != lastRotaryValue) {
currentOption = v_rotaryValue;
lastRotaryValue = currentOption;
lastInteractMS = millis();
}
sei();
g_display.clearDisplay();
g_display.setFont();
g_display.setCursor(0,0);
switch(menuItem) {
case MENUDISPLAY:g_display.println(STR_DISPLAYMODE);break;
case MENUSERIAL:g_display.println(STR_SERIALPRINTENABLED);break;
case MENURESET:g_display.println(STR_FACTORYDEFAULT);break;
case MENUSOUND:g_display.println(STR_SOUND);break;
case MENUINFOS:showInfos(currentOption);break;
}
switch(menuItem) {
case MENUDISPLAY: {
switch(currentOption) {
case OPTIONLEFT:snprintf(strData,MAXSTRDATALENGTH+1,STR_MINIMAL);break;
case OPTIONRIGHT:snprintf(strData,MAXSTRDATALENGTH+1,STR_MAXIMAL);break;
}
g_display.setFont(&FreeSans9pt7b);
centerText(strData,2);
break;
}
case MENUSOUND: {
switch(currentOption) {
case OPTIONLEFT: {
drawIcon(SCREEN_WIDTH-50,(SCREEN_HEIGHT-ICON_HEIGHT)/2, ICONAUDIOOFF);
snprintf(strData,MAXSTRDATALENGTH+1,STR_OFF);
break;
}
case OPTIONRIGHT: {
drawIcon(SCREEN_WIDTH-50,(SCREEN_HEIGHT-ICON_HEIGHT)/2, ICONAUDIOON);
snprintf(strData,MAXSTRDATALENGTH+1,STR_ON);
break;
}
}
g_display.setFont(&FreeSans9pt7b);
centerText(strData,0,-ICON_WIDTH/2);
break;
}
case MENUSERIAL:
case MENURESET: {
switch(currentOption) {
case OPTIONLEFT:snprintf(strData,MAXSTRDATALENGTH+1,STR_NO);break;
case OPTIONRIGHT:snprintf(strData,MAXSTRDATALENGTH+1,STR_YES);break;
}
g_display.setFont(&FreeSans9pt7b);
centerText(strData,2);
break;
}
}
// Overview dots
for (int i=0;i<maxOptions;i++) {
if (i == currentOption) {
g_display.drawFastHLine(SCREEN_WIDTH/2-1-(OVERVIEWGAP*(maxOptions-1))/2 + OVERVIEWGAP*i,SCREEN_HEIGHT-2,2,WHITE);
}
g_display.drawFastHLine(SCREEN_WIDTH/2-1-(OVERVIEWGAP*(maxOptions-1))/2 + OVERVIEWGAP*i,SCREEN_HEIGHT-1,2,WHITE);
}
// Timeout bar
byte timeoutBar = SCREEN_HEIGHT - (SCREEN_HEIGHT*(millis() - lastInteractMS))/USERTIMEOUTMS;
g_display.drawFastVLine(SCREEN_WIDTH-1, SCREEN_HEIGHT-timeoutBar, timeoutBar, WHITE);
for (int i=0;i<4;i++) {
g_display.drawPixel(SCREEN_WIDTH-1,i*(SCREEN_HEIGHT/4), BLACK);
}
g_display.display();
if (millis()-lastInteractMS > USERTIMEOUTMS) {
beep();
exitLoop = true;
}
if (digitalRead(ROTARY_SW_PIN)==LOW) {
if (menuItem == MENUSOUND) {
g_soundEnabled = (currentOption == OPTIONRIGHT);
beep(SHORTBEEP);
}
g_display.invertDisplay(true);
delay(INVERTTIMEMS);
g_display.invertDisplay(false);
while (digitalRead(ROTARY_SW_PIN)==LOW) esp_task_wdt_reset(); // Wait for button release
exitLoop = true;
}
} while (!exitLoop); // Until button was pressed or timeout
switch(menuItem) {
case MENUSOUND: {
saveSettings();
break;
}
case MENUDISPLAY: {
g_displayMode = currentOption;
saveSettings();
break;
}
case MENUSERIAL: {
g_serialEnabled = (currentOption == OPTIONRIGHT);
setSerialMode();
saveSettings();
break;
}
case MENURESET:{
if (currentOption == OPTIONRIGHT) {
initSettings();
saveSettings();
SERIALDEBUG.flush();
ESP.restart();
}
break;
}
}
// Restore rotary encoder start value
cli();
v_rotaryValue = rotaryValueBackup;
sei();
}
// Device menu
void menu() {
#define MENUITEMLENGHT 80
char menuItem[MAXMENUITEMS][MENUITEMLENGHT] = {STR_START,STR_BATTERY,STR_IDLETIME,STR_THRESHOLD,STR_DISPLAY,STR_SOUND,STR_SERIAL,STR_LORATEST,STR_INFO,STR_RESET,STR_RESTART};
int currentMenuItem = 0;
int lastRotaryValue;
int16_t x, y;
uint16_t w, h;
bool exitLoop = false;
unsigned long lastInteractMS = 0;
SERIALDEBUG.println("Start menu");
cli();
v_rotaryValue = 0;
currentMenuItem = v_rotaryValue;
lastRotaryValue = v_rotaryValue;
sei();
g_mpu.enableSleep(true);
lastInteractMS = millis();
do {
esp_task_wdt_reset();
// Get rotary value and check for under- or overflow
cli();
if (v_rotaryValue >= MAXMENUITEMS) v_rotaryValue = 0;
if (v_rotaryValue < 0) v_rotaryValue = MAXMENUITEMS-1;
if (v_rotaryValue != lastRotaryValue) {
currentMenuItem = v_rotaryValue;
lastRotaryValue = currentMenuItem;
lastInteractMS = millis();
}
sei();
if (digitalRead(ROTARY_SW_PIN)==LOW) {
beep(SHORTBEEP);
while (digitalRead(ROTARY_SW_PIN)==LOW) esp_task_wdt_reset(); // Wait for button release
delay(BUTTONDEBOUNCEMS); // Debounce
switch(currentMenuItem) {
case MENUSTART: {
exitLoop = true;
break;
}
case MENUTHRESHOLD:
case MENUTIMEOUT: {
if (currentMenuItem == MENUTHRESHOLD) g_mpu.enableSleep(false);
changeValue(currentMenuItem);
if (currentMenuItem == MENUTHRESHOLD) g_mpu.enableSleep(true);
break;
}
case MENUINFOS: // No perfect way to use changeSettings for displaying infos, but it works