Esp8266 Wifi模块 优点:
1. 价格便宜
2. 体积小
Esp8266 缺点:
1. 冗余单片机应答信号过多 导致在处理能力不够的单片机上运行速度慢
2. 丢包率相对较高
3. Github库不多 实测大多不能用
该模块支持 TCP、UDP和双工模式,但TCP 协议传输速率很低,在多机WIFI实时通信中 采用UDP更加合理
下面给出我开发的WIFI封装库程序:
wifi.h
#include <SoftwareSerial.h>
void wifiSend(String s);
String wifiGet();
void setWifi();
wifi.cpp (根据需要修改AT指令的UDP连接地址即可)
#include <SoftwareSerial.h>
#include "wifi.h"
#include <Arduino.h>
#define WIFI_TX
#define WIFI_RX
SoftwareSerial wifi(WIFI_RX, WIFI_TX); //RX, TX
void wifiSend(String s);
String wifiGet();
void setWifi();
void getWifiSerialData();
String cutString(String s);
String _comdata_wifi = ""; //for incoming wifi serial data
void setWifi(){
wifi.begin();
Serial.println("system is ready!");
String order1="AT+CIPSTART=\"UDP\",\"192.168.0.100\",7300,1100,2";
order1.trim();
wifi.println(order1);
delay();
Serial.println("wifi is done!");
}
void wifiSend(String s){
String order="AT+CIPSEND=";
order=order+s.length();
order.trim();
wifi.println(order);
delay();
s.trim();
wifi.println(s);
}
String wifiGet(){
getWifiSerialData();
String res="";
if(_comdata_wifi!=""){
Serial.println(_comdata_wifi);
res=cutString(_comdata_wifi);
_comdata_wifi = String("");
}
return res;
}
void getWifiSerialData(){
while (wifi.available() > ){
_comdata_wifi += char(wifi.read()); //get wifi data
}
}
String cutString(String s){
//Serial.println(s.length());
char target[]="X";
int num=s.lastIndexOf(target);
if(num!=-1){
return s.substring(num-3,num);
}
else{
return "0";
}
}
最后给出测试代码
#include "wifi.h"
void setup()
{
Serial.begin();
setWifi();
delay();
}
void loop(){
wifiSend("Q");
String s2=wifiGet();
Serial.println(s2);
}