Playing with Arduino
A page to record my playing with Arduino
noTone()

Abstract

The noTone() stops the output of square wave began by tone().

Checks the timer/counter number using by tone() and stops it.

Souce Code

The noTone() is defined in hardware/arduino/avr/cores/arduino/Tone.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#define AVAILABLE_TONE_PINS 1
 
// Leave timer 0 to last.
const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1, 0 */ };
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255 */ };
 
void noTone(uint8_t _pin)
{
  int8_t _timer = -1;
   
  for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
    if (tone_pins[i] == _pin) {
      _timer = pgm_read_byte(tone_pin_to_timer_PGM + i);
      tone_pins[i] = 255;
      break;
    }
  }
   
  disableTimer(_timer);
 
  digitalWrite(_pin, 0);
}

The AVAILABLE_TONE_PINS is set to 1. This is the number of pins that can be used at the same time.

The tone_pin_to_timer_PGM[] is an array that holds timer/counter. Currently only “2” is defined.

The tone_pins[] shows pins which is used by timer/counter, which is related to tone_pin_to_timer_PGM[].

1
2
3
4
5
#define AVAILABLE_TONE_PINS 1
 
// Leave timer 0 to last.
const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1, 0 */ };
static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255 */ };

The input is _pin and its type is uint8_t. There is no output.

Checks if the specified _pin is used. If found, set the timer number to _timer then sets tone_pins[i] to 255 which means unused.

 7
 8
 9
10
11
12
13
14
15
16
17
void noTone(uint8_t _pin)
{
  int8_t _timer = -1;
   
  for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
    if (tone_pins[i] == _pin) {
      _timer = pgm_read_byte(tone_pin_to_timer_PGM + i);
      tone_pins[i] = 255;
      break;
    }
  }

The pgm_read_byte() is a macro to read one byte from PROGMEM. As the tone_pin_to_timer_PGM is an array, tone_pin_to_timer_PGM+i means the i-th element of the array.

It calls disableTimer() to stop the timer. Then it calls digitalWrite() to stop the output to digital pin.

19
20
21
22
  disableTimer(_timer);
 
  digitalWrite(_pin, 0);
}

At the last it calls digitalWrite(), so the pin which is not used by tone() is specified, the output to the pin is stopped.

Version

Arduino 1.8.13

Last Update

June 19, 2020

inserted by FC2 system