Hello, I'm new to arduino development with a few hours under the belt yet. I'm have an irritating problem. I'm using attachInterrupt to read an external interrupt on pin 2 (Uno R3 board). If I attach a speaker to another pin and send a tone() to the speaker my CHANGE external interrupt fires to often, tests show the higher the frequency on tone the more interrupts fires.
When reading the pin I get HIGH several interrupts in a row, and then LOW several interrupt in a row. I can easily filter out the wrong ones isince it shouldn't fire HIGH -> HIGH ->HIGH. My question is why it does. I have some teories on my own but I'm leaving this to a correct answer...
I post some code, I have not executed exactly this code but it should demonstrate my problem.
/Linus
unsigned long m = 0;
volatile unsigned long startM = 0;
volatile unsigned long M = 0;
volatile unsigned long cnt = 0;
int ton = 0;
void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(8, OUTPUT);
attachInterrupt(0, change, CHANGE);
}
void change() {
int reading;
cnt++;
reading = digitalRead(2);
if (reading == HIGH) {
startM = micros();
} else {
M = micros() - startM;
}
}
// the loop routine runs over and over again forever:
void loop() {
// Do not fire interrupt when copying current reading
noInterrupts();
m = M;
interrupts();
// If I enable a tone the interrupt on pin
// fires to often!?
if (ton == 0) {
tone(8, 5000);
ton = 1;
}
Serial.print("millis: ");
Serial.print(m);
Serial.print(":");
// cnt counts to fast if tone is enabled?!
Serial.print(cnt);
Serial.print("\n");
delay(50);
}