summaryrefslogtreecommitdiffstats
path: root/fw/timer0_test.c
blob: ef5e62232a8f15760d0f44e415fc4606ac1bd1e9 (plain) (blame)
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
#include <pic16f84a.h>

typedef unsigned char uint8_t;

__sfr __at(0x70) UART_TX;
__sfr __at(0x72) UART_STATUS;

/*
 * OPTION_REG 0x07: T0CS=0 (Fosc/4), PSA=0, PS=111 (1:256)
 * At 50 MHz: overflow every 256*256 / (50M/4) = 5.24 ms → ~191 ovf/sec
 */
#define STATUS_RP0   0x20
#define T0IF         0x04   /* INTCON bit 2 */
#define T0IE         0x20   /* INTCON bit 5 */
#define GIE          0x80   /* INTCON bit 7 */
#define OVF_PER_SEC  191

static volatile uint8_t ovf_count = 0;

void isr(void) __interrupt(0) {
    if (INTCON & T0IF) {
        ovf_count++;
        INTCON &= ~T0IF;
    }
}

static void uart_send(uint8_t b) {
    while (UART_STATUS & 0x01);
    UART_TX = b;
}

static void uart_puts(const char *s) {
    while (*s) uart_send((uint8_t)*s++);
}

static void print_uint8(uint8_t v) {
    uint8_t started = 0;
    if (v >= 200) { uart_send('2'); v -= 200; started = 1; }
    else if (v >= 100) { uart_send('1'); v -= 100; started = 1; }
    {
        uint8_t t = '0';
        while (v >= 10) { v -= 10; t++; }
        if (started || t != '0') uart_send(t);
    }
    uart_send(v + '0');
}

void main(void) {
    uint8_t seconds = 0;

    /* Configure OPTION_REG (bank 1, same 7-bit addr as TMR0) */
    STATUS |= STATUS_RP0;
    TMR0 = 0x07;
    STATUS &= ~STATUS_RP0;

    TMR0 = 0;
    INTCON = T0IE | GIE;    /* enable Timer0 overflow interrupt */

    uart_puts("\x1B[2J\x1B[H");
    uart_puts("Timer0 test\r\n");
    uart_puts("-----------\r\n");

    while (1) {
        ovf_count = 0;
        while (ovf_count < OVF_PER_SEC);   /* ISR bumps ovf_count */

        uart_puts("t = ");
        print_uint8(seconds);
        uart_puts(" s\r\n");
        PORTA ^= 0x01;
        seconds++;
    }
}