ESP8266到ANDROID通讯

时间:2019-02-12 20:18:03

标签: android arduino esp8266 nodemcu arduino-esp8266

这实际上是我第一次在这里问一个问题,真的希望有人可以解决我的问题。

我一直在从事我的设计项目,其功能之一是它可以从ESP8266 NodeMCU到Android进行通信,而无需将NodeMCU连接到网络。因此,就像Android直接连接到Wifi模块一样,将NodeMCU设置为访问点和WebServer。

我已经建立了一个简单的通信,但是我希望它保持恒定且同步,因为我正在使用此连接来显示从NodeMCU到Android的传感器读数。我的问题是,它不会一直给出值,只会给出第一个数据,然后什么也不给出。

这是我在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的代码:

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()方法中尝试了此代码。

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中显示。

我尝试了几种技巧,但仍然没有运气。

非常感谢您的回复,谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试--Really simple TCP client 我已经按照本手册进行了android服务器的安装,一切正常