Hello all I am trying to use a buzzer at the moment. I have followed this tutorial exactly.
I have tried using digitalWrite(buzzer, HIGH); and tone(buzzer, 1000); and noTone(buzzer); to turn it off. I found that using digitalWrite(buzzer, HIGH); doesn't make the buzzer turn on but tone(buzzer,1000) does. The problem is that my loop will freeze and nothing else is executed after it. Does anyone know why this is? Thanks.
tone() uses pulse width modulation (PWM) on the pin to generate the frequency you (should) hear. `DigitalWrite(buzzer,HIGH)' simply sets the pin to +5V - no sound.
Not really - PWM implies a single frequency and variable duty-cycle.
tone() uses the timers in CTC (clear timer on compare) mode to give variable frequency.
/*
* Created by ArduinoGetStarted.com
*
* This example code is in the public domain
*
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-button-piezo-buzzer
*/
const int BUTTON_PIN = 7; // Arduino pin connected to button's pin
const int buzzer= 3; // Arduino pin connected to Buzzer's pin
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode
pinMode(buzzer, OUTPUT); // set arduino pin to output mode
}
void loop() {
int buttonState = digitalRead(BUTTON_PIN); // read new state
if (buttonState == HIGH) {
Serial.println("The button is being pressed");
tone(buzzer, 1000);
}
else
if (buttonState == LOW) {
Serial.println("The button is unpressed");
noTone(buzzer);
}
Serial.println("after the sound");
}
Serial.println("after the sound"); This code is never executed. How do I clear the timer on compare? What compare thanks/
Well that code was quickly taken put of something bigger so I made mistakes when I copy pastes it but they are still not going to make a difference when I use tone one way or another in my loop it freezes my loop and nothing after it is executed.
I found a new library for a newer version of tone hope this one doesn't do that.