通过WiFi将Android传输到Arduino,两种方式均不会发送数据

时间:2019-04-30 10:21:24

标签: android arduino android-wifi

我是Android开发的新手,所以我可能会遗漏一些明显的东西。我一直在进行WiFi开发并一直遇到相同的问题,即使我的Android设备愉快地连接到互联网,也无法检测到其对等组。 (为了公平起见,它确实发现了隔壁的打印机)

在这种特定情况下,我试图从启用WiFi的Arduino发送/接收字符串,但是没有运气。我没有看到来自Android设备的数据(通过Arduino IDE的串行监视器),反之亦然,我没有看到通过我的应用程序上的TextView显示的来自Arduino的数据。

Arduino可以毫无问题地连接到WiFi,并立即显示其IP地址,然后可以将其输入到Android应用中。 Android设备知道本地WiFi,因为我可以毫无问题地上网。

在Android方面:

MainActivity.java

package qdivision.org.android_2_arduino_wifi;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    Button offLED, onLED, connect;
    EditText ipServer;
    TextView state;
    TextView arduinoMsg;
    boolean socketStatus = false;
    Socket socket;
    MyClientTask myClientTask;
    String address;
    int port = 80;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        offLED = (Button)findViewById(R.id.off_led);
        offLED.setEnabled(false);
        onLED = (Button)findViewById(R.id.on_led);
        onLED.setEnabled(false);
        connect = (Button)findViewById(R.id.connect);
        ipServer = (EditText)findViewById(R.id.ip_server);
        state = (TextView)findViewById(R.id.state);
        arduinoMsg = (TextView)findViewById(R.id.arduino_msg);

        connect.setOnClickListener(connectOnClickListener);
        offLED.setOnClickListener(OnOffLedClickListener);
        onLED.setOnClickListener(OnOffLedClickListener);

    }

    OnClickListener connectOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if(socketStatus)
                Toast.makeText(MainActivity.this,"Already talking to a Socket!! Disconnect and try again!", Toast.LENGTH_LONG).show();
            else {
                socket = null;
                address = ipServer.getText().toString();
                if (address == null)
                    Toast.makeText(MainActivity.this, "Please enter valid address", Toast.LENGTH_LONG).show();
                else {
                    myClientTask = new MyClientTask(address);
                    ipServer.setEnabled(false);
                    connect.setEnabled(false);
                    myClientTask.execute("onLED");
                    offLED.setEnabled(true);
                    state.setText("IP ");
                }
            }
        }
    };

    OnClickListener OnOffLedClickListener = new OnClickListener(){
        @Override
        public void onClick(View v) {
            String onoff = "";
            if(v== offLED){
                onoff="offLED";
                offLED.setEnabled(false);
                onLED.setEnabled(true);
            }else if (v== onLED){
                onoff="onLED";
                onLED.setEnabled(false);
                offLED.setEnabled(true);
            }
            MyClientTask taskEsp = new MyClientTask(address);
            taskEsp.execute(onoff);

        }
    };


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

        String server;

        MyClientTask(String server){
            this.server = server;
        }

        @Override
        protected String doInBackground(String... params) {

            StringBuffer chain = new StringBuffer("");

            final String val = params[0];
            final String p = "http://" + server + "/" + val;

            runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    state.setText(p);
                }
            });

            String serverResponse = "";
            try {
                URL url = new URL(p);
                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
                InputStream inputStream = connection.getInputStream();

                BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
                String line = "";
                while ((line = rd.readLine()) != null) {
                    chain.append(line);
                }
                inputStream.close();
                arduinoMsg.setText(chain.toString());
                System.out.println("chain: " + chain.toString());

                connection.disconnect();

            } catch (IOException e) {
                e.printStackTrace();
                serverResponse = e.getMessage();
            }

            return serverResponse;
        }

        @Override
        protected void onPostExecute(String s) {

        }
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="false"
    android:layout_centerInParent="false"
    android:layout_centerVertical="false"
    android:orientation="vertical"
    tools:context="udea.edu.co.blink_wemos.MainActivity"
    android:gravity="center">

    <EditText
        android:id="@+id/ip_server"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="IP"
        android:text="192.168.1.66"/>

    <Button
        android:id="@+id/connect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="52dp"
        android:text="CONNECT" />

    <TextView
        android:id="@+id/state"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ACTION"
        android:textSize="30sp" />

    <Button
        android:id="@+id/off_led"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OFF" />

    <Button
        android:id="@+id/on_led"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ON " />

    <TextView
        android:id="@+id/arduino_msg"
        android:layout_width="284dp"
        android:layout_height="108dp"
        android:text="@string/arduino_msg_title" />

</LinearLayout>

权限已添加到AndroidManifest.xml

<uses-permission 
    android:name="android.permission.INTERNET" />
<uses-permission 
    android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission
    android:required="true"
    android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission
    android:required="true"
    android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission
    android:required="true"
    android:name="android.permission.CHANGE_WIFI_STATE"/>

在Arduino方面:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

const char* ssid = "SKYNET";
const char* password = "asifidbesostupid";

ESP8266WebServer server(80);

void offLED(){
  String message = "Off LED";
  server.send(200, "text/plain", message);
  digitalWrite(BUILTIN_LED, LOW);  // turn on LED with voltage HIGH
  Serial.print("off\n");
}

void onLED(){
  String message = {"On LED"};
  server.send(200, "text/plain", message);
  digitalWrite(BUILTIN_LED, HIGH);  // turn on LED with voltage HIGH
  Serial.print("on\n");
}

void connection(){
  String message = {"On LED"};
  server.send(200, "text/plain", message);
  digitalWrite(BUILTIN_LED, HIGH);  // turn on LED with voltage HIGH
}

void setup(void){  
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  pinMode(BUILTIN_LED, OUTPUT); // Onboard LED
  server.on("/offLED", offLED);
  server.on("/onLED", onLED);
  server.on("/", connection);

  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

编辑#1:根据以下注释,从logcat面板中收集以下异常

  

05-01 11:09:57.827 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:java.net.ConnectException:无法连接到   /192.168.1.84(端口80):连接失败:EHOSTUNREACH(无路由   主持人)05-01 11:09:57.829   7174-7578 / qdivision.org.android_2_arduino_wifi W / System.err:在   libcore.io.IoBridge.connect(IoBridge.java:124)05-01 11:09:57.830   7174-7578 / qdivision.org.android_2_arduino_wifi W / System.err:在   java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)05-01   11:09:57.830 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)05-01   11:09:57.831 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于java.net.Socket.connect(Socket.java:884)05-01   11:09:57.832 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:160)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:67)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   com.android.okhttp.Connection.connect(Connection.java:152)05-01   11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   com.android.okhttp.OkHttpClient $ 1.connectAndSetOwner(OkHttpClient.java:128)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:342)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:331)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:249)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   qdivision.org.android_2_arduino_wifi.MainActivity $ MyClientTask.doInBackground(MainActivity.java:123)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   qdivision.org.android_2_arduino_wifi.MainActivity $ MyClientTask.doInBackground(MainActivity.java:95)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:在android.os.AsyncTask $ 2.call(AsyncTask.java:295)   05-01 11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   java.util.concurrent.FutureTask.run(FutureTask.java:237)05-01   11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:234)05-01   11:09:57.833 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)   05-01 11:09:57.834 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:588)   05-01 11:09:57.834 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:at java.lang.Thread.run(Thread.java:818)05-01   11:09:57.834 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:由:android.system.ErrnoException:连接   失败:EHOSTUNREACH(无路由到主机)05-01 11:09:57.834   7174-7578 / qdivision.org.android_2_arduino_wifi W / System.err:在   libcore.io.Posix.connect(本机方法)05-01 11:09:57.834   7174-7578 / qdivision.org.android_2_arduino_wifi W / System.err:在   libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)05-01   11:09:57.834 7174-7578 / qdivision.org.android_2_arduino_wifi   W / System.err:位于   libcore.io.IoBridge.connectErrno(IoBridge.java:137)05-01 11:09:57.834   7174-7578 / qdivision.org.android_2_arduino_wifi W / System.err:在   libcore.io.IoBridge.connect(IoBridge.java:122)05-01 11:09:57.834   7174-7578 / qdivision.org.android_2_arduino_wifi W / System.err:... 22   更多

编辑#2:我已经在Android设备上安装了Termux并在发送的250个软件包中ping了Arduino丢失0%的软件包。因此,Android可以通过网络到达Arduino,但由于某些原因,该应用无法实现。

编辑#3 我毕竟无法ping通Arduino(事实证明我是ping Raspberry Pi)。但在进一步的开发中,我可以从Raspberry Pi和PC上ping Android设备。作为回报,我可以对Raspberry Pi进行ping操作,但不能对来自Android设备的PC进行ping操作。

0 个答案:

没有答案