Newer
Older
tree-os / src / kernel / drivers / interrupts / timer / timer.c
#include <_stdio.h>
#include <interrupts.h>
#include <irqs.h>
#include <ports.h>
#include <stdint.h>
#include <task.h>

#define PIT_A 0x40
#define PIT_CONTROL 0x43

#define PIT_MASK 0xFF
#define PIT_SCALE 1193180
#define PIT_SET 0x36

#define CMD_BINARY 0x00

#define CMD_MODE0 0x00
#define CMD_MODE1 0x02
#define CMD_MODE2 0x04
#define CMD_MODE3 0x06
#define CMD_MODE4 0x08
#define CMD_MODE5 0x0a

#define CMD_RW_BOTH 0x30

#define CMD_COUNTER0 0x00
#define CMD_COUNTER2 0x80

void setTimerFreq(uint32_t hz) {
    int divisor = PIT_SCALE / hz;
    outb(PIT_CONTROL, CMD_BINARY | CMD_MODE3 | CMD_RW_BOTH | CMD_COUNTER0);
    outb(PIT_A, (uint8_t)divisor);
    outb(PIT_A, (uint8_t)(divisor >> 8));
}

uint32_t timerMillis = 0;

uint32_t time = 0;

void timerHandler() {
    timerMillis++;
    if (timerMillis % 1000 == 0) {
        printf("\e[s\e[Htime since power on :0x%x seconds\e[u", ++time);
    }
}

void setupTimer() {
    printf("setting timer frequency to 1kHz\n");
    setTimerFreq(1000);
    setIRQHandler(0, &timerHandler);
}