diff --git a/module01/ex03/main.c b/module01/ex03/main.c index 77d3636..ba36f08 100644 --- a/module01/ex03/main.c +++ b/module01/ex03/main.c @@ -1,4 +1,5 @@ #include +#include // stringify #define STRINGIFY_HELPER(x) #x @@ -64,11 +65,49 @@ #define TIME_MS(ms) (((F_CPU / PRESCALE_VALUE) * ms) / 1000) #define PERIOD 1000 #define DUTY_CYCLE 10 +#define PERCENT(percent, period) (((float)percent / 100) * period) // END MACROS +typedef struct { + int duty_cycle; + int max; + int min; +} IncrementParams; + +void increment_duty_cycle(void *param) { + IncrementParams *params = (IncrementParams *)param; + if(params->duty_cycle < params->max) { + params->duty_cycle += 10; + } + OCR1A = TIME_MS(PERCENT(params->duty_cycle, PERIOD)); +} + +void decrement_duty_cycle(void *param) { + IncrementParams *params = (IncrementParams *)param; + if(params->duty_cycle > params->min) { + params->duty_cycle -= 10; + } + OCR1A = TIME_MS(PERCENT(params->duty_cycle, PERIOD)); +} + +void on_press(int bit, void (*action)(void*), void *params) { + if ((TEST(PIND, bit)) == 0) { + action(params); + _delay_ms(20); + while ((TEST(PIND, bit)) == 0) { + continue; + } + _delay_ms(20); + } +} int main() { + int duty_cycle = DUTY_CYCLE; + int max = 100; + int min = 0; + IncrementParams params = {duty_cycle, max, min}; + MODE_OUTPUT(LED2); // Table 16-4 : set timer in Fast PWM (Pulse With Modulation) mode with TOP = ICR1 (Mode 14) @@ -83,12 +122,13 @@ int main() { ICR1 = TIME_MS(PERIOD); // 16.9.3 : set the duty cycle to DUTY_CYCLE% of the time -> OC1A (alternate function of PORTB1, aka LED2) is cleared when TCNT1 (the counter value) equals OCR1A - OCR1A = TIME_MS(DUTY_CYCLE); + OCR1A = TIME_MS(PERCENT(DUTY_CYCLE, PERIOD)); // start the timer with the prescaler TCCR1B |= (PRESCALE_SET); while(1) { - continue; + on_press(SW1, increment_duty_cycle, ¶ms); + on_press(SW2, decrement_duty_cycle, ¶ms); } } \ No newline at end of file