forked from tarohs/nisejjy
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclocksync.ino
More file actions
1651 lines (1508 loc) · 51.4 KB
/
clocksync.ino
File metadata and controls
1651 lines (1508 loc) · 51.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// clocksync.ino - ESP32 fake radio clock station
//
// Forked from 'nisejjy' by SASAKI Taroh (tarohs).
// Maintained by Tanvach.
//
// See README.md for usage, hardware setup, and attribution.
// See HOW_IT_WORKS.md for technical details on signal encoding.
//
#define VERSION "1.3.1"
//...................................................................
// hardware config
// Radio output pin (default 32). Grove pins 25 or 26 also work if you prefer using the Grove port;
// avoid them if you need I2C on SDA/SCL. Stay within isSafeAtomPin().
#define PIN_RADIO (32)
// note: {pin -> 330ohm -> 30cm loop antenna -> GND} works
// (33mW, but detuned length (super shorten), only very weak radiowave emitted).
#define PIN_BUZZ (-1) // no onboard buzzer on M5 Atom Lite
#define PIN_LED (-1) // use M5 Atom RGB LED instead
// Optional measurement input (jumper to radio pin for self-test)
// Default: GPIO33.
#define PIN_MEAS (33)
// Optional button pin (default 39 for M5 Atom Lite)
#define PIN_BUTTON (39)
#include <WiFi.h>
#include <ESPmDNS.h>
#include <WebServer.h>
#include <WebServer.h>
// M5 Atom Lite support (RGB LED, button, etc.)
#include <M5Atom.h>
// Drive strength configuration for safe antenna drive
#include "driver/gpio.h"
// High-resolution timer for precise tick scheduling
#include "esp_timer.h"
// ESP-IDF LEDC driver
#include "driver/ledc.h"
#include <Preferences.h>
#define DEVICENAME "clocksync"
// WiFi credentials are sourced from secrets.h (gitignored). An example
// file is provided as secrets_example.h. If secrets.h is missing, the
// example is used so the sketch still builds.
#if __has_include("secrets.h")
#include "secrets.h"
#elif __has_include("secrets_example.h")
#include "secrets_example.h"
#else
#error "Missing secrets.h or secrets_example.h"
#endif
char ssid[] = WIFI_SSID;
char passwd[] = WIFI_PASS;
// POSIX TZ string — set to your local timezone (see README for examples).
// WWVB requires a US timezone for correct DST bits.
// Find yours: tail -1 /etc/localtime (Mac/Linux) or see README
#define TZ "PST8PDT,M3.2.0,M11.1.0" // US Pacific; see README for other zones
// ------------------------------------------------------------------
// Logging helpers (USB serial only; web UI shows status separately)
#define LOG_PRINT(x) do { Serial.print(x); } while (0)
#define LOG_PRINTLN(x) do { Serial.println(x); } while (0)
#define LOG_PRINTF(fmt, ...) do { Serial.printf((fmt), ##__VA_ARGS__); } while (0)
// Minimal HTTP server for control/status
WebServer server(80);
//...................................................................
// station specs
//
#define SN_JJY_E (0) // JJY Fukushima Japan
#define SN_JJY_W (1) // JJY Fukuoka Japan
#define SN_WWVB (2) // WWVB US
#define SN_DCF77 (3) // DCF77 Germany
#define SN_BSF (4) // BSF Taiwan
#define SN_MSF (5) // MSF UK
#define SN_BPC (6) // BPC China
#define SN_DEFAULT (SN_WWVB)
int st_cycle2[] = {
// interrupt cycle, KHz: double of station freq
80, // 40KHz JJY-E
120, // 60KHz JJY-W
120, // 60KHz WWVB
155, // 77.5KHz DCF77
155, // 77.5KHz BSF
120, // 60KHz MSF
137 // 68.5KHz BPC
};
// interrupt cycle to makeup radio wave, buzzer (500Hz = 1KHz cycle):
// peripheral freq == 80MHz
// ex. radio freq 40KHz: intr 80KHz: 80KHz / 80MHz => 1/1000 (1/tm0cycle)
// buzz cycle: 1KHz / 80KHz 1/80 (1/radiodiv)
int tm0cycle;
#define TM0RES (1)
int radiodiv;
// TM0RES (interrupt counter), AMPDIV (buzz cycle(1000) / subsec(10)), SSECDIV (subsec / sec)
// don't depend on station specs.
#define AMPDIV (100) // 1KHz / 100 => 10Hz, amplitude may change every 0.1 seconds
#define SSECDIV (10) // 10Hz / 10 => 1Hz, clock ticks
// enum symbols
#define SP_0 (0)
#define SP_1 (1)
#define SP_M (2)
#define SP_P0 (SP_1) // for MSF
#define SP_P1 (3) // for MSF
/*#define SP_M0 (3) // for HBG
#define SP_M00 (4) // for HBG
#define SP_M000 (5) // for HBG
*/
#define SP_2 (2) // for BSF/BPC
#define SP_3 (3) // for BSF/BPC
#define SP_M4 (4) // for BSF/BPC
#define SP_MAX (SP_M4)
//
// bits_STATION[] => *bits60: 60 second symbol buffers, initialized with patterns
// sp_STATION[] => *secpattern: 0.1sec term pattern in one second, for each symbol
// * note: when sp_STATION[n * 10], secpattern[] is like 2-dim array secpattern[n][10].
//
// JJY & WWVB *note: comment is the format of JJY.
int8_t bits_jjy[] = {
// 60bit transmitted frame, of {SP_0, SP_1, SP_M}
SP_M, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_M, // (M), MIN10[3], 0, MIN1[4], (M)
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_M, // 0, 0, HOUR10[2], 0, HOUR1[4], (M)
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_M, // 0, 0, DOY100[2], DOY10[4], (M)
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_M, // DOY1[4], 0, 0, PA1, PA2, 0, (M)
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_M, // 0, YEAR[8], (M)
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_M // DOW[3], LS1, LS2, 0, 0, 0, 0, (M)
};
// *note: if summer time, set bit 57/58 (WWVB) (bit 38/40 (JJY, in future))
int8_t sp_jjy[] = {
// in (0, 1), [SP_x][amplitude_for_0.1sec_term_in_second]
1, 1, 1, 1, 1, 1, 1, 1, 0, 0, // SP_0
1, 1, 1, 1, 1, 0, 0, 0, 0, 0, // SP_1
1, 1, 0, 0, 0, 0, 0, 0, 0, 0 // SP_M
};
int8_t sp_wwvb[] = {
// in (0, 1), [SP_x][amplitude_for_0.1sec_term_in_second]
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // SP_0
0, 0, 0, 0, 0, 1, 1, 1, 1, 1, // SP_1
0, 0, 0, 0, 0, 0, 0, 0, 1, 1 // SP_M
};
// DCF77 encoding is LSB->MSB. //HBG *note: [0] is changed depending on DCF/HBG (also min/hour).
int8_t bits_dcf[] = {
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, // 0, reserved[9]
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_1, SP_0, // reserved[5], 0, 0, (0, 1)(MEZ), 0
SP_1, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, // 1, MIN1[4], MIN10[3], P1, (1->)
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, // HOUR1[4], HOUR10[2], P2, D1[4]
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, // D10[2], DOW[3], M1[4], M10[1]
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_M // Y1[4], Y10[4], P3, (M)
};
int8_t sp_dcf[] = {
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // SP_0
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // SP_1
1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // SP_M
};
/*
int8_t sp_hbg[] = {
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // SP_0
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // SP_1
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // SP_M
0, 1, 0, 1, 1, 1, 1, 1, 1, 1, // SP_M0 // 00sec
0, 1, 0, 1, 0, 1, 1, 1, 1, 1, // SP_M00 // 00sec at 00min
0, 1, 0, 1, 0, 1, 0, 1, 1, 1 // SP_M000 // 00sec at 00/12 hour 00min
};
*/
// BSF: quad encoding.
int8_t bits_bsf[] = {
SP_M4, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0,
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0,
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0,
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_M4,
SP_1, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, // 1, min[3], hour[2.5], P1[.5],
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_M4 // DOM[2.5], DOW[2.5], mon[2],
// year[3.5], P2[.5], 0, 0, M
};
int8_t sp_bsf[] = {
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // SP_0
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, // SP_1
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, // SP_2
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, // SP_3
1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // SP_M4
};
// MSF has 4 patterns.
int8_t bits_msf[] = {
SP_M, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0,
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0,
SP_1, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0,
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0,
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0,
SP_0, SP_0, SP_0, SP_P0, SP_P0, SP_P0, SP_P0, SP_P0, SP_P0, SP_0
};
int8_t sp_msf[] = {
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // SP_0
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // SP_1/SP_P0 (parity 0)
0, 0, 0, 0, 0, 1, 1, 1, 1, 1, // SP_M
0, 0, 0, 1, 1, 1, 1, 1, 1, 1 // SP_P1 (parity 1)
};
// BPC: quadary and has 5 patterns.
int8_t bits_bpc[] = {
SP_M4, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, // (B), P1, P2, h[2], m[3], DOW[2]
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, // P3, D[3], M[2], Y[3], P4
SP_M4, SP_1, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, // P1: 0, 1, 2 for 00-19, -39, -59s
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, // P2: 0, P3: AM/PM(0/2)+par<hmDOW>
SP_M4, SP_2, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, // P4: par<DMY> (0/1)
SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0, SP_0
};
int8_t sp_bpc[] = {
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, // SP_0
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, // SP_1
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, // SP_2
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, // SP_3
0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // SP_M4
};
// func for makeup patterns
void mb_jjy(void); // JJY-E, JJY-W
void mb_wwvb(void); // WWVB
void mb_dcf(void); // DCF77
void mb_bsf(void); // BSF
void mb_msf(void); // MSF
void mb_bpc(void); // BPC
int8_t *st_bits[] = { bits_jjy, bits_jjy, bits_jjy, bits_dcf, bits_bsf, bits_msf, bits_bpc };
int8_t *bits60;
int8_t *st_sp[] = { sp_jjy, sp_jjy, sp_wwvb, sp_dcf, sp_bsf, sp_msf, sp_bpc };
int8_t *secpattern;
void (*st_makebits[])(void) = { mb_jjy, mb_jjy, mb_wwvb, mb_dcf, mb_bsf, mb_msf, mb_bpc };
void (*makebitpattern)(void);
const char *stationNames[] = {
"JJY_E (40 kHz)",
"JJY_W (60 kHz)",
"WWVB (60 kHz)",
"DCF77 (77.5 kHz)",
"BSF (77.5 kHz)",
"MSF (60 kHz)",
"BPC (68.5 kHz)"
};
const char stationCmds[] = { 'j', 'k', 'w', 'd', 't', 'm', 'c' };
//...................................................................
// globals
hw_timer_t *tm0 = NULL;
volatile SemaphoreHandle_t timerSemaphore;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
volatile uint32_t buzzup = 0; // inc if buzz cycle (/2) passed
int istimerstarted = 0;
// TX enable/disable (controls whether the carrier + modulation scheduler are running)
int txEnabled = 1; // 1=enabled, 0=disabled
int radioc = 0; // 0..(RADIODIV - 1)
int ampc = 0; // 0..(AMPDIV - 1)
int tssec = 0; // 0..(SSECDIV - 1)
// Radio output GPIO (runtime configurable)
volatile int pinRadio = PIN_RADIO;
// GPIO drive strength (0=weakest..3=strongest)
int driveStrength = GPIO_DRIVE_CAP_2;
int currentStation = SN_DEFAULT;
int ntpsync = 1;
time_t now;
struct tm nowtm;
//int tsec, tmin, thour, // initial values for date/time
// tday, tmon, tyear; // tyear: lower 2 digits of 20xx
//int tdoy, tdow; // day of year (1-365/366), day of week (0-6)
int radioout = 0, // pin output values
buzzout = 0;
int ampmod; // 1 if radio out is active (vibrating), 0 if reducted,
// at cuttent subsecond-second frame for current date-time
int buzzsw = 0; // sound on/off
volatile int overrideCarrier = 0; // 1: force continuous carrier for self-test
volatile uint32_t measCount = 0; // edge counter for self-test
int wwvbEncodeNextMinute = 0; // 1: encode next minute (WWVB compatibility)
int dstOverride = 2; // 0=standard,1=DST,2=auto(nowtm.tm_isdst)
Preferences prefs;
// Last command response to surface in web UI (optional detail)
String lastCmdResp;
int ledEnabled = 1; // 0=off, 1=on (M5 LED or PIN_LED)
static int lastLedState = -1; // -1 unknown, 0 off, 1 on, -2 disabled
// WiFi Reconnect Tracking
static unsigned long lastWiFiCheckTime = 0;
const unsigned long WIFI_CHECK_INTERVAL = 60000; // 60 seconds
// LEDC carrier generation (single output pin)
// LEDC carrier generation (single output pin)
static const ledc_mode_t LEDC_MODE = LEDC_LOW_SPEED_MODE;
static const ledc_timer_t LEDC_TIMERIDX = LEDC_TIMER_0;
static const ledc_channel_t LEDC_CHANNEL_ID = LEDC_CHANNEL_0;
static const int LEDC_RES_BITS = 8; // 8-bit duty resolution
static uint32_t carrierHz = 60000; // updated per station
static int dutyHigh = 128; // ~50% duty (max fundamental)
static int dutyLow = 14; // ~5.5% duty (~17% amplitude)
// esp_timer for 100ms aligned ticks
static esp_timer_handle_t tick_timer = NULL;
static esp_timer_handle_t align_timer = NULL;
static volatile int secBoundaryFlag = 0; // set at each second boundary
static volatile int tickFlag = 0; // set each 100ms tick
static volatile int currentSecond = 0; // updated at second boundary
// WWVB minute bits prepared like txtempus (bit 59 is first second)
static uint64_t wwvb_bits = 0;
static time_t wwvb_minute_prepared = (time_t)-1;
// extern
void IRAM_ATTR onTimer(void);
void setup(void);
void loop(void);
void starttimer(void);
void stoptimer(void);
void setTxState(int enable);
void ampchange(void);
void setstation(int station);
void binarize(int v, int pos, int len);
void bcdize(int v, int pos, int len);
void rbinarize(int v, int pos, int len);
void rbcdize(int v, int pos, int len);
void quadize(int v, int pos, int len);
int parity(int pos, int len);
int qparity(int pos, int len);
void setlocaltime(void);
void getlocaltime(void);
//void setdoydow(void);
//int julian(int y, int m, int d);
//void incday(void); // for DCF77
int docmd(char *buf);
int a2toi(char *chp);
void printbits60(void);
void ntpstart(void);
void ntpstop(void);
int isSafeAtomPin(int p);
void printhelp(void);
void IRAM_ATTR meas_isr(void);
int isUSDSTPending2h(void);
int getDSTFlag(void);
// LEDC/timer helpers
void setupCarrierLEDC(void);
void setCarrierPowerLevel(int highPower);
void scheduleAlignedTicks(void);
void IRAM_ATTR onAlignedStart(void *arg);
void IRAM_ATTR onTick100ms(void *arg);
void prepareWWVBMinuteBits(time_t minuteStartUTC);
// Web server helpers
void setupWebServer(void);
String generateStatusText(void);
void handleRoot(void);
void handleStatus(void);
void handleCmd(void);
void saveSettings(void);
void loadSettings(void);
void applyDefaultSettings(void);
// GPIO helpers
int clampDriveCap(int cap);
void applyDriveStrength(void);
//...................................................................
// intr handler:
// this routine is called once every 1/2f sec (where f is radio freq).
// - reverse radio output pin if modulation flag "ampmod" == 1,
// - count up "radioc", if exceeds "radiodev" then
// turn on buzzer flag "buzzup"; the "buzzup" is set once in 1/1000sec
// on every frequency of the station (so "radiodev" should be set
// propery depending to the intr cycle "tm0cycle" of the station).
void IRAM_ATTR onTimer(void) {
// no-op: LEDC-based carrier; ISR not used
return;
}
//...................................................................
void setup(void) {
Serial.begin(115200);
delay(100);
LOG_PRINT("started...\n");
// Initialize M5 Atom Lite (Serial, no I2C, Display/LED enabled)
M5.begin(true, false, true);
// Ensure onboard RGB LED is off initially
M5.dis.drawpix(0, 0x000000);
LOG_PRINTLN("\nUSB serial control ready (115200 bps). Type 'h' + Enter for help.");
// HTTP server provides control/status.
// Credentials are compiled in; no need to persist them to NVS flash.
WiFi.persistent(false);
// Ensure max performance for network services
WiFi.setSleep(false);
// Load persisted settings before initializing subsystems
loadSettings();
if (ntpsync) {
ntpstart();
}
// Explicitly start mDNS after WiFi is connected (ntpstart connects WiFi)
if (WiFi.status() == WL_CONNECTED) {
if (MDNS.begin(DEVICENAME)) {
LOG_PRINTLN("mDNS responder started: " DEVICENAME ".local");
}
}
// Start HTTP control/status server
setupWebServer();
// Prepare radio pin
pinMode(PIN_MEAS, INPUT_PULLDOWN);
pinMode(pinRadio, OUTPUT);
digitalWrite(pinRadio, LOW);
applyDriveStrength();
if (PIN_BUZZ >= 0) {
pinMode(PIN_BUZZ, OUTPUT);
digitalWrite(PIN_BUZZ, buzzout);
}
if (PIN_LED >= 0) {
if (ledEnabled) {
pinMode(PIN_LED, OUTPUT);
digitalWrite(PIN_LED, LOW);
lastLedState = 0;
} else {
pinMode(PIN_LED, INPUT); // tri-state to avoid any drive
lastLedState = -2;
}
} else {
if (ledEnabled) {
// leave off initially; will blink based on ampmod in loop()
M5.dis.drawpix(0, 0x000000);
lastLedState = 0;
} else {
// ensure fully off and no further updates in loop when disabled
M5.dis.drawpix(0, 0x000000);
lastLedState = -2;
}
}
// setdoydow();
setstation(currentStation); // will start carrier only if txEnabled
LOG_PRINT(txEnabled ? "radio started.\n" : "radio disabled (TX off).\n");
}
void loop() {
int buzzup2 = 0; // legacy
static char buf[128];
static int bufp = 0;
static char usb[128];
static int usbp = 0;
// Non-blocking WiFi reconnect check
if (ntpsync) {
unsigned long currentMillis = millis();
if (WiFi.status() == WL_CONNECTED) {
lastWiFiCheckTime = currentMillis; // Constantly reset while connected
} else if (currentMillis - lastWiFiCheckTime >= WIFI_CHECK_INTERVAL) {
lastWiFiCheckTime = currentMillis;
LOG_PRINTLN("WiFi disconnected. Attempting reconnect...");
WiFi.disconnect();
WiFi.begin(ssid, passwd); // Re-initiate connection
}
}
// Update M5 state (button, etc.)
M5.update();
if (M5.Btn.wasPressed()) {
setTxState(!txEnabled);
saveSettings();
LOG_PRINTF("Button: TX %s\n", txEnabled ? "enabled" : "disabled");
}
// For generic ESP32 (if M5Atom lib excluded):
// if (digitalRead(PIN_BUTTON) == LOW) { delay(50); if(digitalRead(PIN_BUTTON)==LOW) { ... } }
// Aligned second boundary
if (secBoundaryFlag) {
secBoundaryFlag = 0;
int lastmin = nowtm.tm_min;
getlocaltime();
currentSecond = nowtm.tm_sec;
if (lastmin != nowtm.tm_min) {
if (currentStation != SN_WWVB) {
makebitpattern();
printbits60();
}
}
if (currentStation == SN_WWVB) {
time_t tnow;
time(&tnow);
time_t minuteStartUTC = tnow - (tnow % 60);
if (wwvb_minute_prepared != minuteStartUTC) {
prepareWWVBMinuteBits(minuteStartUTC);
wwvb_minute_prepared = minuteStartUTC;
}
}
LOG_PRINTF("%d-%d-%d, %d(%d) %02d:%02d:%02d\n",
nowtm.tm_year + 1900, nowtm.tm_mon + 1, nowtm.tm_mday,
nowtm.tm_yday, nowtm.tm_wday,
nowtm.tm_hour, nowtm.tm_min, nowtm.tm_sec);
}
// 100ms tick: drive amplitude
if (tickFlag) {
tickFlag = 0;
int highPower = 1;
if (overrideCarrier) {
highPower = 1;
} else if (currentStation == SN_WWVB) {
int sec = currentSecond % 60;
int lowTicks;
if (sec == 0 || (sec % 10) == 9) {
lowTicks = 8; // marker
} else {
int bit = (int)((wwvb_bits >> (59 - sec)) & 1ULL);
lowTicks = bit ? 5 : 2;
}
highPower = (tssec >= lowTicks) ? 1 : 0;
} else {
highPower = secpattern[bits60[nowtm.tm_sec] * 10 + tssec] ? 1 : 0;
}
ampmod = highPower;
setCarrierPowerLevel(ampmod);
if (ledEnabled) {
int desired = ampmod ? 1 : 0;
if (PIN_LED >= 0) {
if (lastLedState != desired) {
// ensure output mode when enabled
pinMode(PIN_LED, OUTPUT);
digitalWrite(PIN_LED, desired ? HIGH : LOW);
lastLedState = desired;
}
} else {
if (lastLedState != desired) {
M5.dis.drawpix(0, desired ? 0x10ff10 : 0x000000);
lastLedState = desired;
}
}
} else {
// Disable LED hardware completely; do this once
if (lastLedState != -2) {
if (PIN_LED >= 0) {
pinMode(PIN_LED, INPUT);
} else {
M5.dis.drawpix(0, 0x000000);
}
lastLedState = -2;
}
}
Serial.print(ampmod ? "~" : ".");
}
// Commands accepted via USB serial and HTTP
while (Serial.available()) {
usb[usbp] = Serial.read();
if (usb[usbp] == '\n' || usb[usbp] == '\r' || usbp == sizeof(usb) - 1) {
usb[usbp] = '\0';
docmd(usb);
usbp = 0;
} else {
usbp++;
}
}
// Handle HTTP requests quickly; non-blocking
server.handleClient();
delay(1); // feed watchdog
}
//...................................................................
//...................................................................
void starttimer(void) {
if (istimerstarted) {
stoptimer();
}
setupCarrierLEDC();
scheduleAlignedTicks();
LOG_PRINT("(re)started LEDC carrier + tick scheduler...\n");
istimerstarted = 1;
return;
}
void stoptimer(void) {
if (istimerstarted) {
if (align_timer) {
esp_timer_stop(align_timer);
}
if (tick_timer) {
esp_timer_stop(tick_timer);
}
// Turn off carrier and tristate the pin (high-impedance).
// Avoid ledc_stop() which can pause the timer and cause restart issues.
ledc_set_duty(LEDC_MODE, LEDC_CHANNEL_ID, 0);
ledc_update_duty(LEDC_MODE, LEDC_CHANNEL_ID);
pinMode(pinRadio, INPUT); // detach LEDC, Hi-Z: no current through antenna
istimerstarted = 0;
}
}
// setup amplitude value ampmod depends on bit pattern & 0.1 second frame
void ampchange(void) {
// handled in loop() by LEDC amplitude update
return;
}
void setTxState(int enable) {
if (enable) {
txEnabled = 1;
starttimer();
} else {
txEnabled = 0;
stoptimer();
// Force LED off
if (ledEnabled) {
if (PIN_LED >= 0) {
digitalWrite(PIN_LED, LOW);
} else {
M5.dis.drawpix(0, 0x000000);
}
lastLedState = 0;
}
}
}
void setstation(int station) {
stoptimer();
LOG_PRINTF("station #%d:\n", station);
currentStation = station;
tm0cycle = 80000 / st_cycle2[station];
radiodiv = st_cycle2[station];
LOG_PRINTF(" freq %fMHz, timer intr: 80M / (%d x %d), buzz/radio: /%d\n",
(float)radiodiv / 2., tm0cycle, TM0RES, radiodiv);
bits60 = st_bits[station];
LOG_PRINTF(" bits60 pattern: ");
for (int i = 0; i < 60; i++) {
LOG_PRINTF("%d", (int)bits60[i]);
}
secpattern = st_sp[station];
LOG_PRINTF("\n second pattern: ");
for (int i = 0; i < 10; i++) {
LOG_PRINTF("%d", (int)secpattern[i]);
}
LOG_PRINTF("...\n");
makebitpattern = st_makebits[station];
makebitpattern();
printbits60();
if (txEnabled) {
starttimer();
}
return;
}
//...................................................................
// makeup bit pattern for current date, hour:min
void mbc_wwvbjjy(void) //--- [0..33] are common in WWVB/JJY
{
binarize(nowtm.tm_min / 10, 1, 3);
binarize(nowtm.tm_min % 10, 5, 4);
binarize(nowtm.tm_hour / 10, 12, 2);
binarize(nowtm.tm_hour % 10, 15, 4);
int y100 = nowtm.tm_yday / 100;
int y1 = (nowtm.tm_yday - y100 * 100);
int y10 = y1 / 10;
y1 = y1 % 10;
binarize(y100, 22, 2);
binarize(y10, 25, 4);
binarize(y1, 30, 4);
// Serial.printf("min%d-%d hour%d-%d doy%d-%d-%d ", tmin / 10, tmin % 10, thour / 10, thour % 10,
// y100, y10, y1);
return;
}
void mb_jjy(void) //---- JJY_E & JJY_W
{
LOG_PRINT("encode JJY format - ");
mbc_wwvbjjy();
bits60[36] = parity(12, 7);
bits60[37] = parity(1, 8);
// Serial.printf("pa2%d ", s % 2);
binarize((nowtm.tm_year - 100) / 10, 41, 4);
binarize(nowtm.tm_year % 10, 45, 4);
binarize(nowtm.tm_wday, 50, 3);
// Serial.printf("year%d-%d dow%d\n", tyear / 10, tyear % 10, tdow);
return;
}
void mb_wwvb(void) {
LOG_PRINT("encode WWVB format - ");
// For display/debug only; actual modulation uses wwvb_bits
time_t nowtime;
time(&nowtime);
struct tm *utm = gmtime(&nowtime);
struct tm ut = *utm;
// minutes
binarize(ut.tm_min / 10, 1, 3);
binarize(ut.tm_min % 10, 5, 4);
// hours
binarize(ut.tm_hour / 10, 12, 2);
binarize(ut.tm_hour % 10, 15, 4);
// day of year (1..366)
int yday1 = ut.tm_yday + 1;
binarize((yday1 / 100) % 10, 22, 2);
binarize((yday1 / 10) % 10, 25, 4);
binarize(yday1 % 10, 30, 4);
// year (00..99)
binarize((ut.tm_year) / 10, 45, 4);
binarize((ut.tm_year) % 10, 50, 4);
// local DST state (approximate; not used for modulation)
bits60[57] = nowtm.tm_isdst ? SP_1 : SP_0;
bits60[58] = isUSDSTPending2h();
return;
}
void mb_dcf(void) //---- DCF77
{
LOG_PRINT("encode DCF77 format - ");
// bits60[0] = SP_0; // (obsolate) this routine is used also by mb_hbg() which changes bits60[0]
// Seasonal flags (Z1/Z2)
if (getDSTFlag()) {
bits60[17] = SP_1; // Z1 = 1
bits60[18] = SP_0; // Z2 = 0 (DST)
} else {
bits60[17] = SP_0; // Z1 = 0
bits60[18] = SP_1; // Z2 = 1 (standard)
}
rbcdize(nowtm.tm_min, 21, 7);
bits60[28] = parity(21, 7);
rbcdize(nowtm.tm_hour, 29, 6);
bits60[35] = parity(29, 6);
rbcdize(nowtm.tm_mday, 36, 6);
rbinarize(nowtm.tm_wday, 42, 3);
rbcdize(nowtm.tm_mon + 1, 45, 5);
rbcdize(nowtm.tm_year - 100, 50, 8);
bits60[58] = parity(36, 22);
return;
}
/*
void
mb_hbg(void) //---- HBG
{
mb_dcf();
if (tmin != 0) {
bits60[0] = SP_M0;
} else {
if (thour % 12 != 0) {
bits60[0] = SP_M00;
} else {
bits60[0] = SP_M000;
}
}
return;
}
*/
void mb_bsf(void) //---- BSF
{
LOG_PRINT("encode BSF format - ");
quadize(nowtm.tm_min, 41, 3);
quadize(nowtm.tm_hour * 2, 44, 3);
bits60[46] |= qparity(41, 6);
quadize(nowtm.tm_mday * 2, 47, 3);
bits60[49] |= nowtm.tm_wday / 4;
quadize(nowtm.tm_wday % 4, 50, 1);
quadize(nowtm.tm_mon + 1, 51, 2);
quadize((nowtm.tm_year - 100) * 2, 53, 4);
bits60[56] |= qparity(47, 10);
return;
}
void mb_msf(void) {
LOG_PRINT("encode MSF format - ");
bcdize(nowtm.tm_year - 100, 17, 8);
bcdize(nowtm.tm_mon + 1, 25, 5);
bcdize(nowtm.tm_mday, 30, 6);
binarize(nowtm.tm_wday, 36, 3);
bcdize(nowtm.tm_hour, 39, 6);
bcdize(nowtm.tm_min, 45, 7);
bits60[54] = parity(17, 8) * 2 + 1; // in MSF parity bits, values are {1, 3} (SP_1, SP_P1)
bits60[55] = parity(25, 11) * 2 + 1; // for parity {0, 1}.
bits60[56] = parity(36, 3) * 2 + 1;
bits60[57] = parity(39, 13) * 2 + 1;
// Set summertime indicator using DST override
bits60[58] = getDSTFlag() ? SP_P1 : SP_1;
return;
}
void mb_bpc(void) {
LOG_PRINT("encode BPC format - ");
quadize(nowtm.tm_hour % 12, 3, 2);
quadize(nowtm.tm_min, 5, 3);
quadize(nowtm.tm_wday, 8, 2);
bits60[10] = (nowtm.tm_hour / 12) * 2 + qparity(3, 7);
quadize(nowtm.tm_mday, 11, 3);
quadize(nowtm.tm_mon + 1, 14, 2);
quadize(nowtm.tm_year - 100, 16, 3);
bits60[19] = qparity(11, 8);
for (int i = 2; i < 20; i++) {
bits60[20 + i] = bits60[i];
bits60[40 + i] = bits60[i];
}
return;
}
// write binary value into bit pattern (little endian)
void binarize(int v, int pos, int len) {
for (pos = pos + len - 1; 0 < len; pos--, len--) {
bits60[pos] = (uint8_t)(v & 1);
v >>= 1;
}
return;
}
void IRAM_ATTR meas_isr(void) {
measCount++;
}
// -- LEDC carrier helpers -------------------------------------------------
void setupCarrierLEDC(void) {
// Configure LEDC timer and channel for the selected frequency (ESP-IDF)
ledc_timer_config_t tcfg = {};
tcfg.speed_mode = LEDC_MODE;
tcfg.duty_resolution = (ledc_timer_bit_t)LEDC_RES_BITS;
tcfg.timer_num = LEDC_TIMERIDX;
tcfg.freq_hz = carrierHz;
tcfg.clk_cfg = LEDC_AUTO_CLK;
ledc_timer_config(&tcfg);
ledc_channel_config_t c = {};
c.gpio_num = pinRadio;
c.speed_mode = LEDC_MODE;
c.channel = LEDC_CHANNEL_ID;
c.intr_type = LEDC_INTR_DISABLE;
c.timer_sel = LEDC_TIMERIDX;
c.duty = dutyHigh;
c.hpoint = 0;
ledc_channel_config(&c);
}
void setCarrierPowerLevel(int highPower) {
uint32_t d = highPower ? (uint32_t)dutyHigh : (uint32_t)dutyLow;
ledc_set_duty(LEDC_MODE, LEDC_CHANNEL_ID, d);
ledc_update_duty(LEDC_MODE, LEDC_CHANNEL_ID);
}
// -- esp_timer aligned tick scheduler ------------------------------------
void IRAM_ATTR onTick100ms(void *arg) {
int t = tssec + 1;
if (t >= 10) {
t = 0;
secBoundaryFlag = 1;
}
tssec = t;
tickFlag = 1;
}
void IRAM_ATTR onAlignedStart(void *arg) {
// Start periodic 100ms timer exactly at second boundary
if (!tick_timer) {
esp_timer_create_args_t targs = {};
targs.callback = &onTick100ms;
targs.arg = NULL;
targs.dispatch_method = ESP_TIMER_TASK;
targs.name = "tick100ms";
esp_timer_create(&targs, &tick_timer);
}
tssec = 0;
secBoundaryFlag = 1;
tickFlag = 1;
esp_timer_start_periodic(tick_timer, 100000); // 100 ms
}
void scheduleAlignedTicks(void) {
// Create or restart a one-shot timer to fire at the next wall-clock second
if (!align_timer) {
esp_timer_create_args_t aargs = {};
aargs.callback = &onAlignedStart;
aargs.arg = NULL;
aargs.dispatch_method = ESP_TIMER_TASK;
aargs.name = "alignStart";
esp_timer_create(&aargs, &align_timer);
}
struct timeval tv;
gettimeofday(&tv, NULL);
int64_t us_to_next = 1000000 - tv.tv_usec;
if (us_to_next <= 0) us_to_next = 1;
esp_timer_start_once(align_timer, (uint64_t)us_to_next);
}
// -- WWVB minute bits exactly like txtempus ------------------------------
static uint64_t to_padded5_bcd(int n) {
return (uint64_t)(((n / 100) % 10) << 10) | (uint64_t)(((n / 10) % 10) << 5) | (uint64_t)(n % 10);
}
static int is_leap_year_full(int year) {
return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
}
void prepareWWVBMinuteBits(time_t minuteStartUTC) {
struct tm ut;
gmtime_r(&minuteStartUTC, &ut);
// Build 60-bit frame, bit 59 is first second of the minute
uint64_t bits = 0ULL;
bits |= to_padded5_bcd(ut.tm_min) << (59 - 8);
bits |= to_padded5_bcd(ut.tm_hour) << (59 - 18);
bits |= to_padded5_bcd(ut.tm_yday + 1) << (59 - 33);
bits |= to_padded5_bcd(ut.tm_year % 100) << (59 - 53);
bits |= (uint64_t)(is_leap_year_full(ut.tm_year + 1900) ? 1 : 0) << (59 - 55);
// DST flags (bits 57-58): derived from TZ via localtime_r().
// TZ must be set to a US timezone for correct WWVB DST indication.
struct tm lt_now, lt_tom;
time_t t_now_local = minuteStartUTC;
localtime_r(&t_now_local, <_now);
time_t t_tom_local = minuteStartUTC + 86400;
localtime_r(&t_tom_local, <_tom);
bits |= (uint64_t)(lt_tom.tm_isdst ? 1 : 0) << (59 - 57);
bits |= (uint64_t)(lt_now.tm_isdst ? 1 : 0) << (59 - 58);
wwvb_bits = bits;
}
// Return 1 if a US DST switch occurs within the next 2 hours (local time)
int isUSDSTPending2h(void) {
// current local time_t from nowtm
struct tm nowLocal = nowtm;
time_t nowt = mktime(&nowLocal);
int year = nowLocal.tm_year; // years since 1900
auto firstSunday = [](int year1900, int mon) -> int {
struct tm t = { 0 };
t.tm_year = year1900;
t.tm_mon = mon;
t.tm_mday = 1;
t.tm_hour = 0;
t.tm_isdst = -1;
mktime(&t);
int dow = t.tm_wday; // 0..6, 0=Sunday
return 1 + ((7 - dow) % 7);
};
auto secondSunday = [&](int year1900, int mon) -> int {
int d1 = firstSunday(year1900, mon);
return d1 + 7;
};
// DST start: second Sunday in March, 02:00 local
struct tm spring = { 0 };
spring.tm_year = year;
spring.tm_mon = 2; // March
spring.tm_mday = secondSunday(year, 2);
spring.tm_hour = 2;
spring.tm_isdst = -1;
time_t tSpring = mktime(&spring);
// DST end: first Sunday in November, 02:00 local
struct tm fall = { 0 };
fall.tm_year = year;
fall.tm_mon = 10; // November
fall.tm_mday = firstSunday(year, 10);
fall.tm_hour = 2;
fall.tm_isdst = -1;
time_t tFall = mktime(&fall);
time_t tx;
if (nowLocal.tm_isdst > 0) { // currently DST → next is fall
if (nowt < tFall) {
tx = tFall;
} else {
// compute next year's fall
fall.tm_year = year + 1;
fall.tm_mday = firstSunday(year + 1, 10);
tx = mktime(&fall);
}
} else { // currently standard → next is spring
if (nowt < tSpring) {
tx = tSpring;
} else {
// next year's spring