Android向arduino发送和接收数据

时间:2016-01-06 19:59:39

标签: android url android-asynctask arduino

我正在尝试从arduino发送和接收数据到我的Android手机。问题是我只收到arduino到手机的数据,但是我无法将数据发送到arduino来打开执行器。

下面是arduino sketch的代码

#include "DHT.h"
#include <SPI.h>
#include <Ethernet.h>
#include <SoftwareSerial.h>

#define DHTPIN 2
#define DHTTYPE DHT11

EthernetServer server(80);
DHT dht(DHTPIN, DHTTYPE);

String rawData;

byte mac[] = {0x90, 0xA2, 0xDA, 0x09, 0x00, 0x0C};
byte ip[] = {192, 168, 1, 177}; 

void setup(){
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  server.begin();
  dht.begin();
  pinMode(6,OUTPUT);
}

void loop(){
  float h = dht.readHumidity();
  float t = dht.readTemperature();

if(isnan(t) || isnan(h)){return;}
  rawData=String(t)+String(",")+String(h);

 EthernetClient client = server.available();

  if (client) {
    boolean currentLineIsBlank = true;

  String buffer = ""; //adding

    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        buffer += c;
        //Serial.write(c);
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  
          client.println("Refresh: 1"); 
          client.println(); 
          client.println(rawData);
          break;
        }


        if (c == '\n') { // if New line
          currentLineIsBlank = true;
          buffer = "";  // Clear buffer
        } else if (c == '\r') { // If cariage return...
          //Read in the buffer if there was send "GET /?..."

 if(buffer.indexOf("GET /?led2=1")>=0) { // If led2 = 1
            digitalWrite(5, HIGH); // led 2 > on
          }
          if(buffer.indexOf("GET /?led2=0")>=0) { // If led2 = 0
            digitalWrite(5, LOW); // led 2 > off
          }
        } else {

          currentLineIsBlank = false;
        }



      }
    }
    delay(1);
    client.stop();
    Ethernet.maintain();
  }  
}

这是我的Android代码 MainActivity

public class MainActivity extends Activity {

    Switch led;
    private TextView data;
    Sensors sensor;
    Button buttonConnect;

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

        buttonConnect=(Button)findViewById(R.id.button1);

        data=(TextView)findViewById(R.id.textView2);

        new Sensors().execute("http://192.168.1.177/");

        led =(Switch)findViewById(R.id.switch1);
        led.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              if (isChecked) {
                  new Sensors().execute("http://192.168.1.177/?led2=0");
              } else {
                  new Sensors().execute("http://192.168.1.177/?led2=1");
              }
          }
      });


class Sensors extends AsyncTask<String, byte[], String>{

        InputStream nis;
        OutputStream nos;
        BufferedReader in;
        DefaultHttpClient httpclient =new DefaultHttpClient();
        URL url;
        URLConnection urlconn=null;
        InputStreamReader isn;

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

            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response;
            try {
                while(true){                    
                    response = httpclient.execute(new HttpGet(params[0]));              
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    response.getEntity().writeTo(out);
                    byte[] theByteArray = out.toByteArray();
                    publishProgress(theByteArray); 
                }

 } catch (ClientProtocolException e) {
                //TODO Handle problems..
            } catch (IOException e) {
                //TODO Handle problems..
            }
            return null ;
        }

protected void onProgressUpdate(byte[]... values) {
                String command=new String(values[0]);//get the String from the recieved bytes
                data.setText(command);
            }

    }

布局文件

<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.arduinoandroidasyntasktesting4.MainActivity" >

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Led" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sensor Data"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Data"
        android:textAppearance="?android:attr/textAppearanceLarge" />

  </LinearLayout>

我的logcat没有出错,当我在浏览器中测试网址时,它正在工作,我可以打开和关闭LED。我认为问题出在android代码中。

您可以查看这些代码中的问题以及我如何解决它。

0 个答案:

没有答案