30 Days Lost in Space → Help Center

Coding Concepts

tone() and noTone() in Arduino Code

tone(pin, frequency) plays a note on a buzzer and returns at once; noTone(pin) stops it. Melodies, one tone at a time, the Timer2 conflict, tested sketches.

tone(pin, frequency) starts a square wave on a pin, which makes a passive buzzer sound at that pitch, and noTone(pin) stops it. tone() returns immediately and the sound keeps playing in the background; give it a third argument, a duration in milliseconds, and it stops by itself, but your sketch still doesn't wait for it.

That one fact, that tone() never waits, explains most buzzer bugs. The rest of this page covers notes, melodies, the hardware timer behind it, and the pins it quietly takes from you.

How Sound Works on the Board

A buzzer makes sound when something pushes it back and forth fast enough to move air. tone() does the pushing: it flips the pin between HIGH and LOW at the frequency you ask for, an even 50/50 square wave, using the chip's Timer2 to time each flip. Because a hardware timer does the work, your code keeps running while the note plays.

The kit's buzzer is a passive buzzer: it has no sound of its own and plays whatever frequency you feed it. (An active buzzer has its own oscillator and only beeps at one pitch.) The passive buzzer guide covers the part itself.

The Two Functions

tone()

tone(pin, frequency);             // plays until you call noTone()
tone(pin, frequency, duration);   // plays for duration milliseconds, then stops by itself

| Parameter | Type | What it means | |-----------|------|---------------| | pin | int | Any digital pin connected to your buzzer | | frequency | unsigned int | Pitch in hertz (cycles per second), 31 and up | | duration | unsigned long | (Optional) How many milliseconds to play |

With a duration, the tone stops on its own, but tone() returns at once. So if you call tone(pin, 440, 500) and immediately tone(pin, 880, 500), the second call replaces the first and you never hear the 440 Hz note. Put a delay() after each note, or use millis() as in Example 3.

noTone()

noTone(pin);

Stops the tone on that pin and leaves the pin LOW. If nothing is playing on that pin, it does nothing. Call it with the same pin you gave tone().

Frequency Ranges

| Range | Hz | Notes | |-------|----|-------| | Human hearing | 20 to 20,000 | Full range | | Small piezo sweet spot | 500 to 5,000 | Where the kit's buzzer sounds best | | Good for melodies | 200 to 2,000 | Musical notes that are easy to tell apart | | Below 31 | under 31 | Not possible: the timer can't count that slowly |

The 31 Hz floor is real. Ask for less and you don't get a deeper note, you get a wrong one: in our simulator tone(8, 20) came out at about 58 Hz. The 30 Days Day 24 lesson goes as low as 38 Hz for its rumbling engines.

Note Frequency Table

| Note | Hz | Note | Hz | |------|----|------|----| | C4 | 262 | G4 | 392 | | C#4 | 277 | G#4 | 415 | | D4 | 294 | A4 | 440 | | D#4 | 311 | A#4 | 466 | | E4 | 330 | B4 | 494 | | F4 | 349 | C5 | 523 | | F#4 | 370 | | |

A4 at 440 Hz is the universal tuning reference. Each octave up doubles the frequency (A5 is 880 Hz). For every note by name, the Arduino IDE's File > Examples > 02.Digital > toneMelody sketch comes with a pitches.h tab that defines NOTE_C4, NOTE_A4 and the rest; copy that tab into your own sketch.

Example 1: Sound Until You Say Stop

The simplest pattern: start a tone with no duration when something happens, and stop it with noTone() when it ends. This lid alarm keeps a photoresistor in a dark box (photoresistor from 5V to A0, 10 kΩ from A0 to GND) and the buzzer on pin 8:

// Lid alarm: keep it in a dark box. When the lid opens and light gets in, the buzzer sounds.
const int SENSOR_PIN = A0;   // light sensor with a 10k resistor: more light, a higher reading
const int BUZZER_PIN = 8;
const int BRIGHT = 400;      // above this reading the lid is open (0 to 1023)
bool open = false;

void setup() {
  Serial.begin(9600);
}

void loop() {
  int light = analogRead(SENSOR_PIN);
  if (light > BRIGHT && !open) {
    open = true;
    tone(BUZZER_PIN, 2000);       // no duration: it plays until noTone()
    Serial.println("Opened!");
  } else if (light <= BRIGHT && open) {
    open = false;
    noTone(BUZZER_PIN);           // silence, and the pin is left LOW
    Serial.println("Closed");
  }
  delay(50);
}

The open flag matters: it calls tone() once when the lid opens instead of on every pass of loop(). The 30 Days Day 12 lesson uses the same pair to turn the keypad into an instrument: each key starts a note with tone(BUZZER_PIN, tone_frequency), and a stop key calls noTone(BUZZER_PIN).

Example 2: A Melody from Two Arrays

Store the notes in one array and their lengths in another, then walk through them:

// Buzzer melody: the buzzer on pin 8 plays a short tune, waits, and plays it again.
const int BUZZER_PIN = 8;

const int NOTES[] = { 523, 659, 784, 1047, 784, 1047 };   // C5 E5 G5 C6 G5 C6, in hertz
const int LENGTHS[] = { 150, 150, 150, 300, 150, 450 };   // milliseconds
const int COUNT = 6;

void setup() {
  Serial.begin(9600);
}

void loop() {
  for (int i = 0; i < COUNT; i++) {
    tone(BUZZER_PIN, NOTES[i], LENGTHS[i]);
    delay(LENGTHS[i] + 40);   // tone() doesn't wait, so wait here: the note plus a small gap
  }
  Serial.println("played");
  delay(1500);
}

The + 40 matters. tone() with a duration doesn't wait, so the delay() holds the sketch for the length of the note and then 40 ms more. Without that gap, two notes of the same pitch blend into one long note.

Example 3: A Melody That Doesn't Stop Your Sketch

delay() freezes everything else while the tune plays. To keep reading sensors or blinking lights, let millis() decide when the next note is due:

// A melody that doesn't stop the rest of your sketch: millis() decides when the next note starts.
const int BUZZER_PIN = 8;
const int LED_PIN = 13;   // blinks the whole time, to prove loop() never waits

const int NOTES[] = { 523, 659, 784, 1047 };   // C5 E5 G5 C6
const int LENGTHS[] = { 200, 200, 200, 400 };  // milliseconds
const int COUNT = 4;
const int GAP = 40;                            // silence between notes

int note = 0;
unsigned long noteStarted = 0;
unsigned long blinked = 0;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(9600);
  tone(BUZZER_PIN, NOTES[0], LENGTHS[0]);
  noteStarted = millis();
}

void loop() {
  if (millis() - noteStarted >= (unsigned long)(LENGTHS[note] + GAP)) {
    note = (note + 1) % COUNT;              // the next note, back to the first after the last
    tone(BUZZER_PIN, NOTES[note], LENGTHS[note]);
    noteStarted = millis();
    Serial.print("note ");
    Serial.println(note);
  }

  if (millis() - blinked >= 100) {          // meanwhile: anything else, never blocked
    blinked = millis();
    digitalWrite(LED_PIN, !digitalRead(LED_PIN));
  }
}

We ran this in our simulator: the first note came out at 523 Hz while pin 13 kept blinking 5 times a second the whole time. The millis() guide explains the timing pattern.

One Tone at a Time

The board has one timer for tone(), so only one pin can play at once. If a tone is playing on pin 8, tone(12, 2000) does nothing at all; call noTone(8) first and then pin 12 plays. In our test pin 12 stayed silent until exactly that happened. Calling tone() again on the same pin simply changes the pitch.

tone() and PWM: The Timer2 Conflict

Timer2 also runs analogWrite() on pins 3 and 11. While a tone is playing, those two pins stop pulsing, so an LED you're dimming on them goes dark or stuck, with no error message to tell you why.

It goes both ways. Calling analogWrite() on pin 11 during a tone overwrites the timer setting the tone runs on: in our simulator a 1,000 Hz tone jumped to about 2,475 Hz the moment we wrote to pin 11. After noTone(), pin 11 stays dark until you call analogWrite() on it again.

| PWM Pin | Timer | Affected by tone()? | |---------|-------|---------------------| | 3 | Timer2 | Yes | | 5 | Timer0 | No | | 6 | Timer0 | No | | 9 | Timer1 | No | | 10 | Timer1 | No | | 11 | Timer2 | Yes |

The easy fix is to keep dimmed LEDs on pins 5, 6, 9 and 10 whenever a buzzer is in the circuit. The 30 Days Day 14 lesson has its RGB LED on pins 11, 10 and 9, so it switches the LED off for each beep and back on afterwards:

// A recognized button was pressed. Give short beep and blue LED
void giveInputFeedback() {
  displayColor(0, 0, 0);  // Turn off LED while playing tone
  tone(BUZZER_PIN, 880, 200);
  delay(200);               // Delay while tone is playing because tone() returns immediately
  displayColor(0, 0, 128);  // Restore blue LED
}

Common Mistakes

| Mistake | What Happens | Fix | |---------|-------------|-----| | Calling tone() on every pass of loop() | The note restarts constantly and sounds rough | Call it once when something changes, with a flag like Example 1 | | No delay after tone() with a duration | Only the last note of a melody plays | delay() for the note's length plus a small gap, or use millis() | | Starting a second pin while one plays | The second pin stays silent | noTone() the first pin, then start the second | | Forgetting noTone() | The buzzer keeps going forever | Call noTone(pin) with the same pin | | Asking for less than 31 Hz | A wrong, higher note | Stay at 31 Hz or above | | Using an active buzzer | Odd warbling instead of your note | Use a passive buzzer with tone() | | analogWrite() on pin 3 or 11 while a tone plays | LED dimming breaks, and pin 11 changes the tone's pitch | Use pins 5, 6, 9 or 10 for dimming |

A buzzer that makes no sound at all has its own checklist: Buzzer Makes No Sound.

Frequently Asked Questions

What does noTone() do?

It stops the square wave that tone() started on that pin and leaves the pin LOW. It only affects the pin you name, and it does nothing if that pin isn't playing.

Do I need noTone() if I gave tone() a duration?

No. tone(pin, frequency, duration) stops by itself when the time is up. You need noTone() for tones started without a duration, or to cut a timed tone short.

Can I play two tones at the same time?

Not with tone() on the HERO Board: there is one timer for it, so one pin plays at a time. A second tone() on another pin is ignored until you call noTone() on the first.

Can I change the volume with tone()?

No. tone() always drives an even 50/50 square wave, so loudness depends on the buzzer and the frequency. The kit's buzzer sounds best between 500 and 5,000 Hz; a resistor in series with the buzzer makes it quieter.

What is RTTTL?

RTTTL (Ring Tone Text Transfer Language) is the text format old mobile phones used for ringtones. A tune is one line of text: a name, the defaults (d=4,o=5,b=200 means quarter notes, octave 5, 200 beats per minute), then notes like 8g. A sketch reads the line note by note and plays each one with tone(). The Pandora's Box course builds a full player in its RTTTL Alarm lesson.