digitalPinToTimer()

概要

digitalPinToTimer()は、指定したピンに対応するタイマを返すマクロです。

ソースコード

digitalPinToTimer()は、hardware/arduino/avr/cores/arduino/Arduino.h に定義されています。以下に全ソースコードを示します。

1
#define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )

入力はPで、digital_pin_to_timer_PGMにPを足した値をpgm_read_byte()に渡しています。pgm_read_byte()は、PROGMEM指定した変数を読み出すためのマクロで、hardware/tools/avr/avr/include/avr/pgmspace.hに定義されています。

digital_pin_to_timer_PGMは、(Arduino Unoの場合)hardware/arduino/avr/variants/standard/pins_arduino.hで定義されていて、以下に示す配列です。この配列はPROGMEMが指定されているため、SRAMではなくフラッシュメモリに配置されます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
	NOT_ON_TIMER, /* 0 - port D */
	NOT_ON_TIMER,
	NOT_ON_TIMER,
	TIMER2B,
	NOT_ON_TIMER,
	TIMER0B,
	TIMER0A,
	NOT_ON_TIMER,
	NOT_ON_TIMER, /* 8 - port B */
	TIMER1A,
	TIMER1B,
	TIMER2A,
	NOT_ON_TIMER,
	NOT_ON_TIMER,
	NOT_ON_TIMER,
	NOT_ON_TIMER, /* 14 - port C */
	NOT_ON_TIMER,
	NOT_ON_TIMER,
	NOT_ON_TIMER,
	NOT_ON_TIMER,
};

digital_pin_to_timer_PGMは配列なので、digital_pin_to_timer_PGM + (P)というのは、足し算は足し算ですが、配列digital_pin_to_timer_PGMのP+1番目の要素が入っているアドレスを表すことになります。C言語では、配列x[i]は、*(x + i)という形でアクセスすることができます。例えば、Pが3のときは、4番目(配列は0番から始まります)の要素であるTIMER2Bが入っているアドレスということになります。

結果としてdigitalPinToTimer()は、フラッシュメモリに配置したdigital_pin_to_timer_PGMのP+1番目の要素を返却することになります。

バージョン

Arduino AVR Boards 1.8.6

最終更新日

March 21, 2023

inserted by FC2 system