如何在android中从esp 8266获取数据后重新连接

时间:2016-08-23 07:53:58

标签: android arduino esp8266

你好,我从esp8266发送数据后卡住了 我将esp8266与我的arduino连接

这是我的arduino代码

#include <SoftwareSerial.h>
//#include <OneWire.h>
//#include <DallasTemperature.h>
//#include <stdlib.h>
//#include "Wire.h"
//#define DS3231_I2C_ADDRESS 0x68
//#define ONE_WIRE_BUS 5
//WIFI
#include <SPI.h>
#include <WiFi.h>
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
//OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
//DallasTemperature sensors(&oneWire);

int wifiTx = 4;
int wifiRx = 3;
#define DEBUG true
char com;
String data;

SoftwareSerial wifi(wifiTx, wifiRx);

//wifi
char ssid[] = "waifu";     //  your network SSID (name)
char pass[] = "chronoangel";  // your network password
//int status = WL_IDLE_STATUS;     // the Wifi radio's status


void setup() {
  // put your setup code here, to run once:
  Wire.begin();
  Serial.begin(9600);
  wifi.begin(115200);
  sensors.begin();
  //sekon, menit,jam, day of week, hari, bulan taun
  //setDS3231time(0,15,2,1,13,7,16);
  //\start_wifi();
  esp();
}

void loop() {
 test_wifi();
 //loop_esp();

}

void esp()
{
    sendCommand("AT\r\n",2000,DEBUG); 
    sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
    sendCommand("AT+CWMODE=1\r\n",1000,DEBUG); // configure as access point
    sendCommand("AT+CWJAP=\"waifu\",\"chronoangel\"\r\n",3000,DEBUG);
    delay(10000);
    //Serial.println("\nCek IP");
    //sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
    sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
    Serial.println("\nGet PORT"); 
    sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
    Serial.println("\nSet IP");
    sendCommand("AT+CIPSTA=\"192.168.1.7\"\r\n",1000,DEBUG); // set ip address
    sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
    Serial.println("\nServer Ready"); 
}
void test_wifi()
{  
  if(wifi.available())
  {
    char toSend = (char)wifi.read();
    Serial.print(toSend);
  }

  //Read from usb serial to wifi
  if(Serial.available())
  {
    char toSend = (char)Serial.read();
    wifi.print(toSend);
  }
}

这是我的android工作室代码

package com.example.chronoangel.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView textResponse;
    EditText editTextAddress, editTextPort;
    Button buttonConnect, buttonClear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextAddress = (EditText) findViewById(R.id.IP);
        editTextPort = (EditText) findViewById(R.id.Port);
        buttonConnect = (Button) findViewById(R.id.connect);
        //buttonClear = (Button)findViewById(R.id.clear);
        textResponse = (TextView) findViewById(R.id.textData);
        buttonConnect.setOnClickListener(buttonConnectOnClickListener);

    }

            OnClickListener buttonConnectOnClickListener = new OnClickListener(){

                    @Override
                    public void onClick(View arg0) {
                        MyClientTask myClientTask = new MyClientTask(editTextAddress.getText().toString(), Integer.parseInt(editTextPort.getText().toString()));
                        myClientTask.execute();
                    }};


        //class to get data from esp8266
        public class MyClientTask extends AsyncTask<Void, Void, Void> {

            String dstAddress;
            int dstPort;
            String response = "";

            MyClientTask(String addr, int port) {
                dstAddress = addr;
                dstPort = port;
            }

            @Override
            protected Void doInBackground(Void... arg0) {

                Socket socket = null;

                try {
                    socket = new Socket(dstAddress, dstPort);

                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    InputStream inputStream = socket.getInputStream();

    /*
     * notice:
     * inputStream.read() will block if no data return
     */
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        byteArrayOutputStream.write(buffer, 0, bytesRead);
                        response += byteArrayOutputStream.toString("UTF-8");

                    }

                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    response = "UnknownHostException: " + e.toString();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    response = "IOException: " + e.toString();
                } finally {
                    if (socket != null) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                textResponse.setText(response);
                super.onPostExecute(result);

            }

        }



}

这是我对我的计划的看法: enter image description here 我的问题与此页面类似:

http://stackoverflow.com/questions/34274774/esp8266-wifi-server-to-android-client

但我认为在那里没有线索如何在发送数据后重新连接

程序在我点击Android app上的连接后运行

发送AT + COMMAND后,在我的串口arduino中

AT+CIPSEND = 0,2
然后我发送数据&#34; ab&#34;到我的机器人

数据未发送,但如果ii发送AT + COMMAND

AT+CIPCLOSE=0

数据已发送,但我必须再次点击连接以从esp

获取数据

我的问题是我们可以在点击连接后获得连续数据吗? 在arduino发送消息后,我怎么想让android再次连接呢?

1 个答案:

答案 0 :(得分:0)

这更像是一个建议而不是一个答案,因为我认为除了每次关闭连接之外别无他法。

但我强烈建议您将自己的软件用于ESP8266而不是使用AT命令。它们很适合一开始,连接到网络等等。但他们是有限的。由于您已经使用了arduino allready,我建议使用IDE为您的ESP编写一些代码。 你可以在这里找到很多代码和帮助。 https://create.arduino.cc/projecthub/Metavix/programming-the-esp8266-with-the-arduino-ide-in-3-simple-601c16

ESP8266WiFi.h提供了许多可以使用的功能。