Newer
Older
tree-os / src / kernel / drivers / interrupts / timer / timer.c
#include <stdint.h>
#include <_stdio.h>
#include <interrupts.h>
#include <ports.h>
#include <task.h>
#include <irqs.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;

void timerHandler() {
	timerMillis++;
	if (timerMillis % 1000 == 0) {
		// printf("second\n");
		// yields();
	}
}

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