-
Notifications
You must be signed in to change notification settings - Fork 1
/
nixie-clock.ino
2150 lines (1896 loc) · 77.6 KB
/
nixie-clock.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
/*
* A Nixie Clock Implementation
*
* Features:
* - 6 IN-8-2 Nixie featuring 0-9 digits and decimal points
* - Multiplexed display, requires one single K155ID1 Nixie driver chip
* - Synchronization with the DCF77 time signal
* - Automatic crystal drift compensation using DCF77 time
* - Power saving mode for running on a backup super-capacitor
* - Dual timers: Timer1 used for timekeeping and Timer2 for countdown timer / stopwatch
* - Automatic and manual display brightness adjustment
* - Menu navigation using 3 push-buttons
* - Alarm clock with the weekday and weekend options
* - Countdown timer
* - Stopwatch
* - Service menu
* - Cathode poisoning prevention and the "Slot Machine" effect
* - Screen blanking with dual time intervals
* - Settings are stored to EEPROM
* - and more...
*
* This source file is part of the Nixie Clock Arduino firmware
* found under http://www.github.com/microfarad-de/nixie-clock
*
* Please visit:
* http://www.microfarad.de
* http://www.github.com/microfarad-de
*
* Copyright (C) 2021 Karim Hraibi (khraibi at gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Version: 5.1.1
* Date: March 26, 2023
*/
#define VERSION_MAJOR 5 // Major version
#define VERSION_MINOR 1 // Minor version
#define VERSION_MAINT 1 // Maintenance version
#include <time.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include "src/TimerOne/TimerOne.h"
#include "src/TimerTwo/TimerTwo.h"
#include "src/Button/Button.h"
#include "src/Dcf/Dcf.h"
#include "src/Adc/Adc.h"
#include "src/Nvm/Nvm.h"
#include "src/MathMf/MathMf.h"
#include "Nixie.h"
#include "Brightness.h"
#include "Features.h"
//#include "BuildDate.h"
//#define SERIAL_DEBUG // activate debug printing over RS232
//#define DEBUG_VALUES // activate the debug values within the service menu
#ifdef SERIAL_DEBUG
#define SERIAL_BAUD 115200 // serial baud rate
#endif
// use these macros for printing to serial port
#ifdef SERIAL_DEBUG
#define PRINT(...) Serial.print (__VA_ARGS__)
#define PRINTLN(...) Serial.println (__VA_ARGS__)
#else
#define PRINT(...)
#define PRINTLN(...)
#endif
// reset the Nixie tube uptime to NIXIE_UPTIME_RESET_VALUE
//#define NIXIE_UPTIME_RESET
#ifdef NIXIE_UPTIME_RESET
// reset the Nixie tube uptime to this value in seconds upon booting
#define NIXIE_UPTIME_RESET_VALUE ((uint32_t)0*ONE_HOUR)
#endif
// upon the absence of this string in EEPROM all the settings will be reset to default
#define SETTINGS_RESET_CODE 0xDEADBEEF
// anode control pins
#define ANODE0_PIN 12
#define ANODE1_PIN 11
#define ANODE2_PIN 10
#define ANODE3_PIN 7
#define ANODE4_PIN 4
#define ANODE5_PIN 2
// K155ID1 BCD decoder pins
#define BCD0_PIN 9
#define BCD1_PIN 6
#define BCD2_PIN 5
#define BCD3_PIN 8
// pin controlling the comma
#define COMMA_PIN 13
// DCF77 settings
#define DCF_PIN 3 // DCF77 digital pin
#define DCF_START_EDGE FALLING // trigger the start of a DCF bit on FALLING/RISING edge of DCF_PIN
// pin controlling the buzzer
#define BUZZER_PIN 1
// pin for controlling the brightness boosting feature
#define BRIGHTNESS_PIN 0
// analog pins
#define NUM_APINS 5 // total number of hardware analog pins in use for non-blocking ADC
#define BUTTON0_APIN A2 // button 0 - "mode"
#define BUTTON1_APIN A3 // button 1 - "increase"
#define BUTTON2_APIN A1 // button 2 - "decrease"
#define LIGHTSENS_APIN A0 // light sensor
#define EXTPWR_APIN A6 // measures external power voltage
#define VOLTAGE_APIN A7 // measures the retention super capacitor voltage
// various constants
#define TIMER1_DIVIDER 64 // (Timer1 period) = TIMER_DEFAULT_PERIOD / TIMER1_DIVIDER
#define TIMER2_DIVIDER 40 // (Timer2 period) = (Timer1 period) / TIMER2_DIVIDER
#define TIMER_DEFAULT_PERIOD (1000000 * TIMER1_DIVIDER) // default value of timerPeriod (total is 1 second)
#define TIMER_MIN_PERIOD (TIMER_DEFAULT_PERIOD - TIMER_DEFAULT_PERIOD / 100) // minimum allowed value of timerPeriod
#define TIMER_MAX_PERIOD (TIMER_DEFAULT_PERIOD + TIMER_DEFAULT_PERIOD / 100) // maximum allowed value of timerPeriod
#define WDT_TIMEOUT WDTO_4S // watcchdog timer timeout setting
#define EEPROM_SETTINGS_ADDR 0 // EEPROM address of the settngs structure
#define EEPROM_BRIGHTNESS_ADDR (EEPROM_SETTINGS_ADDR + sizeof (Settings)) // EEPROM address of the display brightness lookup table
#define MENU_ORDER_LIST_SIZE 3 // size of the dynamic menu ordering list
#define SETTINGS_LUT_SIZE 17 // size of the settings lookup table
#ifdef DEBUG_VALUES
#define NUM_DEBUG_VALUES 3 // total number of debug values shown in the service menu
#define NUM_DEBUG_DIGITS 7 // number of digits for the debug values shown in the service menu
#else
#define NUM_DEBUG_VALUES 0
#endif
#define NUM_SERVICE_VALUES (5 + NUM_DEBUG_VALUES) // total number of values inside the service menu
/*
* Enumerations for the states of the menu navigation state machine
* the program relies on the exact order of the below definitions
*/
enum MenuState_e { SHOW_TIME_E, SHOW_DATE_E, SHOW_WEEK_E, SHOW_ALARM_E, SHOW_TIMER_E, SHOW_STOPWATCH_E, SHOW_SERVICE_E, SHOW_BLANK_E,
SET_ALARM_E, SET_SETTINGS_E, SET_HOUR_E, SET_MIN_E, SET_SEC_E, SET_DAY_E, SET_MONTH_E, SET_YEAR_E, SET_WEEK_E,
SHOW_TIME, SHOW_DATE, SHOW_WEEK, SHOW_ALARM, SHOW_TIMER, SHOW_STOPWATCH, SHOW_SERVICE, SHOW_BLANK,
SET_ALARM, SET_SETTINGS, SET_HOUR, SET_MIN, SET_SEC, SET_DAY, SET_MONTH, SET_YEAR, SET_WEEK };
#ifdef DEBUG_VALUES
// Class for storing debug values
class DebugClass {
public:
int32_t values[NUM_DEBUG_VALUES];
void initialize (void) {
for (uint8_t i = 0; i < NUM_DEBUG_VALUES; i++) {
set ( i, (int32_t)111111111 * i );
if (i % 2 != 0) {
values[i] = -values[i];
}
}
}
void set (uint8_t index, int32_t value) {
if (index < NUM_DEBUG_VALUES) {
values[index] = value;
}
}
} Debug;
#endif
/*
* Structure that holds the settings to be stored in EEPROM
*/
struct Settings_t {
uint32_t timerPeriod; // virtual period of Timer1/Timer2 (equivalent to 1 second)
volatile uint32_t nixieUptime; // stores the nixie tube uptime in seconds
uint8_t reserved[2]; // reserved for future use
int8_t timeZone; // time difference between UTC and local time
int8_t dstEnabled; // daylight saving time (0 = disabled, 1 = enabled, 2 = automatic)
bool dcfSyncEnabled; // enables DCF77 synchronization feature
bool dcfSignalIndicator; // enables the live DCF77 signal strength indicator (blinking decimal point on digit 1)
uint8_t dcfSyncHour; // hour of day when DCF77 sync shall start
uint8_t blankScreenMode; // turn-off display during a time interval in order to reduce tube wear (1 = every day, 2 = on weekdays, 3 = on weekends, 4 = permanent)
uint8_t blankScreenStartHr; // start hour for disabling the display
uint8_t blankScreenFinishHr; // finish hour for disabling the display
uint8_t cathodePoisonPrevent; // enables cathode poisoning prevention measure by cycling through all digits (1 = on preset time, 2 = "Slot Machine" every minute, 3 = "Slot Machine" every 10 min)
uint8_t cppStartHr; // start hour for the cathode poisoning prevention measure
int8_t clockDriftCorrect; // manual clock drift correction
uint8_t reserved0; // reserved for future use
bool brightnessAutoAdjust; // enables the brightness auto-adjustment feature
bool brightnessBoost; // enables the brightness boosting feature
uint8_t blankScreenMode2; // turn-off display during a time interval in order to reduce tube wear (second profile) (1 = every day, 2 = on weekdays, 3 = on weekends)
uint8_t blankScreenStartHr2; // start hour for disabling the display (second profile)
uint8_t blankScreenFinishHr2; // finish hour for disabling the display (second profile)
uint8_t reserved1[1]; // reserved for future use
uint32_t settingsResetCode; // all settings will be reset to default if this value is different than the value of SETTINGS_RESET_CODE
AlarmEeprom_s alarm; // alarm clock settings
int8_t weekStartDay; // the first day of a calendar week (1 = Monday, 7 = Sunday)
int8_t calWeekAdjust; // calendar week compensation value
uint8_t reserved2[2]; // reserved for future use
} Settings;
/*
* Lookup table that maps the individual system settings
* to their ranges and IDs
*/
const struct SettingsLut_t {
int8_t *value; // pointer to the value variable
uint8_t idDigit1; // most significant digit to be displayed for the settings ID
uint8_t idDigit0; // least significant digit to be dispalyed for the settings ID
int8_t minVal; // minimum value
int8_t maxVal; // maximum value
int8_t defaultVal; // default value
} SettingsLut[SETTINGS_LUT_SIZE] =
{
{ (int8_t *)&Settings.timeZone, 1, 1, -11, 14, 1 }, // time difference between UTC and local time
{ (int8_t *)&Settings.dstEnabled, 1, 2, 0, 2, 2 }, // daylight saving time (0 = disabled, 1 = enabled, 2 = automatic)
{ (int8_t *)&Settings.weekStartDay, 1, 3, 1, 7, 1 }, // start day of the week (1 = Monday, 7 = Sunday)
{ (int8_t *)&Settings.clockDriftCorrect, 1, 4, -99, 99, 0 }, // manual clock drift correction
{ (int8_t *)&Settings.dcfSyncEnabled, 2, 1, false, true, true }, // DCF sync
{ (int8_t *)&Settings.dcfSignalIndicator, 2, 2, false, true, true }, // - signal indicator
{ (int8_t *)&Settings.dcfSyncHour, 2, 3, 0, 23, 3 }, // - sync hour
{ (int8_t *)&Settings.blankScreenMode, 3, 1, 0, 4, 2 }, // screen blanking (0 = off, 1 = every day, 2 = on weekdays, 3 = on weekends, 4 = permanent)
{ (int8_t *)&Settings.blankScreenStartHr, 3, 2, 0, 23, 8 }, // - start hour
{ (int8_t *)&Settings.blankScreenFinishHr, 3, 3, 0, 23, 17 }, // - finish hour
{ (int8_t *)&Settings.blankScreenMode2, 4, 1, 0, 3, 1 }, // screen blanking (second profile) (0 = off, 1 = every day, 2 = on weekdays, 3 = on weekends)
{ (int8_t *)&Settings.blankScreenStartHr2, 4, 2, 0, 23, 2 }, // - start hour
{ (int8_t *)&Settings.blankScreenFinishHr2, 4, 3, 0, 23, 5 }, // - finish hour
{ (int8_t *)&Settings.cathodePoisonPrevent, 5, 1, 0, 3, 3 }, // cathode poisoning prevention (0 = off, 1 = on preset time, 2 = "Slot Machine" every minute, 3 = "Slot Machine" every 10 min)
{ (int8_t *)&Settings.cppStartHr, 5, 2, 0, 23, 4 }, // - start hour
{ (int8_t *)&Settings.brightnessAutoAdjust, 6, 1, false, true, true }, // brightness auto adjust
{ (int8_t *)&Settings.brightnessBoost, 6, 2, false, true, false } // - brighntess boost
};
/*
* Global variables
*/
struct G_t {
uint32_t timer1Step; // minimum adjustment step for Timer1 in µs
uint32_t timer1Period; // Timer1 period = timerPeriod / TIMER1_DIVIDER
uint32_t timer1PeriodFH; // Timer1 high fractional part
uint32_t timer1PeriodFL; // Timer1 low fractional part
uint32_t timer1PeriodLow; // Timer1 period rounded down to the multiple of timer1Step (µs)
uint32_t timer1PeriodHigh; // Timer1 period rounded up to the multiple of timer1Step (µs)
uint32_t timer2Step; // minimum adjustment step for Timer2 in µs
uint32_t timer2PeriodFH; // Timer2 high fractional part
uint32_t timer2PeriodFL; // Timer2 low fractional part
uint32_t timer2PeriodLow; // Timer2 period rounded down to the multiple of timer2Step (µs)
uint32_t timer2PeriodHigh; // Timer2 period rounded up to the multiple of timer2Step (µs)
volatile bool timer1UpdateFlag = true; // set to true if Timer1 parameters have been updated
volatile bool timer2UpdateFlag = true; // set to true if Timer2 parameters have been updated
uint32_t dcfSyncInterval = 0; // DCF77 synchronization interval in minutes
time_t lastDcfSyncTime = 0; // stores the time of last successful DCF77 synchronizaiton
tm lastDcfSyncTm = { 0 }; // local time of the last successful DCF77 synchronization as a tm structure
bool manuallyAdjusted = true; // prevent crystal drift compensation if clock was manually adjusted
bool dcfSyncActive = false; // enable/disable DCF77 synchronization
bool cppEffectEnabled = false; // Nixie digit cathod poison prevention effect is triggered every x seconds (avoids cathode poisoning)
uint32_t secTickMsStamp = 0; // millis() at the last second tick, used for accurate crystal drift compensation
volatile bool timer1TickFlag = false; // flag is set every second by the Timer1 ISR
volatile uint8_t timer2SecCounter = 0; // increments every time Timer2 ISR is called, used for converting 25ms into 1s ticks
volatile uint8_t timer2TenthCounter = 0; // increments every time Timer2 ISR is called, used for converting 25ms into 1/10s ticks
time_t systemTime = 0; // current system time (UTC)
tm *localTm = NULL; // pointer to the current local time structure
bool dstActive = false; // daylight saving time is currently active
NixieDigit_s timeDigits[NIXIE_NUM_TUBES]; // stores the Nixie display digit values of the current time
NixieDigit_s dateDigits[NIXIE_NUM_TUBES]; // stores the Nixie display digit values of the current date
MenuState_e menuState = SHOW_TIME_E; // state of the menu navigation state machine
#ifdef SERIAL_DEBUG
volatile uint8_t printTickCount = 0; // incremented by the Timer1 ISR every second
#endif
// analog pins as an array
const uint8_t analogPin[NUM_APINS] = { BUTTON0_APIN, BUTTON1_APIN, BUTTON2_APIN, LIGHTSENS_APIN, EXTPWR_APIN };
// dynamically defines the order of the menu items
MenuState_e menuOrder[MENU_ORDER_LIST_SIZE] = { SHOW_STOPWATCH_E, SHOW_TIMER_E, SHOW_SERVICE_E };
} G;
/*
* Various objects
*/
ButtonClass Button[NUM_APINS]; // array of push button objects
AlarmClass Alarm; // alarm clock object
CdTimerClass CdTimer; // countdown timer object
StopwatchClass Stopwatch; // stopwatch object
/***********************************
* Function prototypes
***********************************/
void eepromWriteSettings (void);
void timer1ISR (void);
void timer2ISR (void);
void timerCallback (bool);
time_t convertToLocalTime (time_t time);
time_t convertToUtcTime (time_t time);
void syncToDcf (void);
void timerCalibrate (time_t, int32_t);
void timerCalculate (void);
void updateDigits (void);
void adcRead (void);
void powerSave (void);
void reorderMenu (int8_t);
uint8_t weekDay (void);
int8_t calendarWeek (void);
uint8_t calendarWeekValidate (void);
void settingsMenu (void);
/***********************************
* Arduino setup routine
***********************************/
void setup() {
uint8_t i;
MCUSR = 0; // clear MCU status register
wdt_disable (); // and disable watchdog
#ifdef SERIAL_DEBUG
// initialize serial port
Serial.begin (SERIAL_BAUD);
#endif
#ifdef DEBUG_VALUES
// initialize the debug values
Debug.initialize ();
#endif
PRINTLN (" ");
PRINTLN ("+ + + N I X I E C L O C K + + +");
PRINTLN (" ");
// initialize the ADC
Adc.initialize (ADC_PRESCALER_128, ADC_DEFAULT);
// initialize the Nixie tube display
Nixie.initialize ( ANODE0_PIN, ANODE1_PIN, ANODE2_PIN, ANODE3_PIN, ANODE4_PIN, ANODE5_PIN,
BCD0_PIN, BCD1_PIN, BCD2_PIN, BCD3_PIN, COMMA_PIN, G.timeDigits, NIXIE_NUM_TUBES);
// initialize the brightness control algorithm
Brightness.initialize (EEPROM_BRIGHTNESS_ADDR, BRIGHTNESS_PIN);
// initilaize the DCF77 receiver
Dcf.initialize (DCF_PIN, DCF_START_EDGE, INPUT);
// reset system time
G.systemTime = 0;
G.localTm = localtime (&G.systemTime);
G.localTm->tm_sec = 0; // seconds after the minute - [ 0 to 59 ]
G.localTm->tm_min = 0; // minutes after the hour - [ 0 to 59 ]
G.localTm->tm_hour = 0; // hours since midnight - [ 0 to 23 ]
G.localTm->tm_mday = 1; // day of the month - [ 1 to 31 ]
G.localTm->tm_mon = 0; // months since January - [ 0 to 11 ]
G.localTm->tm_year = 101; // years since 1900
G.localTm->tm_isdst = 0;
G.systemTime = mktime (G.localTm);
set_system_time (G.systemTime);
// retrieve system settings period from EEOROM
eepromRead (EEPROM_SETTINGS_ADDR, (uint8_t *)&Settings, sizeof (Settings));
// validate the Timer1 period loaded from EEPROM
if (Settings.timerPeriod < TIMER_MIN_PERIOD || Settings.timerPeriod > TIMER_MAX_PERIOD)
Settings.timerPeriod = TIMER_DEFAULT_PERIOD;
#ifdef NIXIE_UPTIME_RESET
// force a nixie tube uptime reset
Settings.nixieUptime = NIXIE_UPTIME_RESET_VALUE;
eepromWriteSettings ();
PRINTLN ("[setup] Nixie uptime reset");
#endif
// reset all settings on first-time boot
if (Settings.settingsResetCode != SETTINGS_RESET_CODE) {
Brightness.initializeLut ();
Settings.alarm.hour = 06;
Settings.alarm.minute = 45;
Settings.alarm.mode = ALARM_OFF;
Settings.alarm.lastMode = ALARM_WEEKDAYS;
Settings.timerPeriod = TIMER_DEFAULT_PERIOD;
Settings.calWeekAdjust = 0;
Settings.nixieUptime = 0;
for (i = 0; i < SETTINGS_LUT_SIZE; i++) {
*SettingsLut[i].value = SettingsLut[i].defaultVal;
}
Settings.settingsResetCode = SETTINGS_RESET_CODE;
eepromWriteSettings ();
PRINTLN ("[setup] settings initialized");
}
PRINTLN ("[setup] other:");
// validate settings loaded from EEPROM
for (i = 0; i < SETTINGS_LUT_SIZE; i++) {
PRINT(" ");
PRINT (SettingsLut[i].idDigit1, DEC); PRINT ("."); PRINT (SettingsLut[i].idDigit0, DEC); PRINT ("=");
PRINTLN (*SettingsLut[i].value, DEC);
if (*SettingsLut[i].value < SettingsLut[i].minVal || *SettingsLut[i].value > SettingsLut[i].maxVal) *SettingsLut[i].value = SettingsLut[i].defaultVal;
}
PRINT ("[setup] timerPeriod=");
PRINTLN (Settings.timerPeriod, DEC);
// initialize Timer1 to trigger timer1ISR once per second
G.timer1Step = Timer1.initialize (Settings.timerPeriod / TIMER1_DIVIDER);
Timer1.attachInterrupt (timer1ISR);
// Timer2 is used for Chronometer and Countdown Timer features
// Timer2 has a maximum period of 32768us
G.timer2Step = Timer2.initialize (Settings.timerPeriod / (TIMER1_DIVIDER * TIMER2_DIVIDER));
Timer2.attachInterrupt (timer2ISR);
cli ();
Timer2.stop ();
Timer2.restart ();
sei ();
G.timer2SecCounter = 0;
G.timer2TenthCounter = 0;
// intialize the Timer1 and Timer2 parameters
timerCalculate();
#ifndef SERIAL_DEBUG
// initialize the Buzzer driver (requires serial communication pin)
Buzzer.initialize (BUZZER_PIN);
// enable/disable the brightness boost feature (requires serial communication pin)
Brightness.boostEnable (Settings.brightnessBoost);
#endif
// apply auto brightness setting
Brightness.autoEnable (Settings.brightnessAutoAdjust);
// initialize the alarm, countdown timer and stopwatch
Alarm.initialize (&Settings.alarm);
CdTimer.initialize (timerCallback);
Stopwatch.initialize (timerCallback);
// activate DCF synchronization if enabled
G.dcfSyncActive = Settings.dcfSyncEnabled;
// enable the watchdog
wdt_enable (WDT_TIMEOUT);
}
/*********/
/***********************************
* Arduino main loop
***********************************/
void loop() {
static bool cppWasEnabled = false, blankWasEnabled = false;
static int8_t hour = 0, lastHour = 0, minute = 0, wday = 0;
// actions to be executed once every second
if (G.timer1TickFlag) {
G.secTickMsStamp = millis ();
updateDigits (); // update the Nixie display digits
G.timer1TickFlag = false;
}
lastHour = hour;
hour = G.localTm->tm_hour;
minute = G.localTm->tm_min;
wday = G.localTm->tm_wday;
// start DCF77 reception at the specified hour
if (hour != lastHour && hour == Settings.dcfSyncHour && Settings.dcfSyncEnabled) G.dcfSyncActive = true;
Nixie.refresh (); // refresh the Nixie tube display
// refresh method is called many times across the code to ensure smooth display operation
// enable cathode poisoning prevention effect at a preset hour
if (Settings.cathodePoisonPrevent == 1 && hour == Settings.cppStartHr && G.menuState != SET_HOUR) {
if (!cppWasEnabled) {
G.cppEffectEnabled = true;
cppWasEnabled = true;
}
}
else {
G.cppEffectEnabled = false;
cppWasEnabled = false;
}
Nixie.refresh ();
// disable Nixie display at a preset hour interval in order to extend the Nixie tube lifetime
// or permanently disable Nixie Display
if (Settings.blankScreenMode == 4 ||
( ( (
(Settings.blankScreenMode >= 1 && Settings.blankScreenMode <= 3 ) && (
(Settings.blankScreenStartHr < Settings.blankScreenFinishHr && hour >= Settings.blankScreenStartHr && hour < Settings.blankScreenFinishHr ) ||
(Settings.blankScreenStartHr >= Settings.blankScreenFinishHr && (hour >= Settings.blankScreenStartHr || hour < Settings.blankScreenFinishHr) )
) &&
(Settings.blankScreenMode != 2 || (wday >= 1 && wday <= 5) ) && (Settings.blankScreenMode != 3 || wday == 0 || wday == 6)
) ||
(
(Settings.blankScreenMode2 >= 1 && Settings.blankScreenMode2 <= 3 ) && (
(Settings.blankScreenStartHr2 < Settings.blankScreenFinishHr2 && hour >= Settings.blankScreenStartHr2 && hour < Settings.blankScreenFinishHr2 ) ||
(Settings.blankScreenStartHr2 >= Settings.blankScreenFinishHr2 && (hour >= Settings.blankScreenStartHr2 || hour < Settings.blankScreenFinishHr2) )
) &&
(Settings.blankScreenMode2 != 2 || (wday >= 1 && wday <= 5) ) && (Settings.blankScreenMode2 != 3 || wday == 0 || wday == 6)
)
) && !G.cppEffectEnabled
)
) {
if (!blankWasEnabled && G.menuState == SHOW_TIME) {
G.menuState = SHOW_BLANK_E;
blankWasEnabled = true;
}
// re-enable blanking after switching to the service display /*or at the change of an hour*/
else if (G.menuState == SHOW_SERVICE /*|| ( G.menuState != SHOW_BLANK && G.menuState != SET_HOUR && hour != lastHour)*/ ) {
blankWasEnabled = false;
}
}
// disable blanking if blanking blankScreenMode != 4, CPP is enabled or outside the preset time intervals
else if (G.menuState == SHOW_BLANK) {
G.menuState = SHOW_TIME_E;
blankWasEnabled = false;
}
// ensure that blankWasEnabled is reset after blanking period elapses, even if not in blanking mode
else if (blankWasEnabled) {
blankWasEnabled = false;
}
Nixie.refresh ();
// write-back system settings to EEPROM every night
if (hour != lastHour && hour == 1 && G.menuState != SET_HOUR) {
Nixie.blank ();
eepromWriteSettings ();
PRINTLN ("[loop] >EEPROM");
}
Nixie.refresh ();
// toggle the decimal point for the DCF signal indicator
static bool dcfSyncWasActive = false;
if (G.dcfSyncActive) {
// DCF77 sync status indicator
Nixie.comma[1] = Dcf.level || !Settings.dcfSignalIndicator;
dcfSyncWasActive = true;
#ifdef DCF_DEBUG_VALUES
static bool debugValuesWereEnabled = false;
if (G.menuState == SHOW_TIME) {
Nixie.comma[2] = Dcf.debug[0];
Nixie.comma[3] = Dcf.debug[1];
Nixie.comma[4] = Dcf.debug[2];
Nixie.comma[5] = Dcf.debug[3];
debugValuesWereEnabled = true;
}
else if (debugValuesWereEnabled) {
Nixie.comma[2] = false;
Nixie.comma[3] = false;
Nixie.comma[4] = false;
Nixie.comma[5] = false;
debugValuesWereEnabled = false;
}
#endif
}
else if (dcfSyncWasActive) {
Nixie.comma[1] = false;
dcfSyncWasActive = false;
}
Nixie.refresh ();
adcRead (); // process the ADC channels
Nixie.refresh ();
settingsMenu (); // navigate the settings menu
Nixie.refresh ();
syncToDcf (); // synchronize with DCF77 time
Nixie.refresh ();
CdTimer.loopHandler (); // countdown timer loop handler
Nixie.refresh ();
Stopwatch.loopHandler (); // stopwatch loop handler
Nixie.refresh ();
Alarm.loopHandler (hour, minute, wday, G.menuState != SET_MIN && G.menuState != SET_SEC); // alarm clock loop handler
Nixie.refresh ();
Buzzer.loopHandler (); // buzzer loop handler
#ifdef SERIAL_DEBUG
// print the current time
if (G.printTickCount >= 15) {
PRINT ("[loop] ");
PRINTLN (asctime (localtime (&G.systemTime)));
//PRINT ("[loop] nixieUptime=");
//PRINTLN (Settings.nixieUptime, DEC);
G.printTickCount = 0;
}
#endif
}
/*********/
/***********************************
* Write settings back to EEPROM
***********************************/
void eepromWriteSettings (void) {
eepromWrite (EEPROM_SETTINGS_ADDR, (uint8_t *)&Settings, sizeof (Settings));
Brightness.eepromWrite ();
}
/*********/
/***********************************
* Timer1 ISR
* Triggered once every second by Timer 1
***********************************/
void timer1ISR (void) {
static uint32_t fractCountH = 0;
static uint32_t fractCountL = 0;
static bool toggleFlag = false;
uint8_t add1;
system_tick ();
if (Nixie.enabled) Settings.nixieUptime++;
if (fractCountL < G.timer1PeriodFL) add1 = 1;
else add1 = 0;
// dynamically adjust the timer period to account for fractions of a step
if (fractCountH < (G.timer1PeriodFH + add1) && (!toggleFlag || G.timer1UpdateFlag) ) {
Timer1.setPeriod (G.timer1PeriodHigh);
toggleFlag = true;
G.timer1UpdateFlag = false;
}
// dynamically adjust the timer period to account for fractions of a step
if (fractCountH >= (G.timer1PeriodFH + add1) && (toggleFlag || G.timer1UpdateFlag) ) {
Timer1.setPeriod (G.timer1PeriodLow);
toggleFlag = false;
G.timer1UpdateFlag = false;
}
fractCountH++;
if (fractCountH >= G.timer1Step ) {
fractCountH = 0;
fractCountL++;
if (fractCountL >= TIMER1_DIVIDER ) {
fractCountL = 0;
}
}
G.timer1TickFlag = true;
#ifdef SERIAL_DEBUG
G.printTickCount++;
#endif
}
/*********/
/***********************************
* Timer2 ISR
* Triggered once every 25ms by Timer 2
***********************************/
void timer2ISR (void) {
static uint32_t fractCountH = 0;
static uint32_t fractCountL = 0;
static bool toggleFlag = false;
uint8_t add1;
G.timer2SecCounter++;
G.timer2TenthCounter++;
// 1s period = 25ms * 40
if (G.timer2SecCounter >= TIMER2_DIVIDER) {
CdTimer.tick ();
G.timer2SecCounter = 0;
}
// 1/10s period = 25ms * 4
if (G.timer2TenthCounter >= TIMER2_DIVIDER / 10) {
Stopwatch.tick ();
G.timer2TenthCounter = 0;
}
if (fractCountL < G.timer2PeriodFL) add1 = 1;
else add1 = 0;
// dynamically adjust the timer period to account for fractions of a step
if (fractCountH < (G.timer2PeriodFH + add1) && (!toggleFlag || G.timer2UpdateFlag) ) {
Timer2.setPeriod (G.timer2PeriodHigh);
toggleFlag = true;
G.timer2UpdateFlag = false;
}
// dynamically adjust the timer period to account for fractions of a step
if (fractCountH >= (G.timer2PeriodFH + add1) && (toggleFlag || G.timer2UpdateFlag) ) {
Timer2.setPeriod (G.timer2PeriodLow);
toggleFlag = false;
G.timer2UpdateFlag = false;
}
fractCountH++;
if (fractCountH >= G.timer2Step ) {
fractCountH = 0;
fractCountL++;
if (fractCountL >= TIMER2_DIVIDER ) {
fractCountL = 0;
}
}
}
/*********/
/***********************************
* Watchdog expiry ISR
* takes over system ticking during Deep Sleep
***********************************/
ISR (WDT_vect) {
system_tick ();
}
/*********/
/***********************************
* Countdown timer and stopwatch callback function
***********************************/
void timerCallback (bool start) {
if (start) {
Timer2.start ();
}
else {
cli ();
Timer2.stop ();
Timer2.restart ();
sei ();
G.timer2SecCounter = 0;
G.timer2TenthCounter = 0;
}
}
/*********/
/***********************************
* Get the daylight saving time offset
***********************************/
inline int8_t getDstOffset (void) {
// Automatic DST
if (Settings.dstEnabled == 2) {
return G.dstActive;
}
// Manual DST
else {
return Settings.dstEnabled;
}
}
/*********/
/***********************************
* Convert UTC time to local time
***********************************/
time_t convertToLocalTime (time_t time) {
int8_t dst = getDstOffset ();
return time + (Settings.timeZone + dst) * (int32_t)ONE_HOUR;
}
/*********/
/***********************************
* Convert local time back to UTC time
***********************************/
time_t convertToUtcTime (time_t time) {
int8_t dst = getDstOffset ();
return time - (Settings.timeZone + dst) * (int32_t)ONE_HOUR;
}
/*********/
/***********************************
* Synchronize the system clock
* with the DCF77 time
***********************************/
void syncToDcf (void) {
static bool coldStart = true; // flag to indicate initial sync after power-up
static bool dcfWasActive = true;
static int32_t lastDeltaMs = 0;
uint8_t rv;
int32_t delta, deltaMs, ms;
time_t timeSinceLastSync;
time_t sysTime, dcfTime;
// enable DCF77 reception
if (G.dcfSyncActive) {
if (!dcfWasActive) {
Dcf.resumeReception ();
PRINTLN ("[syncToDcf] resume");
dcfWasActive = true;
}
}
else {
if (dcfWasActive) {
Dcf.pauseReception ();
PRINTLN ("[syncToDcf] pause");
dcfWasActive = false;
}
}
// read DCF77 time
rv = Dcf.getTime ();
Nixie.refresh (); // refresh the Nixie tube display
// DCF77 time has been successfully decoded
if (G.dcfSyncActive && rv == 0) {
ms = millis () - G.secTickMsStamp; // milliseconds elapsed since the last full second
sysTime = G.systemTime; // get the current system time
dcfTime = mktime (&Dcf.currentTm); // get the DCF77 timestamp (converted to UTC according to the value of tm_isdst)
delta = (int32_t)(sysTime - dcfTime); // time difference between the system time and DCF77 time in seconds
deltaMs = delta * 1000 + ms; // above time difference in milliseconds
timeSinceLastSync = dcfTime - G.lastDcfSyncTime; // time elapsed since the last successful DCF77 synchronization in seconds
// if no large time deviation has occurred or
// if two consecutive DCF77 timestamps produce a similar time deviation
// then update the system time
if (abs(deltaMs) < 500 || abs (deltaMs - lastDeltaMs) < 500) {
Timer1.stop ();
Timer1.restart (); // reset the beginning of a second
cli ();
set_system_time (dcfTime - 1); // apply the new system time, subtract 1s to compensate for initial tick
sei ();
Timer1.start ();
G.dstActive = (bool)Dcf.dcfTime.cest; // apply the new daylight saving time status
G.lastDcfSyncTime = dcfTime; // remember last sync time
G.dcfSyncActive = false; // pause DCF77 reception
// calibrate timer1 to compensate for crystal drift
if (abs (delta) < 60 && timeSinceLastSync > 1800 && !G.manuallyAdjusted && !coldStart) {
timerCalibrate (timeSinceLastSync, deltaMs);
}
PRINTLN ("[syncToDcf] updated time");
#ifdef SERIAL_DEBUG
G.printTickCount = 0; // reset RS232 print period
#endif
G.manuallyAdjusted = false; // clear the manual adjustment flag
coldStart = false; // clear the initial startup flag
}
lastDeltaMs = deltaMs; // needed for validating dthe ecoded DCF77 timestamp
}
#ifdef SERIAL_DEBUG
// debug printing
// timestamp validation failed
if (rv < 31) {
PRINT ("[syncToDcf] Dcf.getTime=");
PRINTLN (rv, DEC);
if (rv == 0) {
PRINT ("[syncToDcf] delta=");
PRINTLN (delta, DEC);
}
PRINT ("[syncToDcf] ");
PRINT (asctime (&Dcf.currentTm));
PRINTLN (" *");
}
// sync bit has been missed, bits buffer overflow
else if (rv == 31) {
PRINT ("[syncToDcf] many bits=");
PRINTLN (Dcf.lastIdx, DEC);
Dcf.lastIdx = 0;
}
// missed bits or false sync bit detected
else if (rv == 32) {
PRINT ("[syncToDcf] few bits=");
PRINTLN (Dcf.lastIdx, DEC);
Dcf.lastIdx = 0;
}
#endif
}
/*********/
/***********************************
* Calibrate Timer1 frequency in order to compensate for the oscillator drift
* Periodically back-up the Timer1 period to EEPROM
***********************************/
void timerCalibrate (time_t measDuration, int32_t timeOffsetMs) {
int32_t drift;
drift = (timeOffsetMs * 1000 * TIMER1_DIVIDER) / (int32_t)measDuration;
Settings.timerPeriod += drift;
timerCalculate ();
#ifdef DEBUG_VALUES
Debug.set ( 0, (int32_t)measDuration );
Debug.set ( 1, timeOffsetMs);
Debug.set ( 2, drift);
#endif
PRINT ("[timerCalibrate] measDuration=");
PRINTLN (measDuration, DEC);
PRINT ("[timerCalibrate] timeOffsetMs=");
PRINTLN (timeOffsetMs, DEC);
PRINT ("[timerCalibrate] drift=");
PRINTLN (drift, DEC);
PRINT ("[timerCalibrate] timerPeriod=");
PRINTLN (Settings.timerPeriod, DEC);
}
/*********/
/***********************************
* Derive the Timer1 and Timer2 parameters
* out of the Timer1 period
***********************************/
void timerCalculate (void) {
volatile uint32_t f, fh ,fl, low, high;
if (Settings.timerPeriod < TIMER_MIN_PERIOD) Settings.timerPeriod = TIMER_MIN_PERIOD;
if (Settings.timerPeriod > TIMER_MAX_PERIOD) Settings.timerPeriod = TIMER_MAX_PERIOD;
G.timer1Period = Settings.timerPeriod / TIMER1_DIVIDER;
f = Settings.timerPeriod % (G.timer1Step * TIMER1_DIVIDER);
fh = f / TIMER1_DIVIDER;
fl = f % TIMER1_DIVIDER;
low = (Settings.timerPeriod - f) / TIMER1_DIVIDER;
high = low + G.timer1Step;
cli ();
G.timer1PeriodFH = fh;
G.timer1PeriodFL = fl;
G.timer1PeriodLow = low;
G.timer1PeriodHigh = high;
G.timer1UpdateFlag = true;
sei ();
f = G.timer1Period % (G.timer2Step * TIMER2_DIVIDER);
fh = f / TIMER2_DIVIDER;
fl = f % TIMER2_DIVIDER;
low = (G.timer1Period - f) / TIMER2_DIVIDER;
high = low + G.timer2Step;
cli ();
G.timer2PeriodFH = fh;
G.timer2PeriodFL = fl;
G.timer2PeriodLow = low;
G.timer2PeriodHigh = high;
G.timer2UpdateFlag = true;
sei ();
}
/*********/
/***********************************
* Update the Nixie display digits
***********************************/
void updateDigits () {
static int8_t lastMin = 0;
time_t locTime;