- The Goal:
- I am writing a really simple program in the Arduino environment using an Arduino Nano. (the old ones).
- I am trying to have pin 2 act as an interrupt that then call a buzzer function. Please see code for clarity.
- The problem:
- When I run the below code with "buzzer_make_sound" in "loop()" the buzzer works as expected.
- When the interrupt is triggered and the callback function is called, it does not execute timers and the buzzer properly and causes the buzzer not to sound at all and the timers do weird things.
- Code
#include "includes.h" // this includes arduino.h
void callback_rc_receive();
void buzzer_make_sound();
void setup() {
Serial.begin(115200);
pinMode(RC_INPUT_CHANNEL1_PIN, INPUT); // pin 5
pinMode(RC_INPUT_CHANNEL2_PIN, INPUT); // pin 6
pinMode(RC_INPUT_CHANNEL3_PIN, INPUT); // pin 7
pinMode(RC_INPUT_CHANNEL4_PIN, INPUT); // pin 8
pinMode(RC_INCOMING_SIGNAL_TRIGGER_PIN, INPUT); // pin 2
pinMode(BUZZER1_PIN, OUTPUT); // pin 3
pinMode(LED_BUILTIN,OUTPUT);
attachInterrupt(digitalPinToInterrupt(RC_INCOMING_SIGNAL_TRIGGER_PIN), callback_rc_receive, RISING);
ReceiverOne.channel1State = 0; // typedef struct
ReceiverOne.channel2State = 0;
ReceiverOne.channel3State = 0;
ReceiverOne.channel4State = 0;
}
void loop() {
//buzzer_make_sound(); // this sounds the buzzer
}
void buzzer_make_sound(){
Serial.println("Buzzer entry");
int startTime = millis();
tone(BUZZER1_PIN, 2000);
delay(1000);
noTone(BUZZER1_PIN);
delay(1000);
Serial.println("Buzzer exit");
Serial.println(millis() - startTime);
}
void callback_rc_receive(){
if (digitalRead(RC_INPUT_CHANNEL1_PIN) == 1){
Serial.println("1");
buzzer_make_sound();
}else if (digitalRead(RC_INPUT_CHANNEL2_PIN) == 1){
Serial.println("2");
}else if (digitalRead(RC_INPUT_CHANNEL3_PIN) == 1){
Serial.println("3");
}else if (digitalRead(RC_INPUT_CHANNEL4_PIN) == 1){
Serial.println("4");
}else{
Serial.println("Error");
}
}
- Terminal prints:
When running the "buzzer_make_sound()" in loop:
Buzzer entry
Buzzer exit
2001
When triggering the interrupt:
1
Buzzer entry
Buzzer exit
0
1
Buzzer entry
Buzzer exit
0
1
Buzzer entry
Buzzer exit
65536
1
Buzzer entry
Buzzer exit
65536
The strange thing is that when triggering the interrupt, it finishes the task instantly. There is no 2 second delay.
Anyone got any idea at all what is going on? Do Interrupts stop timers? If so, how does one work with timer dependent things?