#include "w5500_init.h" #include #include "socket.h" // W5500 Network Configuration wiz_NetInfo gWIZNETINFO = { .mac = {0x00, 0x08, 0xDC, 0x12, 0x34, 0x56}, // MAC 地址 .ip = {169, 254, 1, 11}, // IP 地址 .sn = {255, 255, 255, 0}, // 子网掩码 .gw = {169, 254, 1, 1}, // 网关地址 .dns = {8, 8, 8, 8}, // DNS 服务器 .dhcp = NETINFO_STATIC // 静态IP模式 }; // W5500 SPI 读写函数 static void W5500_Select(void) { HAL_GPIO_WritePin(NET_CS_GPIO_Port, NET_CS_Pin, GPIO_PIN_RESET); } static void W5500_Deselect(void) { HAL_GPIO_WritePin(NET_CS_GPIO_Port, NET_CS_Pin, GPIO_PIN_SET); } static void W5500_ReadBuff(uint8_t* buff, uint16_t len) { HAL_SPI_Receive(&hspi2, buff, len, HAL_MAX_DELAY); } static void W5500_WriteBuff(uint8_t* buff, uint16_t len) { HAL_SPI_Transmit(&hspi2, buff, len, HAL_MAX_DELAY); } static uint8_t W5500_ReadByte(void) { uint8_t byte; W5500_ReadBuff(&byte, 1); return byte; } static void W5500_WriteByte(uint8_t byte) { W5500_WriteBuff(&byte, 1); } // UDP日志相关定义 #define UDP_LOG_PORT 8888 // UDP日志端口 #define UDP_LOG_SOCKET 7 // 使用Socket 7作为日志socket // 初始化UDP日志功能 int8_t UDP_Log_Init(void); // 发送UDP日志数据 void UDP_Log_Send(const uint8_t* data, uint16_t len); static uint8_t udp_log_buffer[1024]; // UDP发送缓冲区 int8_t UDP_Log_Init(void) { // 关闭可能已经打开的socket close(UDP_LOG_SOCKET); // 以UDP模式打开socket if(socket(UDP_LOG_SOCKET, Sn_MR_UDP, UDP_LOG_PORT, 0) != UDP_LOG_SOCKET) { return -1; } return 0; } void UDP_Log_Send(const uint8_t* data, uint16_t len) { uint8_t broadcast_ip[] = {255, 255, 255, 255}; // 广播地址 sendto(UDP_LOG_SOCKET, data, len, broadcast_ip, UDP_LOG_PORT); } // printf重定向相关实现 #ifdef __GNUC__ int _write(int file, char *ptr, int len) { UDP_Log_Send((uint8_t*)ptr, len); return len; } #elif defined(__ICCARM__) size_t __write(int handle, const unsigned char *buffer, size_t size) { UDP_Log_Send(buffer, size); return size; } #endif int8_t W5500_Init(void) { // 1. 注册通信函数 reg_wizchip_cs_cbfunc(W5500_Select, W5500_Deselect); reg_wizchip_spi_cbfunc(W5500_ReadByte, W5500_WriteByte); reg_wizchip_spiburst_cbfunc(W5500_ReadBuff, W5500_WriteBuff); // 2. 初始化缓冲区大小 uint8_t rx_tx_buff_sizes[] = {2, 2, 2, 2, 2, 2, 2, 2}; // 每个Socket分配2K缓存 if(wizchip_init(rx_tx_buff_sizes, rx_tx_buff_sizes) < 0) { return -1; } // 3. 配置网络参数 wizchip_setnetinfo(&gWIZNETINFO); // 4. PHY 配置 wiz_PhyConf phyconf; phyconf.by = PHY_CONFBY_SW; phyconf.mode = PHY_MODE_AUTONEGO; phyconf.speed = PHY_SPEED_100; phyconf.duplex = PHY_DUPLEX_FULL; wizphy_setphyconf(&phyconf); // 5. 等待PHY就绪 uint32_t tick = HAL_GetTick(); while(1) { if(wizphy_getphylink() == PHY_LINK_ON) break; if(HAL_GetTick() - tick > 5000) { // 5秒超时 return -1; } } // 初始化UDP日志功能 if(UDP_Log_Init() < 0) { return -1; } return 0; }