Arduino 和 android 之间通过以太网屏蔽通信 [英] Communication between Arduino and android via ethernet shield

查看:50
本文介绍了Arduino 和 android 之间通过以太网屏蔽通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Android 通过 Arduino 和以太网屏蔽来切换我的 LED 灯.尽管在 Android 和 Arduino 上编译期间都没有问题,但它没有工作.我将以太网屏蔽连接到我的电脑,并给它提供了与我的电脑相同的地址.

I'm using Android to toggle my led light with Arduino and ethernet shield. It didn't work despite having no problems during compilation neither on Android nor Arduino. I connected the ethernet shield with my computer and I gave it the same address as my computer.

这是我的安卓代码:

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 代码:

And this is the Arduino code:

#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");
  }
}

推荐答案

对 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();
    }
}


编写您的应用程序

向清单添加权限

<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/

这篇关于Arduino 和 android 之间通过以太网屏蔽通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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