เข้าใจ ขา pinout ของ Arduino
ก่อนอื่นเรามาทบทวน spec ของ board arduino uno ที่ใช้ ATmega328p
Techinical Specification
Microcontroller: ATmega328P
Operating Voltage: 5v
Input Voltage: 7-20v
Digital I/O Pins: 14 (of which 6 provide PWM output)
Analog Input Pins: 6
DC Current per I/O Pin: 20 mA
DC Current for 3.3V Pin: 50 mA
Flash Memory: 32 KB of which 0.5 KB used by bootloader
SRAM: 2 KB
EEPROM: 1 KB
Clock Speed: 16 MHz
Length: 68.6 mm
Width: 53.4 mm
Weight: 25 g
ในการพัฒนา นั้นผู้พัฒนาต้องทำความเข้าใจเกี่ยวกับการใช้งาน pinout ของ Arduino เนื่องจากส่วนมากนักพัฒนาจะพัฒนาผ่าน IDE จะมีการอ้างอิงตาม Arduino pin ที่สามารถสังเกตุการใช้งานได้จาก label บน board ได้เลย จากรูปด้านล่างจะเห็นการ mapping ระหว่าง Arduino pin และ ATmega328p
ลองมาเปลี่ยน มุมมองบน board จริง เพื่อทำความเข้าใจ
เมื่อนำมาเขียน code ตามตัวอย่าง blink
1 2 3 4 5 6 7 8 9 10 11 12 |
void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } |
LED_BUILTIN คือค่าคงที่ ให้มีเชื่อมกับ pin 13 จะแสดงผลเป็น ไฟกระพริบ onboard โดยตรง
pinMode(LED_BUILTIN, OUTPUT) ฟังก์ชั่น pinMode() มีหน้าที่กำหนดให้ pin 13 ทำหน้าเป็น OUTPUT และจะใช้คำสั่งต่อมา คือ digitalWrite() กำหนดให้เป็น HIGH หรือ LOW
จะเป็น INPUT/OUTPUT จะเป็น High ถ้า
- ค่า Voltage มีค่ามากกว่า 3.0 v สำหรับ board 5v
- ค่า Voltage มีค่ามากกว่า 2.0 v สำหรับ board 3.3v (เช่น esp8266,esp32)
Syntax ของ pinMode
pinMode(pin, mode)
Parameters
pin
: ตำแหน่งของ pin ที่ต้องการตั้งค่า
mode
: สามารถกำหนดได้เป็น INPUT
, OUTPUT
, หรือ INPUT_PULLUP
Arduino ได้กำหนดให้มี pullup resisters ภายใน มีขนาด 20k ohm และสามารถ enable ให้ทำงานด้วย option INPUT_PULL
ทำให้ pin จะมีสถานะ เป็น HIGH (+5V) เมื่อไม่มีสัญญาณ input เข้า และ จะมีค่าเป็น LOW เมื่อ input เข้า (Senser on จะเป็น LOW, Senser off จะเป็น HIGH) โดยส่งผลให้มีการ กลับกัน เมื่อกำหนดค่าเป็น option INPUT