sysprog-basic/timer2/main.c

73 lines
1.6 KiB
C

/*
* Use the timer to produce a sound in a speaker.
*
* Formular for the frequency:
* (F_CPU/wanted_frequency*2*Prescaler)+1
*
* Cut off the decimal part and see which is
* closer to the wanted frequency.
*
* Task: Sum at start with 440 Hz, when a button is pushed, sum at 264 Hz. The
* other button reverses.
*/
#define F_CPU 16000000UL
#define __AVR_ATmega328P__
#include <avr/interrupt.h>
#include <avr/io.h>
#include <util/delay.h>
#define SOUND_A 17
#define SOUND_C 30
#define MINUTE 60 * 1000
const int TIME = 45 * MINUTE;
int state = 0;
// Timer0 interrupt
ISR(TIMER0_COMPA_vect) {
PORTB ^= (1 << PORTB5); // toggle the speaker
}
// code for INT0
ISR(INT0_vect) {
OCR0A = SOUND_A; // max value for timer
}
// code for INT1
ISR(INT1_vect) {
OCR0A = SOUND_C; // max value for timer
}
int main(void) {
DDRB = 0xff; // write to B
DDRD = 0; // read from D
PORTD |= (1 << PORTD2) | (1 << PORTD3); // pull up D2 and D3
PORTB = 0; // pull down PORT B
// 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: Overflow, Interrupt
// Prescaler: /1024
// max: dynamic depending on pushed button
TCCR0A |= (1 << WGM01); // CTC Mode
OCR0A = SOUND_C; // max value for timer
TIMSK0 |= (1 << OCIE0A); // enable interrupt ISR_COMPA_vect
sei(); // magic interrupt macro
TCCR0B |= (1 << CS02) | (1 << CS00); // enable with prescaler 1024
while (1) {
// do nothing
}
}