ATmega328P/PWM/29. tone(), Servo and the timers they take
PWM · 29 of 33

tone(), Servo and the timers they take

The three timers behind the ~ pins have other jobs. tone() takes Timer2, and PWM on 3 and 11 stops while it plays; the Servo library takes Timer1, and 9 and 10 lose PWM for good; Timer0 keeps millis(), so nothing should touch it. One jumper wire shows the first of these happen.

Your board

Each timer has two jobs

The six ~ pins are three timers, two pins each. The timers are also the only exact clocks on the chip, so anything that needs exact timing borrows one, and a borrowed timer stops making PWM for its two pins.

What tone() and Servo take with them
4 of 6 ~ pins left
The sketch also uses
~ pins with PWM
~5 ~6 ~9 ~10
Time keeping
right
While a tone plays, ~3 and ~11 give no PWM. tone() reprograms Timer2 to toggle its own pin, which is any pin you name. After noTone(), the next analogWrite on 3 or 11 brings PWM back.
TimerPWM pinsAlso used byWhen it is taken
Timer0~5, ~6millis(), micros(), delay()always; never retune it
Timer1~9, ~10the Servo libraryfrom the first attach()
Timer2~3, ~11tone()while a tone plays

Arduino's reference pages say the same in their own words: tone() interferes with PWM on 3 and 11, and the Servo library disables PWM on 9 and 10 "whether or not there is a Servo on those pins". Other libraries that need exact timing, such as some for infrared remotes or LED strips, also take Timer1 or Timer2; their documentation says which.

tone() takes Timer2

tone(pin, frequency) makes a square wave at 50% duty on any pin, from 31 Hz up. The core does it by putting Timer2 in a counting mode that interrupts the sketch twice per cycle to flip the pin. That mode is not PWM, so ~3 and ~11 stop pulsing, and the pin you asked for gets the tone instead. Only one tone plays at a time.

The sketch shows it in four lines of output. Pin 3 pulses at 490.2 Hz; the tone starts on pin 7 and pin 3 goes flat; noTone(7) puts Timer2 back in PWM mode, but pin 3 stays flat; analogWrite(3, 128) reconnects it and the pulses come back. The fix is in the last line: after a tone, write the PWM value again.

Pin 7 has nothing on it, so the tone is silent. With a passive buzzer between 7 and GND it would be a 1 kHz beep.

Servo takes Timer1, and keeps it

A hobby servo wants a pulse of about 0.5 to 2.4 ms, repeated about every 20 ms. The Servo library makes those pulses for up to 12 servos from one timer, and on this chip that timer is Timer1. It reconfigures Timer1 the moment the first servo is attached, so ~9 and ~10 stop making PWM even if no servo is on them, and they stay that way after detach().

The rule that follows is simple: on a project with servos, put the servos anywhere and the dimmable things on 3, 5, 6 or 11. Add a tone and only 5 and 6 are left.

Timer0 is the clock

millis() counts Timer0's overflows on the assumption that one comes every 1.024 ms. Code found online that makes PWM on 5 and 6 faster usually does it by changing Timer0's prescaler, and then every delay() and every millis() timeout in the sketch runs at the wrong speed, along with everything in millis() instead of delay(). If you need a different PWM frequency, change Timer1 or Timer2 and give up what uses them.

The code

Tone_Takes_Pin_3.ino

Wire 3 to 8. Every two seconds the sketch does one thing and measures pin 3 through D8: PWM on, then a tone on pin 7, then noTone(), then PWM asked for again.

// Tone_Takes_Pin_3.ino — tone() takes Timer2, and ~3 stops
// Tools > Board: Arduino Uno, or Arduino Nano with
//   Processor ATmega328P (Old Bootloader if the upload says
//   "not in sync")
// Tools > Port: the CH340 port
// Serial Monitor: 9600 baud
// Wiring: one jumper wire from 3 to 8. Pin 3 is the PWM output,
//   D8 the input. The tone goes to pin 7, which has nothing on it,
//   so you will hear nothing: the pulses are real all the same.

const byte PROBE = 8;
byte phase = 0;

void measure(const char *what) {
  unsigned long hi = pulseIn(PROBE, HIGH, 20000);
  unsigned long lo = pulseIn(PROBE, LOW, 20000);
  Serial.print(what);
  Serial.print(":  ");
  if (hi == 0 || lo == 0) {
    Serial.println("no pulses");
  } else {
    Serial.print(1000000.0 / (hi + lo), 1);
    Serial.println(" Hz");
  }
}

void setup() {
  Serial.begin(9600);
  pinMode(PROBE, INPUT_PULLUP);
}

void loop() {
  if (phase == 0) {
    analogWrite(3, 128);
    measure("analogWrite(3, 128)        ");
  } else if (phase == 1) {
    tone(7, 1000);                     // Timer2 is now tone()'s
    measure("tone(7, 1000) playing      ");
  } else if (phase == 2) {
    noTone(7);
    measure("noTone(7)                  ");
  } else {
    analogWrite(3, 128);               // asks for PWM again
    measure("analogWrite(3, 128) again  ");
    Serial.println();
  }
  phase = (phase + 1) % 4;
  delay(2000);
}

The Serial Monitor shows 490.2 Hz, then no pulses while the tone plays, then still no pulses after noTone(), then 490.2 Hz once analogWrite runs again. Move the wire's 3 end to 7 during the tone and D8 times the tone itself: 1000 Hz.

When it does not work

PWM on 3 or 11 stopped and never came back

tone() reprogrammed Timer2. noTone() sets the timer back to PWM mode, but the pin is no longer connected to it until the next analogWrite on that pin. Call analogWrite again after noTone().

Lamps on 9 and 10 stopped dimming when I added a servo

The Servo library takes Timer1 on this chip as soon as the first servo is attached, whichever pin the servo is on, and detach() does not hand it back. Move the lamps to 3, 5, 6 or 11, or the servo to any pin and the lamps off 9 and 10.

A second tone() call does nothing

Only one tone plays at a time. A call for a different pin while one is playing is ignored; a call for the same pin changes its frequency. Call noTone() on the first pin before starting the second.

delay() and millis() run fast or slow after I changed a timer setting

Timer0 keeps the time. Code that changes its prescaler, often copied to make PWM on 5 and 6 faster, changes the length of a millisecond too. Change Timer1 or Timer2 instead, and accept losing what uses them.

Alongside this page
Where this goes next

The two pins the USB serial line runs on, and why the TX lamp lights when D1 is LOW.

Serial on D0 and D1 →

Edit this page — content/books/atmega328p/timers-tone-and-servo.mdx

Discuss this article

Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.

Browse Modules and blocks on the forum →