W5500-EVB-PICO(RP2040)报[Errno 107] ENOTCONN错误求助
W5500-EVB-PICO 以太网连接出现 [Errno 107] ENOTCONN 错误排查与解决
问题描述
我使用W5500-EVB-PICO通过以太网连接网络,后续计划将BME680数据发送至ThingSpeak。但无论尝试rp2_w5500_20220318_v1.04.uf2、rp2_w5500_20220421_v1.0.5.uf2、rp2_w5500_20221111_v2.0.0.uf2哪个固件,始终出现“Socket operation failed: [Errno 107] ENOTCONN”错误。
测试代码 MAIN2.py
from machine import Pin, SPI import network import socket import time # Pin definitions SPI_MOSI_PIN = 19 SPI_MISO_PIN = 16 SPI_SCK_PIN = 18 SPI_CS_PIN = 17 RESET_PIN = 20 LED_PIN = 25 # Initialize LED led = Pin(LED_PIN, Pin.OUT) def init_ethernet(): """Initialize W5500 Ethernet connection""" print("\nInitializing Ethernet...") led.value(0) try: # Initialize SPI for W5500 print("Initializing SPI...") spi = SPI(0, baudrate=500_000, mosi=Pin(SPI_MOSI_PIN), miso=Pin(SPI_MISO_PIN), sck=Pin(SPI_SCK_PIN)) # Initialize CS and Reset pins print("Initializing control pins...") cs = Pin(SPI_CS_PIN, Pin.OUT) reset = Pin(RESET_PIN, Pin.OUT) # Hard reset sequence print("Performing hard reset sequence...") cs.value(1) reset.value(1) time.sleep(0.5) reset.value(0) time.sleep(0.5) reset.value(1) time.sleep(0.5) # Initialize WIZNET5K print("Creating network interface...") nic = network.WIZNET5K(spi, cs, reset) time.sleep(1) # Configure network with retries print("Activating interface and waiting for DHCP...") retry_count = 0 max_retries = 5 connected = False while not connected and retry_count < max_retries: try: retry_count += 1 print("\nAttempt {}/{}:".format(retry_count, max_retries)) # Reset interface print("Resetting interface...") nic.active(False) time.sleep(1) nic.active(True) time.sleep(1) # Wait for DHCP configuration print("Waiting for DHCP configuration", end="") for _ in range(15): # 15 second timeout if nic.isconnected(): config = nic.ifconfig() if config[0] != '0.0.0.0': # Valid IP received connected = True break print(".", end="") time.sleep(1) print() if connected: print("\nNetwork configured successfully:") print("IP:", config[0]) print("Subnet:", config[1]) print("Gateway:", config[2]) print("DNS:", config[3]) break else: print("DHCP configuration failed, retrying...") except Exception as e: print("Attempt failed:", str(e)) time.sleep(2) if not connected: raise Exception("Failed to configure network after {} attempts".format(max_retries)) print("\nNetwork interface ready!") time.sleep(2) # Final stabilization delay return nic except Exception as e: print("Error in init_ethernet:", str(e)) led.value(0) raise def test_network(nic): """Test network connectivity""" sock = None try: print("\nTesting network connection...") # Check basic connectivity print("Interface connected:", nic.isconnected()) print("Interface active:", nic.active()) # Get network config config = nic.ifconfig() print("\nNetwork configuration:") print("IP:", config[0]) print("Subnet:", config[1]) print("Gateway:", config[2]) print("DNS:", config[3]) # Test local connection first print("\nTesting local connection...") try: sock = socket.socket() sock.settimeout(5) print("Connecting to gateway...") sock.connect((config[2], 80)) print("Gateway connection successful!") sock.close() sock = None except Exception as e: print("Gateway connection failed:", str(e)) if sock: sock.close() sock = None # Test internet connection print("\nTesting internet connection...") try: sock = socket.socket() sock.settimeout(5) print("Connecting to 8.8.8.8...") sock.connect(("8.8.8.8", 53)) print("Internet connection successful!") sock.close() sock = None except Exception as e: print("Internet connection failed:", str(e)) if sock: sock.close() sock = None # Test DNS resolution print("\nTesting DNS resolution...") try: print("Resolving api.thingspeak.com...") addr_info = socket.getaddrinfo("api.thingspeak.com", 80) print("DNS response:", addr_info) server_addr = addr_info[0][-1] print("Server address:", server_addr) sock = socket.socket() sock.settimeout(10) print("\nConnecting to ThingSpeak...") sock.connect(server_addr) print("ThingSpeak connection successful!") print("\nSending test request...") request = b"GET / HTTP/1.0\r\nHost: api.thingspeak.com\r\n\r\n" sock.write(request) print("Reading response...") response = sock.read(256) if response: print("Response received:", response) else: print("No response received") except Exception as e: print("ThingSpeak connection failed:", str(e)) finally: if sock: sock.close() print("Socket closed") return True except Exception as e: print("\nTest failed:", str(e)) if sock: try: sock.close() except: pass return False def main(): """Main diagnostic loop""" while True: try: # Initialize ethernet nic = init_ethernet() # Wait for DHCP print("\nWaiting for DHCP...") for _ in range(20): if nic.isconnected(): break print(".", end="") time.sleep(1) print() # Run network tests if test_network(nic): led.value(1) print("\nAll tests completed. Press Ctrl+C to exit.") while True: time.sleep(1) except Exception as e: print("Error in main loop:", str(e)) led.value(0) time.sleep(5) if __name__ == "__main__": main()
运行报错日志
MPY: soft reboot Initializing Ethernet... Initializing SPI... Initializing control pins... Performing hard reset sequence... Creating network interface... Activating interface and waiting for DHCP... Attempt 1/5: Resetting interface... netif changed 10.10.1.6 Waiting for DHCP configuration Network configured successfully: IP: 10.10.1.6 Subnet: 255.255.255.0 Gateway: 10.10.1.1 DNS: 10.10.1.1 Network interface ready! Waiting for DHCP... Testing network connection... Interface connected: True Interface active: None Network configuration: IP: 10.10.1.6 Subnet: 255.255.255.0 Gateway: 10.10.1.1 DNS: 10.10.1.1 Testing local connection... Gateway connection failed: [Errno 107] ENOTCONN Testing internet connection... Internet connection failed: [Errno 107] ENOTCONN Testing DNS resolution... Resolving api.thingspeak.com... DNS response: [(2, 1, 0, '', ('54.172.245.49', 80))] Server address: ('54.172.245.49', 80) ThingSpeak connection failed: [Errno 107] ENOTCONN Socket closed All tests completed. Press Ctrl+C to exit.
问题原因与解决方案
核心原因
日志显示DHCP已成功获取IP,但所有socket连接均返回ENOTCONN,关键异常点是Interface active: None——说明网络接口状态异常,且默认创建的socket未绑定到W5500硬件接口,而是指向了RP2040的虚拟网卡(无实际连接)。
解决步骤
强制socket绑定到W5500接口
不要直接用socket.socket()创建套接字,改用nic.socket()直接从WIZNET5K接口生成绑定好的socket:# 替换所有 sock = socket.socket() 的行 sock = nic.socket()修复SPI波特率
代码中500K的波特率过低,W5500支持最高10MHz波特率,过低可能导致通信不稳定:spi = SPI(0, baudrate=10_000_000, # 修改为10MHz mosi=Pin(SPI_MOSI_PIN), miso=Pin(SPI_MISO_PIN), sck=Pin(SPI_SCK_PIN))简化接口激活流程
多次切换nic.active(False/True)会导致接口状态混乱,硬重置后直接激活即可:# 替换init_ethernet中的重置接口代码块 print("Activating interface...") nic.active(True) time.sleep(2)调整连通性测试方式
网关80端口通常不对外开放,改用路由器管理端口(如8080)或ping替代(MicroPython可通过ICMP socket实现,或跳过网关测试直接测公网)。
修改后的测试片段示例
# 测试本地连接部分修改 print("\nTesting local connection...") try: sock = nic.socket() sock.settimeout(5) print("Connecting to gateway admin port...") sock.connect((config[2], 8080)) # 替换为你的网关管理端口 print("Gateway connection successful!") sock.close() except Exception as e: print("Gateway connection failed:", str(e)) if sock: sock.close()
内容的提问来源于stack exchange,提问作者user30151196
相关产品推荐
相关产品推荐

