0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Raspberry Pi Pico 2WでLチカ(MicroPython)

0
Posted at

はじめに

最近はマイコンが高騰していることもあり、特に用途が決まっていたわけではないのですが、RaspberryPi Pico 2WHを確保しました。

ラズパイ系は今回が初めてなので、まずは環境構築と簡単なLチカから触ってみます。
せっかくWi‑Fi付きの“W”モデルなので、ブラウザからWi-Fi経由でオンボードLEDをON/OFFできる仕組みも試してみようかと思います。

環境構築

環境構築についてはこちらの方が非常にわかりやすく説明されていたので、ご参考ください。

ソースコード

環境構築できたら以下のソースコードをThonnyにコピペします。
Wi-Fi設定は自分の環境に合わせて書き換えてください。

import network
import socket
import time
from machine import Pin

# オンボードLED
led = Pin("LED", Pin.OUT)

# Wi-Fi設定
SSID = "x"
PASSWORD = "x"

# Wi-Fi接続
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)

timeout = 0
while not wlan.isconnected() and timeout < 20:
    timeout += 1
    time.sleep(0.5)

print("Wi-Fi接続成功")
ip = wlan.ifconfig()[0]
print("アクセス先:", "http://" + ip + ":8080")

# Webサーバ開始
addr = socket.getaddrinfo(ip, 8080)[0][-1]
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(1)

print("Webサーバ起動:", ip, ":8080")

# HTML(UI)
html = """\
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Pico LED</title></head>
<body>
<h2>Pico 2 W LED Control</h2>
<button onclick="location.href='/on'">LED ON</button>
<button onclick="location.href='/off'">LED OFF</button>
</body>
</html>
"""

# メインループ
while True:
    client, addr = s.accept()
    request = client.recv(1024).decode()

    # URL判定
    if request.startswith("GET /on"):
        led.on()
        print(addr[0], "LED ON")
    elif request.startswith("GET /off"):
        led.off()
        print(addr[0], "LED OFF")

    # HTML返却
    client.send("HTTP/1.1 200 OK\r\n")
    client.send("Content-Type: text/html\r\n")
    client.send("Connection: close\r\n\r\n")
    client.send(html)
    client.close()

実行

ソースコードを実行すると、シェルに接続先のIPアドレスが表示されます。
スクリーンショット 2026-06-28 183723.png

表示されたURLへアクセスすると、以下のようなUIが表示されます。
LED ONを押すとオンボードLEDが点灯し、LED OFFを押すと消灯します。
問題なく動作すれば、Wi‑Fi経由のLチカ成功です。
スクリーンショット 2026-06-28 183942.png

おわりに

今回はRaspberryPi Pico 2WHを使って、環境構築からMicroPythonでのLチカを実施しました。
最近はあまりアイデアが浮かばず伸び悩んでいますが、、、皆さまの記事を参考にしながらまた何か作ってみようと思います。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?