I am using an arduino Micro to generate 8 square waves on 8 pins. The idea is as follows: on pin 13 is the main square wave. It represents a certain BPM (beats per minute). The other 7 pins should give multiplications or divisions of that BPM.
It uses timer1 to trigger an interrupt at BPM/192 (this number is choosen to enable easy multiplications). It counts those interrupts and changes the states of the outputs when needed.
The codes seems to run fine for most divisions and most multiplications. However in certain cases like /2, there seem to be shorter pulses from time to time that throw the whole timing off.
Adding a short delay at the end of the loop seems to make the system more stable but still the short pulses appear from time to time.
Does anyone have an idea what the problem might be.
int counter[8] = {0,0,0,0,0,0,0,0}; //storing number of interrupts since last pulse
int trip[8] = {191,383,767,1535,3071,6143,12287,24575}; //number of interrupts needed for div/mult
int outputPin[8] = {13,12,11,10,9,8,7,6};
void setup() {
for (int x = 0; x < 8; x++){
pinMode(outputPin[x], OUTPUT);
digitalWrite(outputPin[x], HIGH);
}
cli();
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A =2602; // 16000000 / (x * 8) -1
TCCR1B |= (1 << WGM12);
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);//prescaler of 8
TIMSK1 |= (1 << OCIE1A);
sei();
}
void pulse(){
for (int count = 0; count < 8; count++){
counter[count]++;
}
}
ISR(TIMER1_COMPA_vect){
pulse();
}
void loop() {
for (int y = 0; y < 8; y++){
if(counter[y] > trip[y]){
digitalWrite(outputPin[y],!digitalRead(outputPin[y]));
counter[y] = 0;
}
}
delayMicroseconds(100);
}