2015年3月5日木曜日

Arduino UNOのピンマップとpinMode( )の関係について

Arduinoにおいて特定のピン操作をしたい時があります。

出典:ATmega168/328のArduino Pin Mapping

例えば、上図のPD5やPD6をhighにしたいlowにしたい!とか、そこでpinMode()を使用します

・pinMode()の詳細
http://arduino.cc/en/Reference/PinMode
仕様を抜粋すると

Syntax
pinMode(pin, mode)
Parameters
pin: the number of the pin whose mode you wish to set
mode: INPUT, OUTPUT, or INPUT_PULLUP.

引数pinには数字を指定しますが、ピンマッピングと照らし合わせることができず、直感的ではありません。

どっかで定義されてないかなとArduinoIDEのフォルダを眺めていたら、USB Host Shieldライブラリ内のavrpin.hに参考になる箇所がありました。それをベースにピンマップの対応をdefine文でおこすと以下のとおり。

#define PD0 0
#define PD1 1
#define PD2 2
#define PD3 3
#define PD4 4
#define PD5 5
#define PD6 6
#define PD7 7

#define PB0 8
#define PB1 9
#define PB2 10
#define PB3 11
#define PB4 12
#define PB5 13

#define PC0 14
#define PC1 15
#define PC2 16
#define PC3 17
#define PC4 18
#define PC5 19

公式のLED点滅のサンプルを置き換えてみると

// LED connected to digital pin 13 = PB5

int pin=PB5;
void setup()
{
    pinMode(
pin, OUTPUT); // sets the digital pin as output
}
    void loop()
{
    digitalWrite(
pin, HIGH); // sets the LED on
    delay(1000); // waits for a second
    digitalWrite(
pin, LOW); // sets the LED off
    delay(1000); // waits for a second
}



これでピンマップに従いながら開発をすることができます。