概要
TIMER2_COMPA_vectは、タイマ/カウンタ2(TCNT2)と比較レジスタ(OCR2A)が同じ値になったときに起動される割り込みハンドラです。tone()の出力を制御するために利用しています。
ソースコード
TIMER2_COMPA_vectは、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
23
24
25
|
volatile long timer2_toggle_count;
volatile uint8_t *timer2_pin_port;
volatile uint8_t timer2_pin_mask;
ISR(TIMER2_COMPA_vect)
{
if (timer2_toggle_count != 0)
{
// toggle the pin
*timer2_pin_port ^= timer2_pin_mask;
if (timer2_toggle_count > 0)
timer2_toggle_count--;
}
else
{
// need to call noTone() so that the tone_pins[] entry is reset, so the
// timer gets initialized next time we call tone().
// XXX: this assumes timer 2 is always the first one used.
noTone(tone_pins[0]);
// disableTimer(2);
// *timer2_pin_port &= ~(timer2_pin_mask); // keep pin low after stop
}
}
|
timer2_toggle_countは、tone()を出力する期間を保持する変数です。timer2_pin_portは、tone()で出力するピンに対応するポート(digitalWrite()の説明)を保持します。timer2_pin_maskは、ポート内のピンに対応するビット位置を示します。
ISR()は、割り込みハンドラを定義する際に利用するマクロです。関数の属性を指定して、割り込みハンドラでの利用を示します。
8
9
10
11
12
13
14
15
|
if (timer2_toggle_count != 0)
{
// toggle the pin
*timer2_pin_port ^= timer2_pin_mask;
if (timer2_toggle_count > 0)
timer2_toggle_count--;
}
|
timer2_toggle_countが0でなければ、timer2_pin_portのtimer2_pin_maskの出力を反転させます。これにより、割り込みがかかるたびにピンの出力がオンとオフが切り替わります。一定間隔でピンの出力を切り替えているためデューティ比が50%になります。
time2_toggle_countが0よりも大きければデクリメントします。
16
17
18
19
20
21
22
23
24
25
|
else
{
// need to call noTone() so that the tone_pins[] entry is reset, so the
// timer gets initialized next time we call tone().
// XXX: this assumes timer 2 is always the first one used.
noTone(tone_pins[0]);
// disableTimer(2);
// *timer2_pin_port &= ~(timer2_pin_mask); // keep pin low after stop
}
}
|
timer2_toggle_countが0になったら、noTone()を呼んで、トーンの出力を停止します。
バージョン
Arduino AVR Boards 1.8.6
最終更新日
March 21, 2023