ESP8266 到 ANDROID 通讯 [英] ESP8266 to ANDROID Communication

查看:41
本文介绍了ESP8266 到 ANDROID 通讯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次在这里提问,真的希望有人能解决我的问题.

it's actually my first time asking a question here, and really hoping someone could give solution to my problem.

我一直致力于我的设计项目,其中一项功能是它可以从 ESP8266 NodeMCU 与 Android 通信,而无需 NodeMCU 连接到网络.所以这就像Android直接连接到Wifi模块,将NodeMCU设置为接入点和WebServer.

I've been working on my Design Project, and one of the feature is that it could communicate from ESP8266 NodeMCU to Android, without the NodeMCU connecting to a network. So it's like the Android connecting directly to the Wifi Module, setting up the NodeMCU as both Access Point and WebServer.

我已经建立了一个简单的通信,但我希望它是持续和同时的,因为我使用这个连接来显示从 NodeMCU 到 Android 的传感器读数.我的问题是,它不会不断给出值,它只会给出第一个数据,然后什么都不给出.

I've established a simple communication, but I want it constant and simultaneous, since i'm using this connection to display the reading of the sensor from the NodeMCU to Android. My problem here is that, it won't constantly give the values, it would only give the first data and then nothing.

这是我在 Android 中的代码:

Here's my Code in Android:

首先是客户端类

public class Client extends AsyncTask<Void, Void, String> {

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

Socket socket = null;

Client(String addr, int port, TextView textResponse) {
    dstAddress = addr;
    dstPort = port;
    this.textResponse = textResponse;
}

@Override
protected String doInBackground(Void... arg0) {
Log.d("Status_2", "Sample_2");
    try {
        if(socket == null)
        {
            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();
            }
        }
    }*/
    //textResponse.setText(response);
    return response;
}

@Override
protected void onPostExecute(String result)
{
    Log.d("Status_1", "sample");
    textResponse.setText(response);
    super.onPostExecute(result);
}

}

这是主要活动

public class MainActivity extends Activity {

TextView response;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear, buttonStop;
int check = 0;
public static Client myClient;


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


    editTextAddress =  findViewById(R.id.addressEditText);
    editTextPort =  findViewById(R.id.portEditText);
    buttonConnect =  findViewById(R.id.connectButton);
    buttonClear =  findViewById(R.id.clearButton);
    buttonStop = findViewById(R.id.buttonStop);
    response =  findViewById(R.id.responseTextView);

    myClient = new Client(editTextAddress.getText()
            .toString(), Integer.parseInt(editTextPort
            .getText().toString()), response);

    buttonStop.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            check = 0;
        }
    });

    buttonConnect.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View arg0)
        {
            check = 1;
                myClient.execute();


        }
    });

    buttonClear.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            response.setText("");
        }
    });
}

}

这是来自 Arduino 的代码:

And here is the code from the Arduino:

int status = WL_IDLE_STATUS;
boolean alreadyConnected = false; // whether or not the client was connected 
previously

WiFiServer server(8080);

void setup() 
{

   delay(1000);
   Serial.begin(115200);
   Serial.println();
  // MotionSensor_Setup();
   Serial.print("Configuring access point...");
   /* You can remove the password parameter if you want the AP to be open. */
   WiFi.softAP(ssid,password);
   delay(10000);
   IPAddress myIP = WiFi.softAPIP();
   Serial.print("AP IP address: ");
   Serial.println(myIP);

   Serial.println("\nStarting server...");
  // start the server:
  server.begin();

}




void loop() 
{
 // wait for a new client:
  WiFiClient client = server.available();
  // when the client sends the first byte, say hello:
    if(client)
    {
     if (!alreadyConnected) 
{
  // clead out the input buffer:
  client.flush();
  Serial.println(analogRead(A0));
  Serial.println();
  client.println("Hello, client!");
  client.println(analogRead(A0));
  delay(500);
  alreadyConnected = true;
   }
    }




if (client.available() > 0) {
  // read the bytes incoming from the client:
  char thisChar = client.read();
  // echo the bytes back to the client:
  server.write(thisChar);
  // echo the bytes to the server as well:
  Serial.write(thisChar);
}

}

最终我在 void loop() 方法中尝试了这段代码.

Eventually I've tried this code here in the void loop() method.

void loop() 
{
 // wait for a new client:
  WiFiClient client = server.available();
  // when the client sends the first byte, say hello:
    while(client.connected())
    {
     client.println(analogRead(A0));
     delay(1000);
     Serial.println(analogRead(A0));
   }
    }

它进入 while 条件并在串行监视器中显示数据,但未在 Android 中显示.

it got inside the while condition and displayed data in the Serial Monitor, but didn't displayed in the Android.

我尝试了几种技术,但仍然没有运气.

I've tried several techniques and still no luck.

非常感谢你们的回复,谢谢!

I would really appreciate your reply guys, Thank you!

推荐答案

你可以试试这个 -> 真的简单的 TCP 客户端我已经根据本手册制作了我的 android 服务器,一切正常

you can try this -> Really simple TCP client I have doing my android server according this manual and all is work OK

这篇关于ESP8266 到 ANDROID 通讯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆