Xyris  0.5
timer.cpp
Go to the documentation of this file.
1 /**
2  * @file timer.cpp
3  * @author Keeton Feavel ([email protected])
4  * @brief Programmable Interrupt Timer driver functions
5  * @version 0.3
6  * @date 2019-11-15
7  *
8  * @copyright Copyright the Xyris Contributors (c) 2019
9  *
10  */
11 #include <Arch/i686/timer.hpp>
12 #include <Arch/i686/isr.hpp>
13 
14 static void timer_callback(struct registers *regs);
15 volatile uint32_t timer_tick;
16 
17 typedef void (*voidfunc_t)();
18 
19 #define MAX_CALLBACKS 8
20 static size_t _callback_count = 0;
21 static voidfunc_t _callbacks[MAX_CALLBACKS];
22 
23 /**
24  * Sleep Timer Non-Busy Waiting Idea:
25  * Create a struct that contains the end time and the callback
26  * function pointer that should be called when timer_tick = end
27  * After each timer_tick we check our end time and call the function
28  * if we're equal.
29  */
30 
31 void timer_init(uint32_t freq) {
32  /* Install the function we just wrote */
34  /* Get the PIT value: hardware clock at 1193180 Hz */
35  uint32_t divisor = 1193180 / freq;
36  uint8_t low = (uint8_t)(divisor & 0xFF);
37  uint8_t high = (uint8_t)((divisor >> 8) & 0xFF);
38  /* Send the command */
42 }
43 
44 static void timer_callback(struct registers *regs) {
45  (void)regs;
46  timer_tick = timer_tick + 1;
47  for (size_t i = 0; i < _callback_count; i++) {
48  _callbacks[i]();
49  }
50 }
51 
52 void sleep(uint32_t ms) {
53  uint32_t start = timer_tick;
54  uint32_t final = start + ms;
55  // Waste CPU cycles like a slob
56  while (timer_tick < final);
57  // Return now that we've waited long enough
58  return;
59 }
60 
61 void timer_register_callback(void (*func)()) {
62  if (_callback_count < MAX_CALLBACKS - 1) {
63  _callbacks[_callback_count] = func;
64  _callback_count++;
65  }
66 }
timer_register_callback
void timer_register_callback(void(*func)())
Definition: timer.cpp:61
sleep
void sleep(uint32_t ms)
Sleeps for a certain length of time.
Definition: timer.cpp:52
timer_tick
volatile uint32_t timer_tick
Definition: timer.cpp:15
timer.hpp
timer_init
void timer_init(uint32_t freq)
Initialize the CPU timer with the given frequency.
Definition: timer.cpp:31
registers
A structure definining values for all x86 registers. Cannot be namespaced due to C linkage and ASM in...
Definition: regs.hpp:19
Interrupts::INTERRUPT_0
@ INTERRUPT_0
Definition: isr.hpp:60
Interrupts::registerHandler
void registerHandler(uint8_t interrupt, InterruptHandler_t handler)
Definition: isr.cpp:98
writeByte
void writeByte(uint16_t port, uint8_t data)
Writes a byte (8 bits) to the CPU bus at a given port address.
Definition: ports.cpp:19
voidfunc_t
void(* voidfunc_t)()
Definition: timer.cpp:17
MAX_CALLBACKS
#define MAX_CALLBACKS
Definition: timer.cpp:19
TIMER_DATA_PORT
#define TIMER_DATA_PORT
Definition: timer.hpp:16
isr.hpp
Interrupt Service Routine header.
TIMER_COMMAND_PORT
#define TIMER_COMMAND_PORT
Definition: timer.hpp:15