Bird
0
0
Arduinoprogramming~5 mins

tone() function for frequency generation in Arduino

Choose your learning style9 modes available
Introduction

The tone() function helps you play sounds by creating a beep or tone at a specific pitch using a speaker or buzzer.

You want to make a simple beep sound when a button is pressed.
You want to play a melody or sound effect on a small speaker.
You want to alert someone with a sound signal.
You want to test if a buzzer or speaker is working.
You want to add sound feedback to your Arduino project.
Syntax
Arduino
tone(pin, frequency);
tone(pin, frequency, duration);

pin is the Arduino pin connected to the speaker or buzzer.

frequency is how high or low the sound is, measured in Hertz (Hz).

duration is how long the tone plays, in milliseconds (optional).

Examples
Play a 1000 Hz tone on pin 8 until noTone() is called.
Arduino
tone(8, 1000);
Play a 500 Hz tone on pin 9 for 200 milliseconds, then stop automatically.
Arduino
tone(9, 500, 200);
Stop any tone playing on pin 8.
Arduino
noTone(8);
Sample Program

This program plays two tones on a buzzer connected to pin 8. First, it plays a 440 Hz sound (A4 note) for half a second, waits one second, then plays an 880 Hz sound (A5 note) for 0.3 seconds, and repeats.

Arduino
#define BUZZER_PIN 8

void setup() {
  // No setup needed for tone()
}

void loop() {
  tone(BUZZER_PIN, 440, 500); // Play A4 note for 500 ms
  delay(1000);                // Wait 1 second
  tone(BUZZER_PIN, 880, 300); // Play A5 note for 300 ms
  delay(700);                 // Wait 0.7 seconds
}
OutputSuccess
Important Notes

Only one tone can play at a time on the Arduino.

Use noTone(pin) to stop the sound early.

Make sure your buzzer or speaker is connected to the correct pin and ground.

Summary

tone() creates sounds by sending a frequency to a speaker or buzzer.

You can control how long the sound plays with an optional duration.

Use noTone() to stop the sound before the duration ends.