Initial commit
[the_perfect_clock.git] / the_perfect_clock.ino
1 // "The Perfect Clock" 
2
3 // Copyright (C) 2019-2020 by Art Cancro <ajc@citadel.org>
4
5 // My perfect clock has no buttons and cannot be set manually.  This version uses a WWVB receiver module
6 // attached to pin D9 of the Arduino, and sets the clock any time it receives a complete frame.  The clock
7 // is kept without an RTC, simply using the millis() timer.  When time is set, it is displayed on
8 // a 7-segment array connected using an HT16K33 decoder/driver (yes, an Adafruit backpack).  Our display
9 // can also display at 15 different brightness levels, so we dim it when the room is dark to avoid
10 // blasticating a dark room with super-bright LED display.
11
12 // The clock is hard coded to use US Eastern time with DST in effect whenever WWVB is announcing it.
13
14 const uint8_t wwvb = 9;       // pin on which WWVB signal will be received
15 const uint8_t greenled = 2;   // An LED attached to this pin will illuminate if the time has been set within the last 24 hours
16 const uint8_t yellowled = 3;  // An LED attached to this pin will illuminate if we are currently receiving a clean frame
17 const uint8_t redled = 4;     // An LED attached to this pin will pulse for 1 ms every second
18 const uint8_t photocell = A0; // Attach a photocell with a 10K voltage divider to this pin
19 const uint8_t addr = 0x70;    // I2C address of HT16K33 (using Adafruit backpack with digits on 0,1,3,4; dots on 2)
20
21 #define MILLISECONDS_PER_MINUTE 60080   // Nominally 60000; adjust if your board runs fast or slow
22
23 // This is a simple BCD-to-7-segment font.  It includes 0x0A through 0x0F even though they're not needed for a time clock.
24 const uint8_t sevensegfont[] = { 63, 6, 91, 79, 102, 109, 125, 7, 127, 111, 119, 124, 57, 94, 121, 113 };
25 const uint8_t firstcolfont[] = { 0, 6, 91 };    // this version of the font is for the first position
26
27 #include <Wire.h>                               // I2C library to drive the HT16K33 display
28
29 int hour = 0;
30 int minute = 0;
31 unsigned long millisecond = 0;
32 unsigned long previous_millis = 0;
33 unsigned long last_sync = -86398000;
34 uint16_t displayBuffer[8];    // Digit buffer for HT16K33
35 int previous_minute = 61;     // What the minute was previously; we use this to detect whether an update is needed
36 int this_pulse = 0;           // Value of the current pulse received
37 int previous_pulse = 0;       // Value of the previous pulse received (two "mark" bits == new frame)
38 int start_of_pulse = 0;       // The value of the millis() timer when the current pulse began
39 uint8_t framebuf[60];         // We store the entire 60-bit frame here
40 uint8_t framesync = 0;        // Nonzero if we've received all good pulses since the start of the frame
41 int position_in_frame = 0;    // Where we are in the frame (1 bit per second)
42 int previous_signal = 0;      // "high" or "low" received on the previous cycle (so we can do edge detection)
43 int time_is_set = 0;          // nonzero when time has been set at least once
44
45 void setup()
46 {
47         int i;
48
49         pinMode(LED_BUILTIN, OUTPUT);   // The built-in LED will display the raw WWVB signal pulses
50         pinMode(greenled, OUTPUT);    // This LED will illuminate if the time has been set within the last 24 hours
51         pinMode(yellowled, OUTPUT);   // This LED will illuminate if we are currently receiving a clean frame
52         pinMode(redled, OUTPUT);      // This LED pulses for 1 ms every second
53         pinMode(wwvb, INPUT);                 // Input pin for WWVB receiver signal
54   pinMode(photocell, INPUT);    // Input pin for photocell
55
56         Wire.begin();                   // Initialize I2C
57
58         Wire.beginTransmission(addr);
59         Wire.write(0x21);               // turn on oscillator
60         Wire.endTransmission();
61
62         Wire.beginTransmission(addr);
63         Wire.write(0xE1);               // brightness (max is 15)
64         Wire.endTransmission();
65
66         Wire.beginTransmission(addr);
67         Wire.write(0x81);               // no blinking or blanking
68         Wire.endTransmission();
69
70         displayBuffer[0] = 0;
71         displayBuffer[1] = 0;
72         displayBuffer[2] = 16;
73         displayBuffer[3] = 0;
74         displayBuffer[4] = 0;
75         show();
76 }
77
78
79 // Note: only write to the display when the readout needs to be updated.
80 // Speaking I2C on every loop iteration jams the WWVB receiver.
81 void loop()
82 {
83         unsigned long m = millis();
84         digitalWrite(redled, (m%1000) ? LOW : HIGH);
85         if (m != previous_millis) {
86                 millisecond += (m - previous_millis);
87                 if (millisecond >= MILLISECONDS_PER_MINUTE) {
88                         millisecond -= MILLISECONDS_PER_MINUTE;
89                         ++minute;
90                         if (minute > 59) {
91                                 minute = 0;
92                                 ++hour;
93                                 if (hour > 23) {
94                                         hour = 0;
95                                 }
96                         }
97                 }
98         }
99         previous_millis = m;
100
101         int pulse_length;
102         int signal = digitalRead(wwvb);                                                         // is the input high or low right now?
103         digitalWrite(LED_BUILTIN, signal);                                              // use the onboard LED to show the signal
104
105         if (signal && (!previous_signal)) {                         // leading edge of pulse detected
106                 start_of_pulse = millis();
107         }
108         else if ((!signal) && (previous_signal)) {                  // trailing edge of pulse detected
109                 pulse_length = millis() - start_of_pulse;
110
111                 if (pulse_length > 150 && pulse_length < 250) {                 // "0" bit ~= 200 ms (represented as "0")
112                         this_pulse = 0;
113                 } else if (pulse_length > 450 && pulse_length < 550) {          // "1" bit ~= 500 ms (represented as "1")
114                         this_pulse = 1;
115                 } else if (pulse_length > 750 && pulse_length < 850) {          // marker bit ~= 800 ms (represented as "2")
116                         this_pulse = 2;
117                 } else {
118                         this_pulse = 15;                                        // bad pulse (represented as "15")
119                         framesync = 0;                                          // throw the whole frame away
120                 }
121
122                 // BEGIN -- THINGS TO DO AT THE END OF A PULSE
123
124                 if ((this_pulse == 2) && (previous_pulse == 2)) {               // start of a new frame!
125
126                         if (framesync == 1) {
127                                 set_the_time();                                                         // We have a whole good frame.  Set the clock!
128                         }
129       else if ((!framesync) && (time_is_set)) {
130         snap_to_zero();                                       // We don't have a whole frame, but we know it's :00 seconds now.
131       }
132
133                         framesync = 1;
134                         position_in_frame = 0;
135                 }
136
137                 if (framesync) {                                                                        // yellow LED = we currently have frame sync
138                         analogWrite(yellowled, 10);                                             // (we run it at a low intensity)
139                 }
140                 else {
141                         digitalWrite(yellowled, LOW);
142                 }
143
144                 if ((framesync) && (position_in_frame < 60)) {
145                         framebuf[position_in_frame++] = this_pulse;
146                 }
147
148                 previous_pulse = this_pulse;
149
150                 // END -- THINGS TO DO AT THE END OF A PULSE
151         }
152
153         previous_signal = signal;
154
155         // Update the display only if it's a new minute.
156
157         if (time_is_set && (minute != previous_minute)) {
158                 previous_minute = minute;
159                 int h12 = (hour % 12) ;
160                 if (h12 == 0) h12 = 12;
161                 displayBuffer[0] = firstcolfont[h12 / 10];
162                 displayBuffer[1] = sevensegfont[h12 % 10];
163                 displayBuffer[2] = (hour<12) ? 0x06 : 0x0a;                     // AM or PM dot , colon always on
164                 displayBuffer[3] = sevensegfont[minute / 10];
165                 displayBuffer[4] = sevensegfont[minute % 10];
166                 show();
167         }
168
169         if ((m - last_sync) < 86400000) {                                               // green LED = got a good sync in the last 24 hours
170                 digitalWrite(greenled, HIGH);
171         }
172         else {
173                 digitalWrite(greenled, LOW);
174         }
175 }
176
177
178 // Write the display buffer to the display
179 void show()
180 {
181   // display the time
182         Wire.beginTransmission(addr);
183         Wire.write(0x00);       // start at address 0x0
184         for (int i = 0; i < 5; i++) {
185                 Wire.write(displayBuffer[i] & 0xFF);
186                 Wire.write(displayBuffer[i] >> 8);
187         }
188         Wire.endTransmission();
189  
190   // set the brightness
191   int light_level = analogRead(photocell) / 64;
192   if (light_level < 1) {
193     light_level = 1;
194   }
195   if (light_level > 15) {
196     light_level = 15;
197   }
198   Wire.beginTransmission(addr);
199   Wire.write(0xE0 + light_level);     // set the display brightness
200   Wire.endTransmission();
201 }
202
203
204 // Set the software clock to the WWVB time currently in the buffer
205 void set_the_time()
206 {
207         int i, newhour, newminute, dst;
208
209         // These six positions MUST contain marker bits.
210         // If any of them do not, we are looking at a corrupt frame.
211         int markers[] = { 0, 9, 19, 39, 49, 59 };
212         for (i=0; i<6; ++i) {
213                 if (framebuf[markers[i]] != 2) {
214                         return;
215                 }
216         }
217
218         newhour = (framebuf[12] ? 20 : 0);
219         newhour += (framebuf[13] ? 10 : 0);
220         newhour += (framebuf[15] ? 8 : 0);
221         newhour += (framebuf[16] ? 4 : 0);
222         newhour += (framebuf[17] ? 2 : 0);
223         newhour += (framebuf[18] ? 1 : 0);
224         if ((newhour < 0) || (newhour > 23)) {
225                 return;                         // reject impossible hours
226         }
227
228         newminute = (framebuf[1] ? 40 : 0);
229         newminute += (framebuf[2] ? 20 : 0);
230         newminute += (framebuf[3] ? 10 : 0);
231         newminute += (framebuf[5] ? 8 : 0);
232         newminute += (framebuf[6] ? 4 : 0);
233         newminute += (framebuf[7] ? 2 : 0);
234         newminute += (framebuf[8] ? 1 : 0);
235         if ((newminute < 0) || (newminute > 59)) {
236                 return;                         // reject impossible minutes
237         }
238
239         // advance 1 minute because WWVB gives the *previous* minute
240         newminute += 1;
241         if (newminute >= 60) {
242                 newminute = newminute % 60;
243                 newhour += 1;
244         }
245
246         // US Eastern time (yes it is hard coded)
247         newhour -= 5;
248
249         // DST (FIXME make this adjustable)
250         dst = (framebuf[57] ? 2 : 0);
251         dst += (framebuf[58] ? 1 : 0);
252         switch(dst) {
253                 case 0:                         // dst not in effect (make no adjustments)
254                         break;
255                 case 2:                         // dst begins today (adjust if local hour > 2)
256                         if (newhour >= 2) {
257                                 ++newhour;
258                         }
259                         break;
260                 case 3:                         // dst is in effect (always adjust)
261                         ++newhour;
262                         break;
263                 case 1:                         // dst ends today (adjust if local hour < 2)
264                         if (newhour < 2) {
265                                 ++newhour;
266                         }
267                         break;
268         }
269
270         // If we went back to the previous day, adjust so that hour > 0
271         if (newhour < 0) {
272                 newhour += 24;
273         }
274
275         // Set the software clock:
276         // * We have decoded the hour and minute from the signal
277         // * This function always gets called *after* the first pulse at :00, so we set the millisecond to 800
278         hour = newhour;
279         minute = newminute;
280         millisecond = 800;
281         time_is_set = 1;
282
283         // Let's remember the last time we synced the clock
284         last_sync = millis();
285 }
286
287
288 // Adjust the time to :00.8 seconds at the nearest minute.
289 void snap_to_zero()
290 {
291   if ((millisecond > 0) && (millisecond < 15000)) {   // If the second is from :00.0 to :15.0
292     millisecond = 800;                                // snap back to :00.8
293   }
294   else if (millisecond > 45000) {                     // If the second is :45.0 or above
295     millisecond = MILLISECONDS_PER_MINUTE + 800;      // snap forward to :00.8 (minute will advance automatically)
296   }
297 }