arduino 与java通信_ardunio+esp8266与javaSocket网络通信(好)

该博客介绍了如何使用Arduino通过ESP8266模块连接WiFi,并与JavaWeb服务器建立TCP连接,实现双向的Socket通信。内容包括Arduino发送AT指令配置ESP8266,发送JSON数据到服务器,以及Java端的接收和处理数据的代码示例。
摘要由CSDN通过智能技术生成

ardunio+esp8266与javaSocket网络通信

功能

通过ardunio向esp8266模块发送at指令,连接上wifi,然后向服务器发送tcp连接请求,之后是与服务器进行sockt通信,实现通过web服务器,更改设备的led开关。

实物连接

连接方式

esp8266连接,ardunio使用软串口RX=2,TX=3,

RX—–ardunio的TX

TX—–ardunio的RX

IO15–GND

CHP_EK—3.3V

RST—-3.3V

IO0—3.3V

IO2 —3.3V

硬件代码

#include

#include

SoftwareSerial mySerial(2, 3); // RX, TX

//发送的数据

String json=”";

//发送数据长度

int sendlength;

void setup() {

// Open serial communications and wait for port to open:

Serial.begin(9600);

while (!Serial) {

}

Serial.println(“Goodnight moon!”);

mySerial.begin(115200);

delay(2000);

mySerial.print(“AT+RST\r\n”);

delay(8000);

clearCash();

Serial.println(“rst finish”);

mySerial.print(“AT+CWMODE=3\r\n”);

delay(5000);

clearCash();

Serial.println(“mode finish”);

mySerial.print(“AT+CWJAP=\”wifiname\”,\”wifipassword\”\r\n”);

delay(8000);

clearCash();

Serial.println(“CWJAP finish”);

mySerial.print(“AT+CIPSTART=\”TCP\”,\”192.168.1.144 \”,8888\r\n” );

delay(8000);

clearCash();

json =”{\”id\”:1,\”name\”:\”szh\”}”;

delay(300);

String text1 =”AT+CIPSEND=”;

sendlength =json.length()+2;

text1.concat(String(sendlength));

Serial.println(text1);

delay(300);

mySerial.println(text1);

delay(1000);

clearCash();

Serial.print(“Send String:”);

Serial.println(json);

mySerial.println(json);

delay(1000);

clearCash();

Serial.println(“setup end”);

}

void loop() { // run over and over

String inString=”";

boolean start =false;

mySerial.listen();

while(mySerial.available()){

char inChar = (char)mySerial.read();

Serial.write(inChar);

if(start){

if(inChar == ‘}’){

start =false;

Serial.println(“start false”);

}

if(start){

inString +=(char)inChar;

}

Serial.println(inString);

}

if(inChar == ‘{‘){

start =true;

Serial.println(“start true”);

delay(10);

}

delay(10);

}

if(inString != “”){

Serial.print(“InputString:”);

Serial.println(inString);

if(inString == “off”){

digitalWrite(7, LOW);

json =”{\”state\”:\”off\”}”;

delay(300);

sendResult();

}else if(inString == “on”){

digitalWrite(7, HIGH);

json =”{\”state\”:\”on\”}”;

delay(300);

sendResult();

}else{

json =”{\”state\”:\”error\”}”;

delay(300);

sendResult();

}

inString=”";

}

}

//清空缓存

void clearCash(){

while(mySerial.available()){

mySerial.read();

}

}

//发送结果数据

void sendResult(){

String text1 =”AT+CIPSEND=”;

sendlength =json.length()+2;

text1.concat(String(sendlength));

mySerial.println(text1);

delay(1000);

clearCash();

mySerial.println(json);

delay(1000);

clearCash();

}

注:每一次发送软串口会返回结果,所以需要将这些信息读取掉。通过at指令,会不太稳定,延迟时间可以长一点。与java的通信协议为json数据,往java发数据,可以完整读取,但java发往设备会出现乱码,所以可以将数据长度简单或者重发。

javaWeb代码

web.xml

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd”

version=”3.1″>

send

com.test.example.SendServlet

send

/send.jsp

com.test.example.SocketListener

服务器启动运行代码

public class SocketListener implements ServletContextListener{

@Override

public void contextInitialized(ServletContextEvent servletContextEvent) {

new Thread(new Runnable() {

@Override

public void run() {

new SocketServer();

}

}).start();

}

@Override

public void contextDestroyed(ServletContextEvent servletContextEvent) {

}

}

public class SocketServer {

/**端口号*/

private static final int port = 8888;

/** 线程池*/

private ExecutorService mExecutorService;

/**ServerSocket对象*/

private ServerSocket mServerSocket;

/**存储socket*/

public static Map socketMap =new HashMap<>();

private String ip;

public SocketServer() {

try {

System.out.println(“socket启动”);

//设置socket端口

mServerSocket = new ServerSocket(port);

//创建线程池

mExecutorService = Executors.newCachedThreadPool();

// 用来临时保存客户端连接的Socket对象

Socket client = null;

while(true){

client = mServerSocket.accept();

ip = client.getInetAddress().getHostAddress();

System.out.println(“ip=”+ip);

socketMap.put(“1″,client);

System.out.println(client+”——”);

mExecutorService.execute(convertData);

}

} catch (IOException e) {

e.printStackTrace();

}

}

/**处理数据*/

public Runnable convertData = new Runnable(){

@Override

public void run() {

System.out.println(“convertData”);

int result;

try {

Socket client = socketMap.get(“1″);

while (true) {

InputStream inputStream = client.getInputStream();

OutputStream outputStream =client.getOutputStream();

while(inputStream.available()>0) {

byte[] data = new byte[inputStream.available()];

inputStream.read(data);

String resultData = new String(data);

resultData = replaceBlank(resultData);

System.out.println(“resultData=” + resultData);

}

}

} catch (IOException e) {

e.printStackTrace();

}

}

};

/***

*去除空格,水平制表符,换行,回车

* @param str

* @return

*/

public static String replaceBlank(String str) {

String dest = “”;

if (str!=null) {

Pattern p = Pattern.compile(“\\s*|\t|\r|\n”);

Matcher m = p.matcher(str);

dest = m.replaceAll(“”);

}

return dest;

}

}

发送信息代码

public class SendServlet extends HttpServlet{

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doGet(req, resp);

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

Socket client = SocketServer.socketMap.get(“1″);

System.out.println(“client=”+client);

String send =”{off}”;

OutputStream out = client.getOutputStream();

out.write(send.getBytes());

out.flush();

System.out.println(“send finish”);

}

}

———————

作者:poorSir

来源:CSDN

原文:https://blog.csdn.net/qq_31433525/article/details/79123197

版权声明:本文为博主原创文章,转载请附上博文链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值