In: Electrical Engineering
/timer setup for timer0 at 1Khz
//For arduino uno or any board with ATMEL 328/168.. diecimila,
duemilanove, lilypad, nano, mini...
//Temporary variable
boolean toggle0 = 0;
void setup(){
pinMode(8, OUTPUT);
cli(); //stop interrupts
// Set Timer0 interrupt at 1KHz
TCCR0A = 0; // Reset entire TCCR2A register to 0
TCCR0B = 0; // Reset entire TCCR2B register to 0
TCNT0 = 0; // Reset counter value to 0
// Set compare match register for 1khz increments
OCR0A = 249; // = (16*10^6) / (2000*64) - 1 (must be <256)
// where 64 is the prescaler
// Turn on CTC mode
TCCR0A |= (1 << WGM01);
// Set CS01 and CS00 bits for 64 prescaler
TCCR0B |= (1 << CS01) | (1 << CS00);
// Enable timer compare interrupt
TIMSK0 |= (1 << OCIE0A);
} //End of setup loop
ISR(TIMER0_COMPA_vect){
// Timer0 interrupt 1kHz toggles pin 8
// It generates pulse wave of frequency 1kHz/2 = 0.5kHz (Takes two
cycles for full wave - Toggle high then Toggle low)
// Hence pulse width = 2ms.
if (toggle0){
digitalWrite(8,HIGH);
toggle0 = 0;
}
else{
digitalWrite(8,LOW);
toggle0 = 1;
}
}
void loop(){
//loop code here
}