Can't make piezo buzzer buzz only once in an if statement.


I have a piezo buzzer, that have to buzz whenever the temperature is over a certain temperature. When the criteria for the if statement is fulfilled the buzzer will buzz. But i can’t make it buzz only once, and then stop buzzing. It will keep buzzing, and i can’t make it buzz only once? Any help?

PS nevermind the danish comments.

// code
//Temperatur pin
const int temperaturePin = A0;

// Led pins, fortæller hvilken port de har
const int ledPin1 = 2;//blå
const int ledPin2 = 3;//rød
const int ledPin3 = 4;//grøn

//potentiometer pin
const int potPin = A1;

//buzzer pin
const int buzPin = 5;//buzzer

void setup() {
// put your setup code here, to run once:

//Hvor hurtigt den opdaterer

//Fortæller det er en OUTPUT
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(buzPin, OUTPUT);


void loop()

//grader = analogRead(potPin);

float voltage, degreesC;

//indlæser strømmen
voltage = getVoltage(temperaturePin);

//omregner modstand til temperatur
degreesC = (voltage - 0.5) * 100.0;

Serial.print("voltage: “);
Serial.print(” deg C: ");

delay(1000); // Opdateringshastighed på et sekund

// LED Styring

if (degreesC <= 26)
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, LOW);

} else if (degreesC >= 26 && degreesC <= 27) {
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
} else if (degreesC >= 27) {
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
tone(5, 392, 500);
} else {
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);

} //end loop

float getVoltage(int pin)
return (analogRead(pin) * 0.004882814);

You have to record the value of millis() when the temperature crosses the threshold.
If the temperature is above the threshold and the recorded millis() value is not too old (say within the last few seconds), sound the buzzer. Otherwise, the buzzer should be off.

Thank you! do you know how to write it in code? :slight_smile:

do you know how to write it in code?

Yes thanks I do.

I suspect you are saying can you write that in code for you. The point is that this forum is not a code writing forum it is to help you help yourself. By posting that code incorrectly you have shown that you have not read the "how to use this forum " sticky post. So read that. Edit the first post to put the code in code tags.

Then have a shot at writing what you want, post it again ( also using code tags ) and we can point out where / if you are going wrong.