day01/ex03/main.c
2026-04-14 16:38:14 +02:00

70 lines
1.6 KiB
C

#include <avr/io.h>
#include "mystd.h"
#include "utils.h"
#define D1 PORTB0
#define D2 PORTB1
#define D3 PORTB2
#define D4 PORTB4
#define PRESCALER 256
#define TIMER_FREQ (F_CPU / PRESCALER)
// the PWM is something that counts from 0 to TOP
// when it reached the value i'll name TOGGLE, it'll set the OUTPUT high
// when it reaches TOP it'll reset COUNTER and set OUTPUT to low
//
// this means we have a clock that reaches TOP every X
// and during this, we can set TOGGLE such that we set OUTPUT high
void timer1_init(uint8_t duty) {
// Set PB1 (OC1A) as output
DDRB |= _BV(PB1);
// Non-inverting OC1B -> the OC1B is set to low on TOP reached
TCCR1A |= _BV(COM1A1);
// set to PWM-fast with ICR1 as TOP
TCCR1A |= _BV(WGM11);
TCCR1B |= _BV(WGM13) | _BV(WGM12);
// TOP => 1hz
ICR1 = TIMER_FREQ - 1;
// TOGGLE => 1/10th of ICR1
OCR1A = ((TIMER_FREQ / 10) * duty);
// Start timer with prescaler 256 (CS12)
TCCR1B |= _BV(CS12);
}
#define SW1 PD2
#define SW2 PD4
int main(void) {
uint8_t prev = 0;
uint8_t duty_cycle = 1;
timer1_init(duty_cycle);
while (1) {
bool has_changed = false;
// lets read both button in a single byte, and keep track of that too
uint8_t cur = (PIND & (_BV(SW1) | _BV(SW2)));
// check for button SW1
if (prev & (_BV(SW1)) && !(cur & (_BV(SW1)))) {
duty_cycle++;
has_changed = true;
}
// check for button SW2
if (prev & (_BV(SW2)) && !(cur & (_BV(SW2)))) {
duty_cycle--;
has_changed = true;
}
prev = cur;
if (has_changed) {
if (duty_cycle > 10)
duty_cycle = 10;
if (duty_cycle < 1)
duty_cycle = 1;
timer1_init(duty_cycle);
}
delay_ms(10);
}
}