import network,usocket,time
from machine import SoftI2C,Pin,Timer
from ssd1306 import SSD1306_I2C
#初始化相关模块
i2c = SoftI2C(sda=Pin(42), scl=Pin(40))
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)
#WIFI 连接函数
def WIFI_Connect():
WIFI_LED=Pin(46, Pin.OUT) #初始化 WIFI 指示灯
wlan = network.WLAN(network.STA_IF) #STA 模式
wlan.active(True) #激活接口
start_time=time.time() #记录时间做超时判断
if not wlan.isconnected():
print('Connecting to network...')
wlan.connect('aaa','bbb') #输入 WIFI 账号密码
while not wlan.isconnected():
#LED 闪烁提示
WIFI_LED.value(1)
time.sleep_ms(300)
WIFI_LED.value(0)
time.sleep_ms(300)
#超时判断,15 秒没连接成功判定为超时
if time.time()-start_time > 15 :
print('WIFI Connected Timeout!')
break
if wlan.isconnected():
#LED 点亮
WIFI_LED.value(1)
#串口打印信息
print('network information:', wlan.ifconfig())
#OLED 数据显示
oled.fill(0) #清屏背景黑色
oled.text('IP/Subnet/GW:',0,0)
oled.text(wlan.ifconfig()[0], 0, 20)
oled.text(wlan.ifconfig()[1],0,38)
oled.text(wlan.ifconfig()[2],0,56)
oled.show()
return True
else:
return False
#判断 WIFI 是否连接成功
if WIFI_Connect():
#创建 socket 连接 TCP 类似,连接成功后发送“Hello 01Studio!”给服务器。
s=usocket.socket()
addr=('192.168.100.2',8089) #服务器 IP 和端口
s.connect(addr)
s.send('Hello 01Studio!')
while True:
text=s.recv(128) #单次最多接收 128 字节
if text == '':
pass
else: #打印接收到的信息为字节,可以通过 decode('utf-8')转成字符串
print(text)
s.send('I got:'+text.decode('utf-8'))
time.sleep_ms(300)
```python
```python
上面代码连接ESP32为什么报错