安卓+ Arduino的蓝牙数据传输 [英] Android + Arduino Bluetooth Data Transfer

查看:449
本文介绍了安卓+ Arduino的蓝牙数据传输的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以让我的Andr​​oid应用程序,通过蓝牙连接到我的Arduino。然而没有数据可以在它们之间进行传输。下面是我的设置和code:

I can get my Android app to connect via Bluetooth to my Arduino. However no data can be transmitted between them. Below is my setup and code:

HTC的Andr​​oid V2.2,蓝牙队友金调制解调器,Arduino的兆丰(ATmega1280)

HTC Android v2.2, Bluetooth mate gold modem, Arduino Mega (ATmega1280)

Android的Java的code:

Android Java code:

package com.example.BluetoothExample;

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.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;  
import android.widget.Button;
import android.widget.Toast;

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

public class BluetoothExampleActivity extends Activity {
  TextView myLabel;
  EditText myTextbox;
  BluetoothAdapter mBluetoothAdapter;
  BluetoothSocket mmSocket;
  BluetoothDevice mmDevice;
  OutputStream mmOutputStream;
  InputStream mmInputStream;
  Thread workerThread;
  byte[] readBuffer;
  int readBufferPosition;
  int counter;
  volatile boolean stopWorker;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button openButton = (Button)findViewById(R.id.open);
    Button sendButton = (Button)findViewById(R.id.send);
    Button closeButton = (Button)findViewById(R.id.close);
    myLabel = (TextView)findViewById(R.id.label);
    myTextbox = (EditText)findViewById(R.id.entry);

    //Open Button
    openButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        try {
          findBT();
          openBT();
        }
        catch (IOException ex) { }
      }
    });

    //Send Button
    sendButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        try {
          sendData();
        }
        catch (IOException ex) {
            showMessage("SEND FAILED");
        }
      }
    });

    //Close button
    closeButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        try {
          closeBT();
        }
        catch (IOException ex) { }
      }
    });
  }

  void findBT() {
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if(mBluetoothAdapter == null) {
      myLabel.setText("No bluetooth adapter available");
    }

    if(!mBluetoothAdapter.isEnabled()) {
      Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(enableBluetooth, 0);
    }

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    if(pairedDevices.size() > 0) {
      for(BluetoothDevice device : pairedDevices) {
        if(device.getName().equals("FireFly-108B")) {
          mmDevice = device;
          break;
        }
      }
    }
    myLabel.setText("Bluetooth Device Found");
  }

  void openBT() throws IOException {
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard //SerialPortService ID
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);    
    mmSocket.connect();
    mmOutputStream = mmSocket.getOutputStream();
    mmInputStream = mmSocket.getInputStream();
    beginListenForData();
    myLabel.setText("Bluetooth Opened");
  }

  void beginListenForData() {
    final Handler handler = new Handler(); 
    final byte delimiter = 10; //This is the ASCII code for a newline character

    stopWorker = false;
    readBufferPosition = 0;
    readBuffer = new byte[1024];
    workerThread = new Thread(new Runnable() {
      public void run() {
         while(!Thread.currentThread().isInterrupted() && !stopWorker) {
          try {
            int bytesAvailable = mmInputStream.available();            
            if(bytesAvailable > 0) {
              byte[] packetBytes = new byte[bytesAvailable];
              mmInputStream.read(packetBytes);
              for(int i=0;i<bytesAvailable;i++) {
                byte b = packetBytes[i];
                if(b == delimiter) {
                  byte[] encodedBytes = new byte[readBufferPosition];
                  System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                  final String data = new String(encodedBytes, "US-ASCII");
                  readBufferPosition = 0;

                  handler.post(new Runnable() {
                    public void run() {
                      myLabel.setText(data);
                    }
                  });
                }
                else {
                  readBuffer[readBufferPosition++] = b;
                }
              }
            }
          } 
          catch (IOException ex) {
            stopWorker = true;
          }
         }
      }
    });

    workerThread.start();
  }

  void sendData() throws IOException {
    String msg = myTextbox.getText().toString();
    msg += "\n";
    //mmOutputStream.write(msg.getBytes());
    mmOutputStream.write('A');
    myLabel.setText("Data Sent");
  }

  void closeBT() throws IOException {
    stopWorker = true;
    mmOutputStream.close();
    mmInputStream.close();
    mmSocket.close();
    myLabel.setText("Bluetooth Closed");
  }

  private void showMessage(String theMsg) {
        Toast msg = Toast.makeText(getBaseContext(),
                theMsg, (Toast.LENGTH_LONG)/160);
        msg.show();
    }
}


Arduino的code:


Arduino Code:

#include <SoftwareSerial.h>

int bluetoothTx = 45;
int bluetoothRx = 47;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup() {
  //pinMode(45, OUTPUT);
  //pinMode(47, INPUT);
  pinMode(53, OUTPUT);
  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(115200);
  bluetooth.print("$$$");
  delay(100);
  bluetooth.println("U,9600,N");
  bluetooth.begin(9600);
}

void loop() {
  //Read from bluetooth and write to usb serial
  if(bluetooth.available()) {
  char toSend = (char)bluetooth.read();
  Serial.print(toSend);
  flashLED();
  }

  //Read from usb serial to bluetooth
  if(Serial.available()) {
  char toSend = (char)Serial.read();
  bluetooth.print(toSend);
  flashLED();
  }
}

void flashLED() {
  digitalWrite(53, HIGH);
  delay(500);
  digitalWrite(53, LOW);
}

我用115200和9600波特率试过,我已经尝试设置蓝牙RX和TX引脚作为输入/输出和输入/输出。在Arduino是接收来自PC的串行数据,但不能将其发送到Android(我可以看到,因为flashLED()方法,这一点)。

I've tried using 115200 and 9600 for the baud rates, and I've tried setting the bluetooth rx and tx pins as input/output and output/input. The Arduino is receiving serial data from the PC but can't send it to the Android (I can see this because of the flashLED() method).

而Android不能在所有到Arduino发送任何数据。不过,他们都连接,因为绿灯调制解调器开启和熄灭,红灯闪烁,当我关闭连接。的发送数据()方法不抛出一个异常,因为否则showMessage(发送失败);将会出现。

The Android can't send any data at all to the Arduino. However they are both connected because the green light on the modem turns on and goes off and the red led flashes when I close the connection. The sendData() method doesn't throw an exception because otherwise showMessage("SEND FAILED"); would appear.

我也是在我的清单中的.xml有这样

I also have this in my manifest .xml

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" />

任何帮助将是很大的AP preciated!

Any help would be greatly appreciated!

$ C $摘自C:

<一个href="http://bell$c$c.word$p$pss.com/2012/01/02/android-and-arduino-bluetooth-communication/">http://bell$c$c.word$p$pss.com/2012/01/02/android-and-arduino-bluetooth-communication/

推荐答案

只是解决了谁碰到这个页面别人的问题。

Just solved the problem for anyone else who came across this page.

看来我的Arduino不使用数字引脚串行通信我喜欢,我用的TX和RX与而不是从<一个采取这一code href="http://jondontdoit.blogspot.com.au/2011/11/bluetooth-mate-tutorial.html">http://jondontdoit.blogspot.com.au/2011/11/bluetooth-mate-tutorial.html,也似乎9600是一个很好的波特率,而不是115200。

Seems that my Arduino doesn't like me using digital pins for serial communication, I use TX and RX instead with this code taken from http://jondontdoit.blogspot.com.au/2011/11/bluetooth-mate-tutorial.html, also seems that 9600 is a good baud instead of 115200.

/***********************
 Bluetooth test program
***********************/
//TODO
//TEST THIS PROGRAM WITH ANDROID,
//CHANGE PINS TO RX AND TX THO ON THE ARDUINO!
//int counter = 0;
int incomingByte;

void setup() {
  pinMode(53, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // see if there's incoming serial data:
  if (Serial.available() > 0) {
    // read the oldest byte in the serial buffer:
    incomingByte = Serial.read();
    // if it's a capital R, reset the counter
    if (incomingByte == 'g') {
      digitalWrite(53, HIGH);
      delay(500);
      digitalWrite(53, LOW);
      delay(500);
      //Serial.println("RESET");
      //counter=0;
    }
  }

  //Serial.println(counter);
  //counter++;

  //delay(250);
}

这篇关于安卓+ Arduino的蓝牙数据传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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