I have a function that turns a buzzer on and off under certain conditions. I'm using a global variable and modulus to time the buzzer. When I print the value of the variable out the function works as expected, but if I remove the Serial.println(buzzerTimer) function it stops working, and the buzzer just plays continuously. Does anyone know the reason for this? Here's the function in question, if you need more code, let me know, thanks!
const int green_led_pin = D0;
const int red_led_pin = D1;
const int buzzer_pin = D7;
const int potentiometer_pin = A0;
int poteValue = 0;
int minTemp = -2;
int maxTemp = 6;
int currentTemp;
int criticalMinTemp = 2;
int criticalMaxTemp = 4;
int sensorTimer = 0;
bool playBuzzer = false;
int buzzerTimer;
int buzzerInterval = 200;
void setup() {
// put your setup code here, to run once:
pinMode(green_led_pin, OUTPUT);
pinMode(red_led_pin, OUTPUT);
pinMode(buzzer_pin, OUTPUT);
pinMode(potentiometer_pin, INPUT);
Serial.begin(9600);
currentTemp = fridgeTemperature();
buzzerTimer = 0;
}
void loop() {
// put your main code here, to run repeatedly:
currentTemp = fridgeTemperature();
setBuzzerStatus();
trigBuzzer();
}
int fridgeTemperature(){
poteValue = analogRead(potentiometer_pin);
return map(poteValue, 0, 1023, minTemp, maxTemp);
}
bool checkTemp(){
if(currentTemp < criticalMinTemp || currentTemp > criticalMaxTemp){
return false;
}
return true;
}
void setBuzzerStatus(){
if(!checkTemp()){
analogWrite(red_led_pin, 255);
analogWrite(green_led_pin, 0);
playBuzzer = true;
} else {
playBuzzer = false;
buzzerTimer = 0;
analogWrite(green_led_pin, 255);
analogWrite(red_led_pin, 0);
}
}
void trigBuzzer(){
buzzerTimer++;
// Serial.println(buzzerTimer);
if(!playBuzzer || buzzerTimer % (buzzerInterval*2) > buzzerInterval){
noTone(buzzer_pin);
}
if((buzzerTimer % (buzzerInterval*2) < buzzerInterval && playBuzzer)){
tone(buzzer_pin, 100, 1000);
}
}
It's a smart fridge simulation, currently using a potentiometer to mimic a thermometer to tell the temperature for the fridge. When the temperature is outside of set bounds the red led should light up and the buzzer buzzes on and off. The buzzer only buzzes when I print out the variable I'm using to time it.
Sorry, I'm pretty new to Arduino, can you expand on this? Thanks!