LoginSignup
7
6

Raspberry Pi Pico W を Wi-Fi に接続してみる。

Last updated at Posted at 2023-10-13

今回は Raspberry Pi Pico W を Wi-Fi に接続してみました。

Raspberry Pi Pico のセットアップなどがまだの場合は下記を参照してください。

環境

今回の環境は下記のとおりです。

開発端末

  • OS: Windows 11 Pro
  • CPU: Intel Core i7-9750H
  • メモリ: 64GB
  • GPU: NVIDIA GeForce RTX 2070 Max-Q

Python 環境

  • Python: 3.11.0

Raspberry Pi

Python コードの作成

Raspberry Pi Pico W を Wi-Fi ネットワークに接続するには、 Python でコードを書く必要があります。

動的 IP アドレスの場合

IP アドレスを Wi-Fi ルーター側で動的に割り当てる場合は、下記のコードで OK です。
SSIDPW に Wi-Fi ルーターのアクセスポイント名とそのパスワードを入力してください。

wlan.py
import network
import time

SSID = ''
PW = ''

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PW)

while wlan.isconnected() == False:
    print('Connecting to Wi-Fi router')
    time.sleep(1)

wlan_status = wlan.ifconfig()
print('Connected!')
print(f'IP Address: {wlan_status[0]}')
print(f'Netmask: {wlan_status[1]}')
print(f'Default Gateway: {wlan_status[2]}')
print(f'Name Server: {wlan_status[3]}')

静的 IP アドレスの場合

IP アドレスを固定したい場合は、次のようにします。
IP_ADDRESS に固定したい IP アドレスを指定してください。

wlan_static.py
import network
import time

SSID = ''
PW = ''
IP_ADDRESS = '192.168.0.81'

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PW)

while wlan.isconnected() == False:
    print('Connecting to Wi-Fi router')
    time.sleep(1)

wlan_status = wlan.ifconfig()
wlan.ifconfig((IP_ADDRESS, wlan_status[1], wlan_status[2], wlan_status[3]))

wlan_status = wlan.ifconfig()
print('Connected!')
print(f'IP Address: {wlan_status[0]}')
print(f'Netmask: {wlan_status[1]}')
print(f'Default Gateway: {wlan_status[2]}')
print(f'Name Server: {wlan_status[3]}')

参考文献

下記の書籍とサイトを参考にさせて頂きました。

  • 福田 和宏 . 最新Pico W対応! ラズパイPico完全ガイド . 株式会社日経BP , 2023

7
6
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
7
6