0
0
AutocadHow-ToBeginner · 3 min read

How to Generate Tone Using Arduino: Simple Guide

Use the tone() function in Arduino to generate a square wave of a specified frequency on a pin, producing a tone. Call noTone() to stop the tone. For example, tone(8, 440) plays a 440 Hz tone on pin 8.
📐

Syntax

The tone() function generates a square wave of the given frequency (in hertz) on a specified Arduino pin. It can optionally take a duration in milliseconds to play the tone for a limited time.

  • pin: The Arduino pin number where the speaker or buzzer is connected.
  • frequency: The frequency of the tone in hertz (Hz), e.g., 440 for the A4 note.
  • duration (optional): How long to play the tone in milliseconds. If omitted, the tone plays until noTone() is called.

The noTone() function stops the tone on the specified pin.

arduino
tone(pin, frequency);
tone(pin, frequency, duration);
noTone(pin);
💻

Example

This example plays a 1-second 440 Hz tone on pin 8, then pauses for 1 second, and repeats.

arduino
const int buzzerPin = 8;

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

void loop() {
  tone(buzzerPin, 440, 1000); // Play 440 Hz tone for 1000 ms
  delay(1500);                // Wait 1.5 seconds
  noTone(buzzerPin);          // Stop tone (optional here)
  delay(500);                 // Wait 0.5 seconds
}
Output
A 440 Hz tone plays on pin 8 for 1 second, then silence for 1.5 seconds, repeating.
⚠️

Common Pitfalls

  • Not connecting the buzzer or speaker correctly to the Arduino pin and ground.
  • Using pins that do not support tone() on some Arduino models (usually all digital pins support it, but check your board).
  • Forgetting to call noTone() if you want to stop the tone before playing another.
  • Using very high or very low frequencies outside the audible range or hardware limits.
arduino
/* Wrong: No noTone call, tone plays indefinitely */
tone(8, 1000);
// No noTone(8) call here

/* Right: Stops tone after playing */
tone(8, 1000, 500); // Plays 1000 Hz for 500 ms
noTone(8);         // Stops tone if needed
📊

Quick Reference

FunctionDescriptionParameters
tone(pin, frequency)Start tone on pin at frequency (Hz)pin: int, frequency: unsigned int
tone(pin, frequency, duration)Start tone on pin at frequency for duration (ms)pin: int, frequency: unsigned int, duration: unsigned long
noTone(pin)Stop tone on pinpin: int

Key Takeaways

Use tone(pin, frequency) to start a tone on a pin and noTone(pin) to stop it.
You can specify duration in tone() to play the tone for a limited time.
Connect your buzzer or speaker between the Arduino pin and ground correctly.
Avoid using unsupported pins or frequencies outside hardware limits.
Remember to call noTone() to stop a tone if needed.