Add PWM dimming.

This commit is contained in:
redxef 2022-07-13 01:32:12 +02:00
parent 67debd24e3
commit 0b415c2ca5
Signed by: redxef
GPG key ID: 7DAC3AA211CBD921

57
main.c
View file

@ -1,14 +1,61 @@
#include <avr/io.h>
#include <util/delay.h>
#define PIN_LED 0b1000;
void init_ports(void) {
DDRB = 0x00;
DDRC = 0x00;
DDRD = 0x00;
DDRD |= PIN_LED;
}
void init_pwm(void) {
// page 84
// 7-6: ouput A, 5-4: output B, 3-2: res, 1-0: waveform
TCCR2A = 0b00100011;
// 7-6: force output A/B, 5-4: res, 3: waveform, 2-0: clock source
TCCR2B = 0b01000001;
// duty
OCR2B = 0;
}
void deinit_pwm(void) {
TCCR2A = 0;
TCCR2B = 0;
OCR2B = 0;
}
void pwm_fade_in(int until, int step) {
int i;
for (i = 0; i < until; i += step) {
OCR2B = i;
_delay_ms(0.5);
}
}
void pwm_fade_out(int until, int step) {
int i;
for (i = OCR2B; i > until; i -= step) {
OCR2B = i;
_delay_ms(0.25);
}
}
int main(void) {
DDRD = 255;
init_ports();
while (1) {
PORTD = 0b00001000;
_delay_ms(100);
PORTD = 0;
_delay_ms(100);
init_pwm();
pwm_fade_in(0x7f, 1);
_delay_ms(300);
OCR2B = 0xff;
_delay_ms(150);
pwm_fade_out(0, 4);
deinit_pwm();
PORTD &= ~PIN_LED;
_delay_ms(2000);
}
return 0;
}