0%

基于micropython实现W5500创建tcpserver

使用本例程需要确认W5500驱动是否已经编译进固件,如果没有会报错
编译带W5500驱动的固件需要把MICROPY_PY_NETWORK_WIZNET5K选项加上
下边是测试源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
''' TCP Server example.
date: 2023-11-23
'''
from usocket import socket
from machine import Pin,SPI,UART
import time, network

''' static netinfo
'''
ip = '192.168.1.11'
sn = '255.255.255.0'
gw = '192.168.1.1'
dns= '8.8.8.8'

netinfo=(ip, sn, gw, dns)

localip = ''
localport = 8000
listen_info = (localip, localport)

''' uart0 init
baudrate: 115200
tx pin : gpio0
rx pin : gpio1
'''
uart = UART(0, 115200, tx=Pin(0), rx=Pin(1))
uart.init(115200, bits=8, parity=None, stop=1)
uart.write('WIZnet chip tcp server example.\r\n')

def w5x00_init():
global localip
''' spi0 init
baudrate: 2000000
mosi pin: gpio19
miso pin: gpio16
sck pin: gpio18
cs pin: gpio17
rst pin: gpio20
'''
spi=SPI(0,2_000_000, mosi=Pin(19),miso=Pin(16),sck=Pin(18))
nic = network.WIZNET5K(spi,Pin(17),Pin(20))
nic.active(True)
# use dhcp, if fail use static netinfo
try:
nic.ifconfig('dhcp')
except:
nic.ifconfig(netinfo)
localip = nic.ifconfig()[0]
print('ip :', nic.ifconfig()[0])
print('sn :', nic.ifconfig()[1])
print('gw :', nic.ifconfig()[2])
print('dns:', nic.ifconfig()[3])
uart.write('ip :{0}\r\n'.format(nic.ifconfig()[0]))
uart.write('sn :{0}\r\n'.format(nic.ifconfig()[1]))
uart.write('gw :{0}\r\n'.format(nic.ifconfig()[2]))
uart.write('dns:{0}\r\n'.format(nic.ifconfig()[3]))

while not nic.isconnected():
time.sleep(1)
# print(nic.regs())
print('no link')
uart.write('no link\r\n')

conn_flag = False

def server_loop():
global localip
global conn_flag
while True:
if(conn_flag == False):
uart.write('socket open\r\n')
s = socket()
s.bind(listen_info) # Source IP Address and Port
s.listen(5) # max conncet counts
conn_flag = True
print("TEST server Loop")
uart.write('TCP Server:{0} ,listen port:{1}\r\n'.format(localip, listen_info[1]))
conn, addr = s.accept()
print('Connect from %s' % str(addr))
uart.write('Connect from {0}:{1}\r\n'.format(addr[0], addr[1]))
else:

try:

data = conn.recv(2048)
data = data.decode('utf-8')

data+='\r\n'
uart.write(data)
if data != 'NULL':
conn.send(data)
except:
uart.write('disconnect')
conn_flag = False

def main():
w5x00_init()
server_loop()
if __name__ == "__main__":
main()