树莓派PICO W网络操作(联网)

树莓派PICO W网络操作(联网)

连接网络

连接网络,当正在连接的时候,自带led闪烁,当连接成功后led灯熄灭

import network
import time
from machine import Pin, Timer
ssid = 'Xiaomi_FANFAN'# 你的wifi名字
password ='yangfan0522'# 你的wifi密码

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
led = Pin("LED", Pin.OUT)

# Wait for connect or fail
max_wait = 10
while max_wait > 0:
    if wlan.status() < 0 or wlan.status() >= 3:
        break
    max_wait -= 1
    led.on()
    print('正在联网...')
 
    time.sleep(1)
    led.off()

# Handle connection error
if wlan.status() != 3:
    raise RuntimeError('network connection failed')
else:
    print('连接成功')
    status = wlan.ifconfig()
    
    print( 'ip = ' + status[0] )

urequests发送GET请求

注意!!使用urequests库发出请求后,必须使用response.close()关闭返回的响应对象。如果
不这样做,对象将不会被垃圾回收,如果请求是在循环中发出的,会出现不可预料的事。

 

import urequests
r = urequests.get('https://www.baidu.com/')
print(r.content)
r.close()

完整代码

import network
import time
from machine import Pin, Timer
ssid = 'Xiaomi_FANFAN'# 你的wifi名字
password ='yangfan0522'# 你的wifi密码

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
led = Pin("LED", Pin.OUT)

# Wait for connect or fail
max_wait = 10
while max_wait > 0:
    if wlan.status() < 0 or wlan.status() >= 3:
        break
    max_wait -= 1
    led.on()
    print('正在联网...')
 
    time.sleep(1)
    led.off()

# Handle connection error
if wlan.status() != 3:
    raise RuntimeError('network connection failed')
else:
    print('连接成功')
    status = wlan.ifconfig()
    
    print( 'ip = ' + status[0] )
    
    
import urequests
r = urequests.get('https://www.baidu.com/')
print(r.content)
r.close()

重定向https

import urequests
r = urequests.get('https://www.baidu.com/')
print(r.status_code) # redirects to https
r.close()

 

简单的支持json

import urequests
import ujson
r = urequests.get("http://date.jsontest.com/")
print(r.json())
r.close()

 

© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容