From 6c9dbec3223dc64d1693e4a5f5db4074232bb1f1 Mon Sep 17 00:00:00 2001 From: Savanni D'Gerinel Date: Wed, 27 Apr 2022 22:28:54 -0400 Subject: [PATCH] Add a program that demonstrates PWM and interrupts --- pwm/src/main.c | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 pwm/src/main.c diff --git a/pwm/src/main.c b/pwm/src/main.c new file mode 100644 index 0000000..570a4da --- /dev/null +++ b/pwm/src/main.c @@ -0,0 +1,74 @@ +#include +#include +#include + +#include + +#define FIVE_SECOND_TICK (8000000 * 10) / 256 + +volatile uint32_t iteration = 0; + +void set_up_pwm(void); +void start_pwm(void); + +ISR(TIMER0_OVF_vect) { + if (iteration >= FIVE_SECOND_TICK) { + GTCCR |= _BV(TSM); + /* + PORTB &= ~(_BV(2)); + PORTB |= _BV(1); + */ + PORTB = _BV(1); + } else { + iteration += 1; + } +} + +void set_up_pwm(void) { + // Stop the clock + GTCCR = _BV(TSM) | _BV(PSR0); + + TCCR0B = _BV(CS00); + + // Set normal mode + TCCR0A = _BV(COM0A1) | _BV(WGM01) | _BV(WGM00); + + // Enable the overflow interrupt + TIMSK = _BV(TOIE0); +} + +void start_pwm(void) { + GTCCR &= ~(_BV(TSM)); +} + +int main (void) { + int8_t step = 1; + uint8_t target = 0; + + set_up_pwm(); + OCR0A = 0; + + PORTB = 0; + DDRB = _BV(2) | _BV(1) | _BV(0); + _delay_ms(50); + PORTB |= _BV(2); + + sei(); + start_pwm(); + + while (iteration != FIVE_SECOND_TICK) { + OCR0A = target; + target += step; + + if (target == 255) { + step = -1; + } else if (target == 0) { + step = 1; + } + + _delay_ms(10); + } + + while (1) {} +} +