This is a problem of my own, but coincidentally I just noticed Dingbat's post and this may help him
I want to sync my 1mSec interrupts (which work fine have used similar code before) to the 10mSec main period. I have got nice clean pulses every 10mSec into pin2.
I can't quite see why this does not work (erratic and extra pulses as the LED flashes slightly faster)
Removing the interrupt source allows normal operation.
The code should work by making the ext interrupt the 10th pulse which would otherwise be provided by the timer interrupt albeit with a slightly increased period. This occurs only once after a power failure
Any ideas, anyone?
/* REAL TIME CLOCK WITH PROGRMMABLE TWO CHANNEL SWITCHING
// ------------------------------------------------------
5 digit comm anode LED display
10 pushbuttons for input
1 interrupt input 100Hz
DS1302 RTC for backup time keeping only. Normal time keeping synced to mains for long term accuracy
2 channel relay outputs.
Platform: Arduino pro Mini 16MHz
IDE: Arduino 0021
V0.1 Nov 14 2010 Set up timer2 interrupt at 1mS and extenal interrupt every 10mS.
*/
//--------------------------------------------------------------------------------------------
#include <EEPROM.h>
volatile byte intrptCounter;
volatile int flashCounter;
volatile boolean mainsFailFlag=0;
boolean ledState=1;
#define testLed 13
void setup(){
//set up timer 2 control registers here
OCR2A = 125; //initialise compare register for first interrupt
TCCR2A = B00000000; //select Normal Mode,freerunning counter, no connection to hardware pins
TCCR2B = B00000101; //normal, prescaler equals clock/128. With 16Mhz clock this gives an 8uSec clock to the TCNT2
TIMSK2 = B00000010; //generate interrupt on output compare match A
pinMode(testLed,OUTPUT);
pinMode(12,OUTPUT);
attachInterrupt(0,mainsInterrupt,RISING); // makes digital pin 2 trigger an interrupt
//Serial.begin(19200);
}
// ------------------ end of setup ------------------
void mainsInterrupt() {
TCNT2=0; // resync timer to mains interrupt
OCR2A =125;
intrptCounter=0;
mainsFailFlag=0;
flashCounter +=1;
}
// ----------- end of external interrupt ------------
ISR (TIMER2_COMPA_vect){
intrptCounter+=1; // will normally only reach 9 and is set to zero by mainsInterrupt function
if (intrptCounter>9){
mainsFailFlag=1;
}
if (intrptCounter==9 && mainsFailFlag== 0){
OCR2A +=150; //this would generate a 1.2 mSec interrupt if mains interrupt does NOT occur
}
else{
OCR2A +=125; //this generate a 1mSec interrupt for all interrupts except where external mains interrupt is expected.
}
flashCounter +=1;
//Serial.print(flashCounter);
}
// --------------- end timer interrupt ---------------
void loop(){
flashLed(); // just tests the 1mSec interrupt by flashing Led every second
}
//-------------------------------------------------------
void flashLed() {
if(flashCounter>=1000){
flashCounter=0;
ledState= !ledState;
digitalWrite(testLed,ledState);
}
}
//