noTone()

概要

noTone()は、tone()関数で開始したピンへの方形波の出力を停止します。

tone()の出力に利用しているタイマ/カウンタの番号を調べてタイマ/カウンタを停止します。

noTone()のリファレンスはこちらを参照してください。

ソースコード

noTone()は、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);
}

AVAILABLE_TONE_PINSは1に定義されています。同時にtone()を利用できるピンの数です。

tone_pin_to_timer_PGM[]は、利用するタイマ/カウンタを定義する配列です。現状、“2"だけが定義されています。

tone_pins[]は、tone_pin_to_timer_PGM[]に対応するタイマ/カウンタで利用しているピンを表します。tone()が実行された後は、tone()の出力を行っているデジタルピンの番号が入っています。

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 */ };

noTone()の入力は_pinでuint8_t型の変数です。返却値はありません。

指定された_pinが利用中のピンかどうかを調べます。見つかった場合は、_timerにタイマの番号を代入し、tone_pins[i]を255(未使用)に設定します。

 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;
    }
  }

pgm_read_byte()は、指定したアドレス(PROGMEM領域)に格納されているデータを1バイト読み取るためのマクロです。tone_pin_to_timer_PGMは配列なので、tone_pin_to_timer_PGM+iは、配列の第i番目の要素を示します。

次にdisableTimer()を呼び出しタイマを停止します。最後に、digitalWrite()でピンへの出力を停止します。

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

最後に無条件でdigitalWrite()を行っているため、tone()で出力していないピンを指定しても、そのピンのデジタル出力はオフになります。

バージョン

Arduino AVR Boards 1.8.6

最終更新日

March 21, 2023

inserted by FC2 system