シェルスクリプトマガジン

Raspberry Pi Pico W/WHで始める電子工作(Vol.85掲載)

著者:米田 聡

本連載では、人気のマイコンボード「Raspberry Pi Pico W/WH」を活用していきます。同ボードは、無線LANやBluetoothの通信機能を搭載し、入手しやすく、価格も手頃なので、IoT機器を自作するのに最適なハードウエアです。第1回は、プログラムの開発環境を構築します。

シェルスクリプトマガジン Vol.85は以下のリンク先でご購入できます。

図17 初期化プログラム(boot.py)

import sys
import time
import network
import ntptime
from machine import RTC

SSID='your_ssid'
PASS='your_passphrase'

IFCONFIG=('192.168.1.80', '255.255.255.0', '192.168.1.1', '192.168.1.1')

def wifi_connect(ssid, passkey, timeout=20):
    conn = network.WLAN(network.STA_IF)
    if conn.isconnected():
        return conn
    
    conn.active(True)
    conn.connect(ssid, passkey)

    while not conn.isconnected() and timeout > 0:
        time.sleep(1)
        timeout -= 1
    if conn.isconnected():
        return conn
    else:
        return None

conn = wifi_connect(SSID, PASS)
if conn is None:
    print('Can not connect to ' + SSID)
else:
    conn.ifconfig(IFCONFIG)
    print('Connect to ' + SSID)
    # 日時設定
    rtc = RTC()
    ntptime.host = 'ntp.nict.jp'
    now = time.localtime(ntptime.time() + 9 * 60 * 60)
    rtc.datetime((now[0], now[1], now[2], now[6], now[3], now[4], now[5], 0))
    now = rtc.datetime()
    print("%04d-%02d-%02d %02d:%02d:%02d" %(now[0], now[1], now[2], now[4], now[5], now[6]))

図18 簡易ネットワークサーバー(main.py)

import usocket as socket
import network
import time

html = '''
<html>
    <head><title>Pico W</title></head>
    <body>
        <h1>Welcome to Pico W</h1>
    </body>
</html>
'''

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 80))
sock.listen(4)

while True:
    conn, addr = sock.accept()
    print('Connect from %s'  %(str(addr)));
    req = conn.recv(1024).decode()
    
    if not req.startswith('GET / HTTP/1.1'):
        conn.send('HTTP/1.1 404 Not Found\r\n')
        conn.close()
    else:
        conn.send('HTTP/1.1 200 OK\r\n')
        conn.send('Content-Type: text/html\r\n')
        conn.send('Connection: close\r\n\r\n')
        conn.sendall(html)
        conn.close()