กะพริบ LED บนบอร์ด Raspberry Pi Pico (Pico และ Pico W)
โปรเจกต์แรกของชุด Raspberry Pi Pico เราจะทำให้ LED สีเขียวบนบอร์ดกะพริบเพื่อตรวจสอบว่าบอร์ดทำงานได้ เป็นการทดลองแรกแบบ "Hello World" ที่คุ้นเคย ไม่ต้องใช้อุปกรณ์ภายนอก แค่ Pico กับสาย USB ก็พอ โค้ดเขียนด้วย MicroPython ซึ่งเป็นภาษาที่ Raspberry Pi Foundation รองรับอย่างเป็นทางการ

วิดีโอ
แผนผังวงจร

ซอร์สโค้ด
1# ─────────────────────────────────────────
2# BlueGrays · bluegrays.com
3# Raspberry Pi Pico Onboard LED Blink (Pico and Pico W)
4# ─────────────────────────────────────────
5# Blinks the onboard LED of the Pico every 0.5 s; the classic "Hello
6# World" project. No external parts, just the Pico and a USB cable. The
7# code works on both the Pico and the Pico W.
8#
9# Pins:
10# LED -> Onboard LED (on the board)
11
12from machine import Pin
13import time
14
15# ============ PIN / PIN ============
16# The name "LED" instead of a pin number: it finds the onboard LED on both the Pico and the Pico W
17# (on the Pico W this LED is wired to the Wi-Fi chip, not a GP pin).
18LED_PIN = "LED" # Onboard LED
19led = Pin(LED_PIN, Pin.OUT)
20
21print("== BlueGrays: Pico Onboard LED Blink ==")
22print("LED pin: LED (Pico / Pico W)")
23print("LED toggles every 500ms")
24
25# ============ MAIN LOOP ============
26while True:
27 led.on() # Turn the LED on
28 print("[LED] ON")
29 time.sleep(0.5)
30
31 led.off() # Turn the LED off
32 print("[LED] OFF")
33 time.sleep(0.5)
34
FAQ
โค้ดนี้ใช้กับ Pico W ได้ด้วยไหม
ได้ LED บนบอร์ด Pico W เชื่อมต่อกับชิป Wi-Fi แทนขา GP โค้ดจึงใช้ Pin('LED', Pin.OUT) แทนหมายเลขขา ชื่อนี้ใช้อ้างถึง LED บนบอร์ดได้ทั้ง Pico และ Pico W หาก LED บน Pico W ไม่ติด ให้ตรวจสอบว่าติดตั้งเฟิร์มแวร์ MicroPython สำหรับ Pico W แล้ว
ติดตั้ง MicroPython ลง Pico อย่างไร
กดปุ่ม BOOTSEL ค้างไว้ขณะเสียบ Pico เข้าพอร์ต USB คอมพิวเตอร์จะแสดงไดรฟ์ชื่อ "RPI-RP2" ลากไฟล์ MicroPython .uf2 ที่ดาวน์โหลดจากเว็บไซต์ Raspberry Pi ไปใส่ในไดรฟ์นี้ หรือใช้ Thonny IDE ทำขั้นตอนนี้โดยอัตโนมัติก็ได้
บันทึกโค้ดลง Pico อย่างไรให้ทำงานทุกครั้งที่เปิดเครื่อง
ใช้ Thonny บันทึกไฟล์ลงใน Pico ด้วยชื่อ "main.py" เมื่อ Pico ได้รับไฟเลี้ยง บอร์ดจะเรียกใช้ไฟล์ main.py โดยอัตโนมัติ
Thonny มองไม่เห็น Pico ต้องทำอย่างไร
เลือก "MicroPython (Raspberry Pi Pico)" ในเมนูเลือกตัวแปลภาษาที่มุมขวาล่าง ตรวจสอบว่าสาย USB เป็นสายที่รับส่งข้อมูลได้และติดตั้ง MicroPython แล้ว
