Arduino和android之间通过以太网盾进行通信

时间:2017-01-06 18:53:55

标签: android arduino-uno

我使用Android通过Arduino和以太网屏蔽来切换我的LED灯。尽管在Android和Arduino的编译过程中都没有遇到任何问题,但它仍无法正常工作。我将以太网屏蔽与我的计算机连接起来,并给了它与我的电脑相同的地址。

这是我的Android代码:

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.ToggleButton;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    /********************************/
     /*    Define all the buttons    */
    /********************************/
    Switch led1 = (Switch) findViewById(R.id.Led1);
    /*******************************************************/
     /*  Set an onclick/onchange listener for every button  */
    /*******************************************************/
    led1.setOnCheckedChangeListener(new        CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                /* Switch is led 1 */
                new Background_get().execute("led1=1");
            } else {
                new Background_get().execute("led1=0");
            }
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/*****************************************************/
/*  This is a background process for connecting      */
/*   to the arduino server and sending               */
/*    the GET request withe the added data           */
/*****************************************************/

private class Background_get extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        try {
            /* Change the IP to the IP you set in the arduino sketch */
            URL url = new URL("http://169, 254, 128, 184/?" + params[0]);
            HttpURLConnection connection = (HttpURLConnection)     url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder result = new StringBuilder();
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                result.append(inputLine).append("\n");
            in.close();
            connection.disconnect();
            return result.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
}

这是Arduino代码:

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(169, 254, 128, 184);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  // Pin 5
  pinMode(5, OUTPUT);
}

void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    String buffer = "";
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        buffer += c;
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          // the connection will be closed after completion of the response
          client.println("Refresh: 5");
          // refresh the page automatically every 5 sec
          client.println();
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
          buffer = "";
        } else if (c != '\r') {
          if (buffer.indexOf("GET /?led1=1") >= 0) { // If led1 = 1
            digitalWrite(5, HIGH); // led 1 > on
          }
          if (buffer.indexOf("GET /?led1=0") >= 0) { // If led1 = 0
            digitalWrite(5, LOW); // led 1 > off
          }
        } else {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

1 个答案:

答案 0 :(得分:0)

编制您的Arduino:

#include "etherShield.h"
#include "ETHER_28J60.h"

int led2 = 7;
int led1 = 6;

static uint8_t mac[6] = {0xAA, 0xBB, 0xCC, 0xDD, 0xBB, 0xAA}; // this just needs to be unique for your network,
                                                              // so unless you have more than one of these boards
                                                              // connected, you should be fine with this value.

static uint8_t ip[4] = {192, 168, 0, 15};                     // the IP address for your board. Check your home hub
                                                              // to find an IP address not in use and pick that
                                                              // this or 10.0.0.15 are likely formats for an address
                                                              // that will work. 

static uint16_t port = 80;                                    // Use port 80 - the standard for HTTP

ETHER_28J60 e;

void setup(){

    e.setup(mac, ip, port);

    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);

    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
}

void loop(){
    char* params;
    if (params = e.serviceRequest()){
        if (strcmp(params, "?cmd=1") == 0){digitalWrite(led1, HIGH);}
        if (strcmp(params, "?cmd=2") == 0){digitalWrite(led1, LOW); }
        if (strcmp(params, "?cmd=3") == 0){digitalWrite(led2, HIGH);}
        if (strcmp(params, "?cmd=4") == 0){digitalWrite(led2, LOW); }

        e.respond();
    }
}

编制您的APP

为您的清单添加权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<强> MainActivity.java

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        StrictMode.ThreadPolicy policy = new StrictMode.
        ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        View led1on = findViewById(R.id.led_1on);
        View led1off = findViewById(R.id.led_1off);
        View led2on = findViewById(R.id.led_2on);
        View led2off = findViewById(R.id.led_2off);

        led1on.setOnClickListener(this);
        led1off.setOnClickListener(this);
        led2on.setOnClickListener(this);
        led2off.setOnClickListener(this);
    }

    public void commandArduino(String url){
        try {
            HttpClient httpclient = new DefaultHttpClient();
            httpclient.execute(new HttpGet(url));      
        } catch (Exception e) {}
    }

    public void onClick(View thisView) {
        switch(thisView.getId()){
            case R.id.led_1on:  commandArduino("http://192.168.0.15/?cmd=1"); break;
            case R.id.led_1off: commandArduino("http://192.168.0.15/?cmd=2"); break;
            case R.id.led_2on:  commandArduino("http://192.168.0.15/?cmd=3"); break;
            case R.id.led_2off: commandArduino("http://192.168.0.15/?cmd=4"); break;
        }
    }
}

<强>参考:

http://www.instructables.com/id/Arduino-Android-LED-control-Using-Ethernet-Shield/