]> git.sur5r.net Git - c128-kasse/blob - src/c128time.c
track day of event and increment it when clock wraps
[c128-kasse] / src / c128time.c
1 /*
2  * RGB2R-C128-Kassenprogramm
3  * © 2007-2009 phil_fry, sECuRE, sur5r
4  * See LICENSE for license information
5  *
6  */
7 #include <peekpoke.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <c128.h>
11 #include <stdint.h>
12
13 #include "bcd2dec.h"
14 #include "general.h"
15 #include "globals.h"
16
17 void update_time(void) {
18   uint8_t bcd_hour, hour, min, sec, tenth;
19
20   /* Read the hour register first to stop the clock from updating the external
21    * registers from the internal (still ticking!) CIA registers. */
22
23   bcd_hour = CIA1.tod_hour;
24
25   /* if high bit is set, it is pm */
26   if (bcd_hour & 0x80) {
27     hour = bcd2dec(bcd_hour ^ 0x80);
28     /* adjust for 24h clock, 12:??pm is still 12:?? */
29     if (hour != 12) {
30       hour += 12;
31     }
32   } else {
33     hour = bcd2dec(bcd_hour);
34   }
35
36   sec = bcd2dec(CIA1.tod_sec);
37   min = bcd2dec(CIA1.tod_min);
38
39   /* MUST read tod_10 to enable the clock latch again */
40   tenth = CIA1.tod_10;
41
42   if (daytime.hour > hour) {
43     daytime.day++;
44   }
45
46   daytime.hour = hour;
47   daytime.min = min;
48   daytime.sec = sec;
49 }
50
51 char *get_time(void) {
52   static char buffer[9];
53   update_time();
54   sprintf(buffer, "%02d:%02d:%02d", daytime.hour, daytime.min, daytime.sec);
55   return buffer;
56 }
57
58 /* divide by 10; put quotient in high nibble, reminder in low nibble */
59 uint8_t dec2bcd(uint8_t dec) { return (((dec / 10) << 4) | (dec % 10)); }
60
61 void set_time(uint8_t day, uint8_t hour, uint8_t min, uint8_t sec) {
62   uint8_t bcd_hour;
63
64   /* CIA TOD will always flip the pm bit
65    * when either 0 or 12 is written to the hour register */
66   if (hour == 0) {
67     /* bcd 12 with high bit (pm) set */
68     bcd_hour = 0x92;
69   } else if (hour > 12) {
70     /* convert 24h clock to 12h with pm bit set */
71     bcd_hour = dec2bcd(hour - 12);
72     bcd_hour = bcd_hour ^ 0x80;
73   } else {
74     /* includes 12pm since the bit gets automatically flipped */
75     bcd_hour = dec2bcd(hour);
76   }
77
78   daytime.day = day;
79   daytime.hour = hour;
80   daytime.min = min;
81   daytime.sec = sec;
82
83   CIA1.tod_hour = bcd_hour;
84   CIA1.tod_min = dec2bcd(min);
85   CIA1.tod_sec = dec2bcd(sec);
86
87   /* set CIA1.tod_10 and program "Control Timer A" */
88   __asm__("jsr initsystime");
89 }