tpyboard v202 测试tcp通讯,i2c的oled程序,呼吸灯源码,希望对大家有所帮助
阅读原文时间:2023年07月14日阅读:1

**1、下载到板子里的main.py代码
**如果需要驱动oled的,可以参考我上面那篇文章
import time, math
import machine
import network
# from ssd1306 import SSD1306_I2C

def oled_text(str,x=0,y=0):

# from machine import I2C
# i2c=machine.I2C(-1, sda=machine.Pin(4), scl=machine.Pin(5), freq=100000)

# oled = SSD1306_I2C(128,64, i2c)
# oled.text(str, x, y)
# oled.show()
# now use socket as usual
import socket
def socket_server_test():
s = socket.socket()
host = socket.gethostname() # 获取本地主机名
port = 12345 # 设置端口
s.bind((host, port)) # 绑定端口
s.listen(5) # 等待客户端连接
while True:
c, addr = s.accept() # 建立客户端连接
print('连接地址:', addr)
c.send('tpyboard 正在通过tcp协议向server发送数据!')
c.close() # 关闭连接
def socket_clent_test():
s = socket.socket()
try :
s.connect(('192.168.31.244',55555))
s.send(b'test success')
data = s.recv(1000)
print (data)
s.close()
except Exception as e :
print (e)

def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network…')
wlan.connect('pang', 'ldx19891025')
while not wlan.isconnected():
print("wifi connecting")
# oled_text ("wifi connect success")

    print('network config:', wlan.ifconfig())

def pulse( t):
led = machine.PWM(machine.Pin(2), freq=100)
for i in range(20):
led.duty(int(math.sin(i / 10 * math.pi) * 500 + 500))
time.sleep_ms(t)

oled_text('--display test--', y=56)

while True:
do_connect()
time.sleep(1)
socket_clent_test()
print('-------')
# oled_text('--display test--',y=8)

pulse( 30)

2、后台电脑上的代码

#!/usr/bin/python3
# 文件名:server.py

导入 socket、sys 模块

import socket
import sys

创建 socket 对象

serversocket = socket.socket()
# 绑定端口号
serversocket.bind(("192.168.31.244", 55555))

设置最大连接数,超过后排队

serversocket.listen(5)

while True:
# 建立客户端连接
clientsocket, addr = serversocket.accept()
# print(clientsocket,addr)
print("连接地址: %s" % str(addr))
buf = clientsocket.recv(1024)
print (buf)
msg = 'test success !' + "\r\n"
clientsocket.send(msg.encode('utf-8'))
clientsocket.close()

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章