sysprog-basic/btn-pwm/main.c

58 lines
1.2 KiB
C

/*
* Use the timers pwm to dim a light on demand.
#define F_CPU 16000000UL
*/
#define __AVR_ATmega328P__
#include <avr/interrupt.h>
#include <avr/io.h>
#include <util/delay.h>
#define PWM_LOW 24
#define PWM_HIGH 192
int state = 0;
// code for INT0
ISR(INT0_vect) {
OCR0A = PWM_HIGH; // max value for timer
PORTB |= (1<<PORTB5);
}
// code for INT1
ISR(INT1_vect) {
OCR0A = PWM_LOW; // max value for timer
PORTB &= ~(1<<PORTB5);
}
int main(void) {
// read from D2 and D3, write to D6
DDRD |= (1 << PORTD6);
DDRB = 0xff; // used for internal led only
PORTD |= (1 << PORTD2) | (1 << PORTD3); // pull up D2 and D3
// enable external interruprs
EIMSK |= (1 << INT0);
EIMSK |= (1 << INT1);
// trigger when anything changes
EICRA |= (1 << ISC00); // for INT0
EICRA |= (1 << ISC10); // for INT1
// Timer 0
// Mode: Fast PWM
// Prescaler: /8
// max: dynamic depending on pushed button
TCCR0A |= (1 << WGM01) | (1 << WGM00); // Fast PWM Mode
OCR0A = PWM_HIGH; // max value for timer
TCCR0A |= (1 << COM0A1); // set non inverting mode, start initialized
TCCR0B |= (1 << CS01); // enable with prescaler 8
sei(); // magic interrupt macro
while (1) {
// do nothing
}
}