// Ex. 5 - Configure timer block for signal generation
const int outputPin = 9; // Pin connected to the output signal
const long frequency = 1000; // Desired frequency in Hz (1 kHz)
void setup() {
pinMode(outputPin, OUTPUT);
// Calculate the Timer1 settings for the desired frequency
long timerCompare = (16000000 / (2 * 1 * frequency)) - 1; // 16 MHz clock, prescaler of 1
// Configure Timer1
TCCR1A = 0; // Clear Timer1 control register A
TCCR1B = 0; // Clear Timer1 control register B
TCNT1 = 0; // Clear the Timer1 counter
// Set the compare match register for the desired frequency
OCR1A = timerCompare;
// Set the CTC mode (Clear Timer on Compare Match)
TCCR1B |= (1 << WGM12);
// Set the prescaler to 1 and start the timer
TCCR1B |= (1 << CS10);
// Enable the output compare match A interrupt
TIMSK1 |= (1 << OCIE1A);
}
void loop() {
// Main loop does nothing, signal generation is handled by the ISR
}
// Interrupt Service Routine for Timer1 compare match
ISR(TIMER1_COMPA_vect) {
// Toggle the output pin to generate the signal
digitalWrite(outputPin, !digitalRead(outputPin));
}