day03/ex03/include/timer2.h
2026-04-16 17:29:49 +02:00

112 lines
2 KiB
C

#ifndef TIMER2_H
# define TIMER2_H
# include <avr/io.h>
# include "mystd.h"
# include "timer_global.h"
static inline void t2_init_fpwm_3(e_timer_prescaler prescaler) {
// Fast PWM (8-bit): WGM22:0 = 0b011
TCCR2A = _BV(WGM20) | _BV(WGM21);
// reset to zero -> timer off
TCCR2B &= ~(_BV(CS22) | _BV(CS21) | _BV(CS20));
// set the correct prescaler
switch (prescaler) {
case (PRESCALER_1): {
TCCR2B |= (_BV(CS20));
break;
}
case (PRESCALER_8): {
TCCR2B |= (_BV(CS21));
break;
}
case (PRESCALER_64): {
TCCR2B |= (_BV(CS21) | _BV(CS20));
break;
}
case (PRESCALER_256): {
TCCR2B |= (_BV(CS22));
break;
}
case (PRESCALER_1024): {
TCCR2B |= (_BV(CS22) | _BV(CS20));
break;
}
case (PRESCALER_OFF): {
break;
}
}
}
static inline void t2_set_ocr(enum e_timer_output output, uint8_t value) {
if (output & TO_A)
OCR2A = value;
if (output & TO_B)
OCR2B = value;
}
static inline void t2_set_out_mode(enum e_timer_output output, enum e_timer_output_mode mode) {
if (output & TO_A) {
TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
switch (mode) {
case (TOM_00): {
break;
}
case (TOM_10): {
TCCR2A |= (_BV(COM2A1));
break;
}
case (TOM_01): {
TCCR2A |= (_BV(COM2A0));
break;
}
case (TOM_11): {
TCCR2A |= (_BV(COM2A1) | _BV(COM2A0));
break;
}
}
}
if (output & TO_B) {
TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
switch (mode) {
case (TOM_00): {
break;
}
case (TOM_10): {
TCCR2A |= (_BV(COM2B1));
break;
}
case (TOM_01): {
TCCR2A |= (_BV(COM2B0));
break;
}
case (TOM_11): {
TCCR2A |= (_BV(COM2B1) | _BV(COM2B0));
break;
}
}
}
}
// OC2B => RED => PD3
// OC0B => GREEN => PD5
// OC0A => BLUE => PD6
#endif /* TIMER0_H */
/*
// OC2B = PD3 → output
DDRD |= _BV(DDD3) | _BV(DDD5) | _BV(DDD6);
// Fast PWM (8-bit): WGM22:0 = 0b011
TCCR2A = _BV(GM20) | _BV(GM21);
TCCR2A |= _BV(COM2B1);
// 50% duty cycle
OCR0B = 128;
// Start timer, prescaler = 64
TCCR2B = _BV(CS22);
*/