forked from Dhole/miniBoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.c
100 lines (91 loc) · 1.75 KB
/
timer.c
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
#include <stdint.h>
#include <stdio.h>
#include "memory.h"
#include "lr35902.h"
#include "io_regs.h"
const uint32_t div_cte = CPU_FREQ / 16384;
static uint32_t cyc_cnt, cyc_div_cnt, div;
static uint8_t div_reg, timemod_reg, timcont_reg, enable;
// We need to detect oveflow, so we use 16 bits!
static uint16_t tim_reg;
void timer_write_8(uint16_t addr, uint8_t v) {
switch (addr) {
case IO_DIVIDER:
div_reg = 0;
break;
case IO_TIMECNT:
tim_reg = v;
break;
case IO_TIMEMOD:
timemod_reg = v;
break;
case IO_TIMCONT:
timcont_reg = v;
switch (timcont_reg & (MASK_IO_TIMCONT_clock)) {
case OPT_Timer_clock_4096:
div = CPU_FREQ / 4096;
break;
case OPT_Timer_clock_262144:
div = CPU_FREQ / 262144;
break;
case OPT_Timer_clock_65536:
div = CPU_FREQ / 65536;
break;
case OPT_Timer_clock_16384:
div = CPU_FREQ / 16384;
break;
}
if (timcont_reg & MASK_IO_TIMCONT_Start) {
cyc_cnt = 0;
enable = 1;
}
break;
default:
break;
}
}
uint8_t timer_read_8(uint16_t addr) {
switch (addr) {
case IO_DIVIDER:
return div_reg;
break;
case IO_TIMECNT:
return (uint8_t) tim_reg;
break;
case IO_TIMEMOD:
return timemod_reg;
break;
case IO_TIMCONT:
return timcont_reg | 0xF8;
break;
default:
break;
}
return 0;
}
void timer_init() {
cyc_cnt = 0;
cyc_div_cnt = 0;
enable = 0;
}
void timer_emulate(uint32_t cycles) {
cyc_div_cnt += cycles;
while (cyc_div_cnt / div_cte > 0) {
cyc_div_cnt -= div_cte;
div_reg += 1;
}
if (!enable) {
return;
}
cyc_cnt += cycles;
while (cyc_cnt / div > 0) {
cyc_cnt -= div;
tim_reg += 1;
if (tim_reg == 0x100) {
// Overflow: Interrupt Timer
//printf("Timer Overflow\n");
mem_bit_set(IO_IFLAGS, MASK_IO_INT_Timer_Overflow);
tim_reg = timemod_reg;
}
}
}