WiFi模块使用AT+lwip上网
LWIP介绍
lwIP is a small independent implementation of the TCP/IP protocol suite that has been initially developed by Adam Dunkels and is now continued here.The focus of the lwIP TCP/IP implementation is to reduce resource usage while still having a full scale TCP. This makes lwIP suitable for use in embedded systems with tens of kilobytes of free RAM and room for around 40 kilobytes of code ROM.Main features include:
- Protocols: IP, IPv6, ICMP, ND, MLD, UDP, TCP, IGMP, ARP, PPPoS, PPPoE
- DHCP client, DNS client (incl. mDNS hostname resolver), AutoIP/APIPA (Zeroconf), SNMP agent (v1, v2c, v3, private MIB support & MIB compiler)
- APIs: specialized APIs for enhanced performance, optional Berkeley-alike socket API
- Extended features: IP forwarding over multiple network interfaces, TCP congestion control, RTT estimation and fast recovery/fast retransmit
- Addon applications: HTTP(S) server, SNTP client, SMTP(S) client, ping, NetBIOS nameserver, mDNS responder, MQTT client, TFTP server
使用UART接口和AT命令连接WiFi模块(如ESP8266),也可以使用LwIP协议栈。这种情况下,需要在LwIP和WiFi模块之间创建一个适配层。这个方案在资源受限的MCU项目中很常见。
实现方式
- 架构设计
应用层 → LwIP协议栈 → 网络接口适配层 → AT命令解析层 → UART驱动 → WiFi模块
- 网络接口适配
需要实现一个自定义的netif(网络接口)来连接LwIP和AT命令层:
// 创建并初始化网络接口
err_t at_wifi_if_init(struct netif *netif)
{// 设置发送函数netif->output = etharp_output; // 用于IPv4netif->linkoutput = at_wifi_output; // 你的自定义发送函数// 设置MTU、MAC等netif->mtu = 1460; // ESP8266的典型值// ...其他初始化代码return ERR_OK;
}
// 实现发送数据包的函数
err_t at_wifi_output(struct netif *netif, struct pbuf *p)
{// 将LwIP的pbuf转换为AT命令// 通常使用AT+CIPSEND命令char cmd[32];sprintf(cmd, "AT+CIPSEND=%d\r\n", p->tot_len);uart_send_string(cmd);// 等待'>'提示符if (wait_for_prompt('>')) {// 发送实际数据pbuf_copy_partial(p, uart_tx_buffer, p->tot_len, 0);uart_send_data(uart_tx_buffer, p->tot_len);// 等待发送OKreturn wait_for_response("SEND OK"