aboutsummaryrefslogtreecommitdiffstats
path: root/main.c
blob: 2b8402fff6525ed5b36bfb3f6ec7d52e2a87f3ca (plain)
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
#include "conf.h"                          //Configuration settings
#include "main.h"                          //Declarations for main

//Initialize variables
#ifdef ADC
// Initialize variable for LDR
unsigned int ldr = 0;
#endif

// Initialize variable for VFD brightness level
unsigned int brtlvl_chg = 0;

// Boolean if external interrupt occurs
unsigned int update = 0;

// Boolean for setting time manually with user input
unsigned int edit_datetime = 0;

// Initialize variables for date time and alarms
unsigned int sec = 0;
unsigned int min = 0;
unsigned int hour = 0;
unsigned int day = 1;
unsigned int date = 1;
unsigned int month = 1;
unsigned int year = 00;
unsigned int century = 20;
unsigned int alarm1_sec = 0;
unsigned int alarm1_min = 0;
unsigned int alarm1_hour = 0;
unsigned int alarm2_min = 0;
unsigned int alarm2_hour = 0;
unsigned int status_reg = 0;
unsigned int alarm1_status = 0;
unsigned int alarm2_status = 0;
unsigned int control_reg = 0;

// Initialize variables for temperature
unsigned int temperature_lsb = 0;
int temperature_msb = 0;
unsigned char temp_sign = ' ';

void main(void) {
#ifdef ADC
    TRISA0 = 0x01; // RA is input (ADC)
#endif
    TRISBbits.TRISB2 = 1;
    TRISBbits.TRISB4 = 1;
    TRISBbits.TRISB5 = 1;

    GIE = 0; //Disable interrupts until set up    
    OPTION_REGbits.nRBPU = 0; // PORTB pull-ups are enabled by individual port latch values
    INTE = 1; // Enable RB0 as external interrupt
    GIE = 1; // Enable all interrupts from now on

    TRISC = 0x00; // Set PORTC as outputs
    PORTC = 0x00; // Set all PORTC pins LOW

    TRISD = 0x00; // Set PORTD as outputs
    PORTD = 0x00; // Set all PORTD pins LOW

#ifdef DEBUG
    Initialize_UART(); //Initialize UART module                    
    UART_send_string(CLS); // Clear screen
    UART_send_string(CURSOR(12, 23)); // Set cursor at line 12, column 23
    UART_send_string(GREEN); // Set Green
    UART_send_string("UART Module Initialized and active\r\n");
    UART_send_string(CLRATTR); // No color
#endif

    I2C_Master_Init(100000); // Init I2C Master with 100KHz Clock
#ifdef DEBUG
    UART_send_string(CURSOR(13, 24)); // Set cursor at line 13, column 24
    UART_send_string(GREEN); // Set Green
    UART_send_string("I2C Module Initialized and active\r\n");
    UART_send_string(CLRATTR); // No color
#endif

#ifdef ADC
    Adc_Init(); // Init I2C Master with 100KHz Clock
#ifdef DEBUG
    UART_send_string(CURSOR(14, 24)); // Set cursor at line 14, column 24
    UART_send_string(GREEN); // Set Green
    UART_send_string("ADC Module Initialized and active\r\n");
    UART_send_string(CLRATTR); // No color
#endif
#endif

    Lcd_Init();
#ifdef DEBUG
    UART_send_string(CURSOR(15, 24)); // Set cursor at line 15, column 24
    UART_send_string(GREEN); // Set Green
    UART_send_string("LCD Module Initialized and active\r\n");
    UART_send_string(CLRATTR); // No color
#endif

#ifdef VFD
    Vfd_Set_Brightness(0); // Maximum 0 - Minimum 3
#endif

    display_Intro();
    display_Lcd_Layout();

    /*
     * Set an initial date time via initial program variables
     * Currently 00:00:00 1/1/00 and Sunday (day of week as 1)
     */

    //Set_Time();
    //Set_Date();
    //Set_DayOfWeek(Get_DayOfWeek(year, month, date));

    /*
     * isr expects 1Hz clock from RTC. This will update clock each second
     * While interrupted, clock is updating and set button will be ignored.
     * Here we set Status register 0Eh bit4 and bit3 as 0b00 for 1Hz.
     * 0x40 sets bit6 as high so BBSQW is enabled and 1Hz square wave results
     * out the !INT/SQW pin of the device.
     */
    Set_Sqwe(0x40); //1Hz

#ifdef VFD
    Vfd_Set_Brightness(3); //Max brightness 3 - minimum
#endif


    while (1) {

        /* 
         * If 1Hz interrupt from RTC received, isr sets update to 1
         * Update time/date/alarm/temp/other variables from RTC
         * Update digits on display device
         * reset update boolean until next RTC 1Hz interrupt
         * delay 500ms for a perception of ':'s blinking at 1/2 duty cycle
         */

        if (update) {
            Lcd_Set_Cursor(1, 3);
            Lcd_Write_Char(':');
            Lcd_Set_Cursor(1, 6);
            Lcd_Write_Char(':');
            Update_Current_Date_Time();
            Read_Alarms_Temp();
            Get_Alarm_Status();
            format_Temperature();
            update_Display();
            update = 0;
            __delay_ms(500);
        } else {
            Lcd_Set_Cursor(1, 3);
            Lcd_Write_Char(' ');
            Lcd_Set_Cursor(1, 6);
            Lcd_Write_Char(' ');
        }

        /* 
         * Edit time when Set button is pressed (Active low)
         * set edit_Date_Time to 1 to enter edit date/time loop
         */

        if (!SETB) {
            __delay_ms(250);
            edit_Date_Time();
        }

        /*
         * If ADC is enabled then read from ADC channel into ldr
         * If VFD available set brtlvl (ldr defaulted to 0)
         * brtlvl is (ldr / 256) and brtlvl_chg is compared with brtlvl
         * New brightness level is set when a difference occurs
         */

#ifdef ADC
        // Get current LDR reading and calculate for brightness levels 0 - 3
        ldr = Adc_Read(0);
#ifdef VFD
        if (brtlvl_chg != brtlvl) {
            Vfd_Set_Brightness(brtlvl);
            brtlvl_chg = brtlvl;
        }
#endif
#endif

#ifdef DEBUG
        UART_send_string(CURSOR(19, 1));
        sprintf(buf, "%sTIME:%s\t%02d:%02d:%02d\t%sDATE:%s\t%02d/%02d/%02d\r\n", YELLOW, CLRATTR,
                hour, min, sec, YELLOW, CLRATTR, date, month, year);
        UART_send_string(buf);
        sprintf(buf, "%sAL1:%s\t%02d:%02d:%02d\t%sSTATUS:%s %d\r\n", YELLOW,
                CLRATTR, alarm1_hour, alarm1_min, alarm1_sec, YELLOW,
                CLRATTR, alarm1_status);
        UART_send_string(buf);
        sprintf(buf, "%sAL2:%s\t%02d:%02d\t\t%sSTATUS:%s %d\r\n", YELLOW,
                CLRATTR, alarm2_hour, alarm2_min, YELLOW, CLRATTR,
                alarm2_status);
        UART_send_string(buf);
        sprintf(buf, "%sWKDAY:%s\t%d\t\t%sDAY:%s\t%s\r\n", YELLOW, CLRATTR,
                day, YELLOW, CLRATTR, Get_WeekDay(day));
        UART_send_string(buf);
        sprintf(buf, "%sTEMP:\t%s%c%c%c.%c%cC%s\t\t%sLDR:%s\t\%04d %d\r\n",
                YELLOW, CLRATTR, temp_sign, temp_2, temp_1, temp_0, 0xB0,
                CLRATTR, YELLOW, CLRATTR, ldr, brtlvl);
        UART_send_string(buf);
        sprintf(buf, "%sISR:\t%s%d", YELLOW, CLRATTR, update);
        UART_send_string(buf);
#endif
    }
}

/*
 * DS3231 11h has MSB of temp and 12h has LSB of temp
 * MSB and LSB bits 7 have sign
 * MSB bits 0-7 have DATA
 * LSB bits 7 and 6 have DATA
 * 10-bits with 0.25 resolution (this program drops hundredths place)
 */

void format_Temperature() {

    // If MSB negative then get 2's complement and sign for display to '-'
    // otherwise MSB is positive and we set sign for display to '+'
    if (temperature_msb < 0) {
        temperature_msb *= -1;
        temp_sign = '-';
    } else {
        temp_sign = '+';
    }

    //Shift LSB fractional value 6 bits to the right so b7 & b6 are b1 & b0
    temperature_lsb >>= 6;

    //Fractional is 0b00, 0b01, 0b10, 0b11. Multiply by 25 for 00, 25, 50, 75
    temperature_lsb *= 25;
}

// Determine Alarm status from control register 0Fh bits 0 (A1F) and 1 (A2F)

void Get_Alarm_Status() {
    alarm1_status = control_reg & 0x01; // Read alarm1 A1F bit
    alarm2_status = (control_reg >> 1) & 0x01; // Read alarm2 A2F bit
}

// Separate data into tens and ones units to display with character displays

void display_Digit(unsigned int data) {
    Lcd_Write_Char(MSB(data));
    Lcd_Write_Char(LSB(data));
}

// Provides the user program info on startup

void display_Intro() {
    // Give an intro message on the LCD
    Lcd_Clear();
    Lcd_Set_Cursor(1, 4);
    Lcd_Write_String("Desk Clock");
    Lcd_Set_Cursor(2, 15);
    Lcd_Write_String("V1");
    __delay_ms(1000); //display for 1sec 
}

// Provides the user the current layout of time/date/temp for the display

void display_Lcd_Layout() {
    // Setup time date display format
    Lcd_Clear();
    Lcd_Set_Cursor(1, 1);
    Lcd_Write_String("HH:mm:ss -PP.P");
    Lcd_Write_Char(0xDF);
    Lcd_Write_Char('C');
    Lcd_Set_Cursor(2, 1);
    Lcd_Write_String(" ddd DD/MM/CCYY ");

    __delay_ms(1000);
}

// Updates the display with values that change and not static info

void update_Display() {
    // Display Hours
    Lcd_Set_Cursor(1, 1);
    display_Digit(hour);

    // Display minutes
    Lcd_Set_Cursor(1, 4);
    display_Digit(min);

    // Display seconds
    Lcd_Set_Cursor(1, 7);
    display_Digit(sec);

    // Display day
    Lcd_Set_Cursor(2, 6);
    display_Digit(date);

    // Display month
    Lcd_Set_Cursor(2, 9);
    display_Digit(month);

    // Display century
    Lcd_Set_Cursor(2, 12);
    display_Digit(century);

    // Display year
    Lcd_Set_Cursor(2, 14);
    display_Digit(year);

    // Display day of week
    Lcd_Set_Cursor(2, 2);
    Lcd_Write_String(Get_WeekDay(day));

    // Display temperature
    Lcd_Set_Cursor(1, 10);
    Lcd_Write_Char(temp_sign);
    display_Digit(temperature_msb);
    Lcd_Set_Cursor(1, 14);
    Lcd_Write_Char(MSB(temperature_lsb));

    // Chime at top of hour
    if (min == 00 && sec == 00) {
        alarm(2);
    }

    // Chime at half of hour
    if (min == 30 && sec == 00) {
        alarm(1);
    }
}

/*
 * Called when set button is pressed and S is in lower right of display for
 * set mode. Immediately goes into setting the hour. Each time SETB is pressed:
 * minutes then seconds then year then month then date then update RTC and
 * edit flag is cleared and clock continues as normal. Sets :'s to display for
 * time in case they were blanked.
 * 
 * Change detection variables are set before values are changed and compared
 * as user goes through fields. If a change is detected then updateRTC flag is
 * enabled causing the RTC to be updated.
 * 
 * As month/date is selected, functions determine if year is leap or not,
 * the max number of days in each month, and displays the day of the week.
 * ex: 29/02/2020 is Sat and leap year with max date to select in Feb as 29.
 * 
 * Order to edit is hour -> min -> sec -> year -> month -> day
 * Pressing Set after day results in RTC being updated with current edit values.
 */

void edit_Date_Time(void) {
    // Variable to determine if RTC is updated or not (date/time valus change)
    int updateRTC = 0;

    // Variables set to current edit value and if a mismatch from user input
    // then updateRTC is set to 1 and RTC will be updated
    unsigned int hour_org = hour;
    unsigned int min_org = min;
    unsigned int sec_org = sec;
    unsigned int year_org = year;
    unsigned int month_org = month;
    unsigned int date_org = date;

    Lcd_Set_Cursor(2, 16);
    Lcd_Write_Char('S');
    edit_datetime++;
    while (edit_datetime > 0 && edit_datetime < 7) {

        // Set colons if not enabled when Set button is pressed
        Lcd_Set_Cursor(1, 3);
        Lcd_Write_Char(':');
        Lcd_Set_Cursor(1, 6);
        Lcd_Write_Char(':');

        switch (edit_datetime) {
            case 1: //Hours
                Lcd_Set_Cursor(2, 16);
                Lcd_Write_Char('h');
                if (!DECR) {
                    __delay_ms(250);
                    if (hour == 0) {
                        hour = 23;
                    } else {
                        hour -= 1;
                    }
                    Lcd_Set_Cursor(1, 1);
                    display_Digit(hour);

                } else if (!INCR) {
                    __delay_ms(250);
                    if (hour + 1 > 23) {
                        hour = 0;
                    } else {
                        hour += 1;
                    }

                    Lcd_Set_Cursor(1, 1);
                    display_Digit(hour);
                }

                break;

            case 2: //Minutes
                Lcd_Set_Cursor(2, 16);
                Lcd_Write_Char('m');
                if (!DECR) {
                    __delay_ms(250);
                    if (min == 0) {
                        min = 59;
                    } else {
                        min -= 1;
                    }
                    Lcd_Set_Cursor(1, 4);
                    display_Digit(min);

                } else if (!INCR) {
                    __delay_ms(250);
                    if (min + 1 > 59) {
                        min = 0;
                    } else {
                        min += 1;
                    }

                    Lcd_Set_Cursor(1, 4);
                    display_Digit(min);
                }

                break;

            case 3: //Seconds
                Lcd_Set_Cursor(2, 16);
                Lcd_Write_Char('s');
                if (!DECR) {
                    __delay_ms(250);
                    if (sec == 0) {
                        sec = 59;
                    } else {
                        sec -= 1;
                    }
                    Lcd_Set_Cursor(1, 7);
                    display_Digit(sec);
                    if (sec_org != sec) {
                        updateRTC = 1;
                    }

                } else if (!INCR) {
                    __delay_ms(250);
                    if (sec + 1 > 59) {
                        sec = 0;
                    } else {
                        sec += 1;
                    }

                    Lcd_Set_Cursor(1, 7);
                    display_Digit(sec);
                    if (sec_org != sec) {
                        updateRTC = 1;
                    }
                }

                break;

            case 6: //Date
                Lcd_Set_Cursor(2, 16);
                Lcd_Write_Char('D');
                if (!DECR) {
                    __delay_ms(250);
                    if (date - 1 == 0) {
                        date = Get_Days_In_Month(year, month);
                    } else {
                        date -= 1;
                    }

                    Lcd_Set_Cursor(2, 2);
                    Lcd_Write_String(Get_WeekDay(Get_DayOfWeek(year, month, date)));
                    Lcd_Set_Cursor(2, 6);
                    display_Digit(date);

                } else if (!INCR) {
                    __delay_ms(250);
                    //TODO USE Formula to get days based on month year (and leap)
                    if (date + 1 > Get_Days_In_Month(year, month)) {
                        date = 1;
                    } else {
                        date += 1;
                    }

                    Lcd_Set_Cursor(2, 2);
                    Lcd_Write_String(Get_WeekDay(Get_DayOfWeek(year, month, date)));
                    Lcd_Set_Cursor(2, 6);
                    display_Digit(date);
                }

                break;

            case 5: //Month
                Lcd_Set_Cursor(2, 16);
                Lcd_Write_Char('M');
                if (!DECR) {
                    __delay_ms(250);
                    if (month - 1 == 0) {
                        month = 12;
                    } else {
                        month -= 1;
                    }
                    Lcd_Set_Cursor(2, 9);
                    display_Digit(month);

                } else if (!INCR) {
                    __delay_ms(250);
                    if (month + 1 > 12) {
                        month = 1;
                    } else {
                        month += 1;
                    }

                    Lcd_Set_Cursor(2, 9);
                    display_Digit(month);
                }

                break;

            case 4: //Year
                Lcd_Set_Cursor(2, 16);
                Lcd_Write_Char('Y');
                if (!DECR) {
                    __delay_ms(250);
                    if (year == 0) {
                        year = 99;
                    } else {
                        year -= 1;
                    }
                    Lcd_Set_Cursor(2, 14);
                    display_Digit(year);

                } else if (!INCR) {
                    __delay_ms(250);
                    if (year + 1 > 99) {
                        year = 0;
                    } else {
                        year += 1;
                    }

                    Lcd_Set_Cursor(2, 14);
                    display_Digit(year);
                }

                break;

                //TODO Maybe add a case to edit century on display

            default:
                break;
        }

        if (!SETB) {
            __delay_ms(250);
            edit_datetime++;
        }
    }

    // TODO Edit alarms

    /*
     * Set button pressed after Date selection then we set the values in RTC.
     * Unset edit_datetime until next time set button is pressed and clear
     * field text from lower right of display.
     */
    if (edit_datetime > 6) {
        Lcd_Set_Cursor(2, 16);
        Lcd_Write_String(" ");
        edit_datetime = 0;
        
        /*
         * If any date/time field was changed, clear updateRTC field and
         * update RTC.
        */
        if(hour_org != hour || min_org != min || sec_org != sec
                || year_org != year || month_org != month || date_org != date) {
            updateRTC = 0;
            Set_Time();
            Set_DayOfWeek(Get_DayOfWeek(year, month, date));
            Set_Date();
        }
    }
}

/*
 * interrupt service routine (isr) triggered by external interrupt pin RB0 by
 * RTC (DS3231) SQW output at 1Hz. The update flag is set so that the display
 * is updated with current RTC date/time/temp info and updates display
 * brightness if enabled
 */
void __interrupt() isr(void) {
    if (INTF == 1) { // External interrupt detected
        update = 1;
        INTF = 0;
    }
}