06 Pico W網路應用

(2022/12/11)

  • Raspberry Pi Pico W 式款低成本且高靈活應用的 RP2040 開發平台,此外還有2.4GHz 無線接口和以下主要功能:

    • 內建 2MB 外部閃存的 RP2040 微控制器晶片

    • 2.4GHz 無線 (802.11n) 介開發板載

    • 用於電源、數據與對閃存重新編程的微型 USB 接口

    • 帶有 0.1 英寸通孔針的 40 針 21mm×51mm 'DIP' 型 1mm 厚的邊緣齒型 PCB

    • 外露 26 個多功能 3.3V 通用 I/O (GPIO)

    • 有 23 個僅適用於數字與另外 3 個支援 ADC 的 GPIO

    • 可作為模組進行表面貼裝

  • Raspberry Pi Pico W 的完整詳細訊息可在 Raspberry Pi Pico W 數據表 中找到



  • 連結至無線網路

    • 參考網站:https://www.oursteam.com.tw/view-resources.php?id=234

    • 程式

      • import network

      • import time


      • wlan = network.WLAN(network.STA_IF)

      • wlan.active(True)

      • wlan.connect('cc1', '075565940')


      • while not wlan.isconnected() and wlan.status() >= 0:

      • print("Waiting to connect:")

      • time.sleep(1)


      • print(wlan.ifconfig())

  • 雖然上述代碼正確,但您應該還是要等待代碼連接成功或連接失敗,然後處理任何連接可能發生的錯誤。

    • import time

    • import network


    • ssid = 'cc1'

    • password = '075565940'


    • wlan = network.WLAN(network.STA_IF)

    • wlan.active(True)

    • wlan.connect(ssid, password)


    • # Wait for connect or fail

    • max_wait = 10

    • while max_wait > 0:

    • if wlan.status() < 0 or wlan.status() >= 3:

    • break

    • max_wait -= 1

    • print('waiting for connection...')

    • time.sleep(1)


    • # Handle connection error

    • if wlan.status() != 3:

    • raise RuntimeError('network connection failed')

    • else:

    • print('connected')

    • status = wlan.ifconfig()

    • print( 'ip = ' + status[0] )

  • 有關 network.WLAN庫的更多訊息,請參閱 庫文檔

  • 發出 HTTP 請求

    • 您可以使用原始套接字對 HTTP 請求採用低級方法

      • 搭配 sockets 的 HTTP

        • # Connect to network

        • import network


        • wlan = network.WLAN(network.STA_IF)

        • wlan.active(True)

        • wlan.connect('Wireless Network', 'The Password')


        • # Should be connected and have an IP address

        • wlan.status() # 3 == success

        • wlan.ifconfig()


        • # Get IP address for google

        • import socket

        • ai = socket.getaddrinfo("google.com", 80)

        • addr = ai[0][-1]


        • # Create a socket and make a HTTP request

        • s = socket.socket()

        • s.connect(addr)

        • s.send(b"GET / HTTP/1.0\r\n\r\n")


        • # Print the response

        • print(s.recv(512))

    • 也可以使用 urequests 庫採用高級方法。

      • 搭配 urequests 的 HTTP

        • # Connect to network

        • import network

        • wlan = network.WLAN(network.STA_IF)

        • wlan.active(True)

        • wlan.connect('Wireless Network', 'The Password')


        • # Make GET request

        • import urequests

        • r = urequests.get("http://www.google.com")

        • print(r.content)

        • r.close()

  • 利用網頁來控制內建LED燈的亮滅

    • 掃描WiFi

      • import network

      • wlan = network.WLAN(network.STA_IF)

      • wlan.active(True)

      • print(wlan.scan())

    • 建一個secrets.py來存WIFI的SSID及密碼

      • secrets = {

      • 'ssid': 'Replace-this-with-your-Wi-Fi-Name',

      • 'pw': 'Replace-this-with-your-Wi-Fi-Password'

      • }

    • 主要程式(main,py)

      • import rp2

      • import network

      • import ubinascii

      • import machine

      • import urequests as requests

      • import time

      • from secrets import secrets

      • import socket


      • # Set country to avoid possible errors

      • rp2.country('DE')


      • wlan = network.WLAN(network.STA_IF)

      • wlan.active(True)

      • # If you need to disable powersaving mode

      • # wlan.config(pm = 0xa11140)


      • # See the MAC address in the wireless chip OTP

      • mac = ubinascii.hexlify(network.WLAN().config('mac'),':').decode()

      • print('mac = ' + mac)


      • # Other things to query

      • # print(wlan.config('channel'))

      • # print(wlan.config('essid'))

      • # print(wlan.config('txpower'))


      • # Load login data from different file for safety reasons

      • ssid = secrets['ssid']

      • pw = secrets['pw']


      • wlan.connect(ssid, pw)


      • # Wait for connection with 10 second timeout

      • timeout = 10

      • while timeout > 0:

      • if wlan.status() < 0 or wlan.status() >= 3:

      • break

      • timeout -= 1

      • print('Waiting for connection...')

      • time.sleep(1)


      • # Define blinking function for onboard LED to indicate error codes

      • def blink_onboard_led(num_blinks):

      • led = machine.Pin('LED', machine.Pin.OUT)

      • for i in range(num_blinks):

      • led.on()

      • time.sleep(.2)

      • led.off()

      • time.sleep(.2)

      • # Handle connection error

      • # Error meanings

      • # 0 Link Down

      • # 1 Link Join

      • # 2 Link NoIp

      • # 3 Link Up

      • # -1 Link Fail

      • # -2 Link NoNet

      • # -3 Link BadAuth


      • wlan_status = wlan.status()

      • blink_onboard_led(wlan_status)


      • if wlan_status != 3:

      • raise RuntimeError('Wi-Fi connection failed')

      • else:

      • print('Connected')

      • status = wlan.ifconfig()

      • print('ip = ' + status[0])

      • # Function to load in html page

      • def get_html(html_name):

      • with open(html_name, 'r') as file:

      • html = file.read()

      • return html


      • # HTTP server with socket

      • addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]


      • s = socket.socket()

      • s.bind(addr)

      • s.listen(1)


      • print('Listening on', addr)

      • led = machine.Pin('LED', machine.Pin.OUT)


      • # Listen for connections

      • while True:

      • try:

      • cl, addr = s.accept()

      • print('Client connected from', addr)

      • r = cl.recv(1024)

      • # print(r)

      • r = str(r)

      • led_on = r.find('?led=on')

      • led_off = r.find('?led=off')

      • print('led_on = ', led_on)

      • print('led_off = ', led_off)

      • if led_on > -1:

      • print('LED ON')

      • led.value(1)

      • if led_off > -1:

      • print('LED OFF')

      • led.value(0)

      • response = get_html('index.html')

      • cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')

      • cl.send(response)

      • cl.close()

      • except OSError as e:

      • cl.close()

      • print('Connection closed')


      • # Make GET request

      • #request = requests.get('http://www.google.com')

      • #print(request.content)

      • #request.close()

    • index.html

      • <!DOCTYPE html>

      • <html>

      • <head>

      • <title>Pico W</title>

      • </head>

      • <body>

      • <h1>Pico W</h1>

      • <p>Control the onboard LED</p>

      • <a href=\"?led=on\"><button>ON</button></a>&nbsp;

      • <a href=\"?led=off\"><button>OFF</button></a>

      • </body>

      • </html>