为什么我的arduino uno与xbee shield v1.4与蓝牙蜜蜂没有收到来自android的任何数据?

时间:2013-01-28 02:41:02

标签: java android bluetooth arduino

我为android开发了这个应用程序,它通过蓝牙将1和0发送到蓝牙蜂作为其连接的固定设备。它假设控制连接到UNO的外部LED。但是当我在上传arduino程序后将arduino插入电源时,当我按下Android应用程序时,LED没有发生任何变化。我想知道我是否没有正确编程微控制器。请帮忙! ><这是我的应用程序代码和arduino的草图。 :

Arduino Sketch

#include <SoftwareSerial.h>

SoftwareSerial mySerial(6, 5);
int dataFromBT;

void setup() {
  Serial.begin(57600);
  Serial.println("LEDOnOff Starting...");

  // The data rate for the SoftwareSerial port needs to 
  // match the data rate for your bluetooth board.
  mySerial.begin(115200);
  pinMode(13, OUTPUT);   
}

void loop() {
  if (mySerial.available())
    dataFromBT = mySerial.read();

  if (dataFromBT == '0') {
    // Turn off LED
    digitalWrite(13, LOW);
  } else if (dataFromBT == '1') {
    // Turn on LEFD
    digitalWrite(13, HIGH);
  }
}

Java代码:

package com.example.twobuttonapp;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

     private static String TAG = "TwoButtonApp";//for use as the tag when logging 

     private static final int REQUEST_ENABLE_BT = 1;
      private BluetoothAdapter btAdapter = null;
      private BluetoothSocket btSocket = null;
      private OutputStream outStream = null;

      // Well known SPP UUID
      private static final UUID MY_UUID =
          UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

      // Insert your bluetooth devices MAC address
      private static String address = "07:12:04:18:51:58";

    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);

         Log.d(TAG, "In onCreate()");

        setContentView(R.layout.activity_main);

        Button buttonStart = (Button)findViewById(R.id.buttonStart);        
         buttonStart.setOnClickListener(new OnClickListener() {
              public void onClick(View v) {
                sendData("1");
                Toast msg = Toast.makeText(getBaseContext(),
                    "You have clicked On", Toast.LENGTH_SHORT);
                msg.show();
              }
            });

         Button buttonStop = (Button)findViewById(R.id.buttonStop);        
         buttonStop.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                  sendData("0");
                  Toast msg = Toast.makeText(getBaseContext(),
                      "You have clicked Off", Toast.LENGTH_SHORT);
                  msg.show();
                }
              });
         btAdapter = BluetoothAdapter.getDefaultAdapter();
            checkBTState();
    }

     @Override
      public void onResume() {
        super.onResume();

        Log.d(TAG, "...In onResume - Attempting client connect...");

        // Set up a pointer to the remote node using it's address.
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        // Two things are needed to make a connection:
        //   A MAC address, which we got above.
        //   A Service ID or UUID.  In this case we are using the
        //     UUID for SPP.
        try {
          btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
          errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }

        // Discovery is resource intensive.  Make sure it isn't going on
        // when you attempt to connect and pass your message.
        btAdapter.cancelDiscovery();

        // Establish the connection.  This will block until it connects.
        Log.d(TAG, "...Connecting to Remote...");
        try {
          btSocket.connect();
          Log.d(TAG, "...Connection established and data link opened...");
        } catch (IOException e) {
          try {
            btSocket.close();
          } catch (IOException e2) {
            errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
          }
        }

        // Create a data stream so we can talk to server.
        Log.d(TAG, "...Creating Socket...");

        try {
          outStream = btSocket.getOutputStream();
        } catch (IOException e) {
          errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
        }
      }

      @Override
      public void onPause() {
        super.onPause();

        Log.d(TAG, "...In onPause()...");

        if (outStream != null) {
          try {
            outStream.flush();
          } catch (IOException e) {
            errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
          }
        }

        try     {
          btSocket.close();
        } catch (IOException e2) {
          errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
        }
      }

      private void checkBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on

        // Emulator doesn't support Bluetooth and will return null
        if(btAdapter==null) { 
          errorExit("Fatal Error", "Bluetooth Not supported. Aborting.");
        } else {
          if (btAdapter.isEnabled()) {
            Log.d(TAG, "...Bluetooth is enabled...");
          } else {
            //Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
          }
        }
      }

      private void errorExit(String title, String message){
        Toast msg = Toast.makeText(getBaseContext(),
            title + " - " + message, Toast.LENGTH_SHORT);
        msg.show();
        finish();
      }

      private void sendData(String message) {
        byte[] msgBuffer = message.getBytes();

        Log.d(TAG, "...Sending data: " + message + "...");

        try {
          outStream.write(msgBuffer);
        } catch (IOException e) {
          String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
          if (address.equals("00:00:00:00:00:00")) 
            msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
          msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

          errorExit("Fatal Error", msg);       
        }
      }


    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_main, menu);
        return true;
    }

    @SuppressWarnings("null")
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.about:
            Toast aboutAlert = null;
            // Show info about the author (that's me!)
         aboutAlert.show();
            return true;
        }
        return false;
        //respond to menu item selection
    }
};

非常感谢!

1 个答案:

答案 0 :(得分:0)

只看arduino代码:

  • read()函数返回char,而不是int
  • 我认为默认的Zigbee速度是9600
  • 跳过available(),只需从read()设置字符并使用它。 read()函数正在阻塞,只会等待下一个字节发生。