summaryrefslogtreecommitdiff
path: root/include/arch/atmega2560/driver/timer.h
blob: c16fbe4687176639eee71a73b0388fc87b267b72 (plain)
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
/*
 * Copyright 2021 Daniel Friesel
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */
#include <avr/io.h>
#include <avr/interrupt.h>

#define ON_TIMER_INTERRUPT_head ISR(TIMER4_COMPA_vect) {
#define ON_TIMER_INTERRUPT_tail }

class Timer {
	private:
		Timer(const Timer &copy);
		unsigned char prescaler;

	public:
		Timer() {}

		inline void setup_khz(uint16_t const frequency) { // 16 MHz base
			OCR4A = frequency ? 16000 / frequency : 65535;
			TCCR4A = _BV(WGM42);
			prescaler = _BV(CS40);
		}
		inline void setup_hz(uint16_t const frequency) { // 16 MHz / 256 == 62.5 kHz base
			OCR4A = frequency ? 62500 / frequency : 65535;
			TCCR4A = _BV(WGM42);
			prescaler = _BV(CS42);
		}
		inline void start(unsigned char const interrupt) {
			TCNT4 = 0;
			TCCR4B = prescaler;
			if (interrupt) {
				TIMSK4 = _BV(OCIE4A);
			}
		}
		inline void stop() { TCCR4B = 0; TIMSK4 = 0; }
};

extern Timer timer;