Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
The tone()
function in Arduino is a versatile and straightforward way to generate sound using a piezo buzzer or a speaker. This function allows you to produce a tone of a specified frequency on a pin for a specified duration or indefinitely. It is particularly useful for creating sound effects, alarms, or even simple melodies in your Arduino projects.
The tone()
function can be used to generate a square wave of the specified frequency (and 50% duty cycle) on a pin. The syntax for the tone()
function is as follows:
tone(pin, frequency);
tone(pin, frequency, duration);
pin
: The pin on which to generate the tone.frequency
: The frequency of the tone in Hertz.duration
: (Optional) The duration of the tone in milliseconds.This example demonstrates how to generate a simple tone on pin 8 of the Arduino.
void setup() {
// Start generating a 1000 Hz tone on pin 8
tone(8, 1000);
}
void loop() {
// Do nothing here
}
In this example, a continuous 1000 Hz tone is generated on pin 8. The loop does nothing, allowing the tone to play indefinitely.
This example shows how to generate a tone for a specific duration.
void setup() {
// Generate a 500 Hz tone on pin 8 for 1000 milliseconds (1 second)
tone(8, 500, 1000);
}
void loop() {
// Do nothing here
}
In this case, a 500 Hz tone will play on pin 8 for 1 second.
This example demonstrates how to play a simple melody using the tone()
function.
int melody[] = {262, 294, 330, 349, 392, 440, 494, 523}; // C4 to C5
int noteDurations[] = {500, 500, 500, 500, 500, 500, 500, 500}; // Duration for each note
void setup() {
for (int i = 0; i < 8; i++) {
int noteDuration = noteDurations[i];
tone(8, melody[i], noteDuration);
delay(noteDuration * 1.30); // Wait for the note to finish
noTone(8); // Stop the tone on pin 8
}
}
void loop() {
// Do nothing here
}
This example plays a simple scale from C4 to C5 on pin 8. Each note is played for 500 milliseconds, and there is a short pause between notes.
tone()
function can only generate one tone at a time. If you call tone()
on a different pin while a tone is already playing, the tone will stop on the first pin and start on the second.noTone(pin)
to stop the tone on a specific pin.