安卓+Arduino蓝牙数据传输

23

我可以让我的安卓应用程序通过蓝牙连接到我的Arduino。但是它们之间无法传输数据。以下是我的设置和代码:

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

安卓Java代码:

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 代码:
#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可以从电脑接收串行数据,但无法将其发送到Android(通过flashLED()方法可以看到这一点)。

Android无法向Arduino发送任何数据。但是它们都连接成功,因为调制解调器上的绿色灯亮起并在关闭连接时闪烁红色LED。sendData()方法不会抛出异常,否则就会出现showMessage("SEND FAILED");。

我还在我的清单.xml中添加了以下内容。

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

非常感谢任何帮助!

代码来源:

http://bellcode.wordpress.com/2012/01/02/android-and-arduino-bluetooth-communication/


你的代码运行良好,请查看以下步骤:首先,您向外部设备发送连接请求,一旦信号被接受,它将发送回接受信号和连接成功,但我们无法定期获取传入数据。这意味着在成功连接后的一段时间后。所以你能告诉我如何从另一个外部设备定期获取传入数据吗?提前致谢... - Ricky Khatri
嗨,你好。我有一个Arduino设备,它会发送Modbus RTU数据给我。我该如何通过蓝牙读取这些数据?我已经完成了蓝牙配对。但是当我写“mmInputStream.available()”时,它返回给我值为'0'。请尽快帮助我。先行致谢。 - Dhruv
7个回答

14

我已经解决了这个问题,希望能帮到其他遇到同样问题的人。

似乎我的Arduino不喜欢我用数字引脚进行串行通信,我改为使用TX和RX引脚,并使用此代码,同时9600波特率比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);
}

5

我也遇到了同样的问题。我进入“设置”->“无线和网络”->“蓝牙设置”,将设备配对后,重新运行我的代码,连接成功,没有异常。我在UI中添加控件以显示已配对设备,我将尝试编写代码来管理从我的UI中配对设备。


1

对于任何发现此页面的人,但被困在使用硬编码的MAC地址上的情况,请将MAC地址设置为NULL,并将此代码插入到OnResume()中。

try{
File f = new File(Environment.getExternalStorageDirectory()+"/mac.txt");
FileInputStream fileIS = new FileInputStream(f);
buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String(); 
while((readString = buf.readLine())!= null){
address = readString;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}

此外,不要忘记允许Eclipse包含必要的库,并将您的MAC地址放入SD卡根目录下的mac.txt文件中,然后您可以简单地给用户一个带有他们MAC地址的文本文件,同时仍然允许应用程序从市场下载而无需定制每个实例。

1
如果你还在寻找答案,尝试更改软件串口引脚。这是你正在使用的库的众所周知的限制。
由于 Mega 上并非所有引脚都支持更改中断,因此只能使用以下引脚进行 RX:10、11、12、13、14、15、50、51、52、53、A8(62)、A9(63)、A10(64)、A11(65)、A12(66)、A13(67)、A14(68)、A15(69)。参考资料 希望这可以帮到你。

1

只有在替换了这一部分后,我才能使其运行。

Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
    {
        for(BluetoothDevice device : pairedDevices)
        {
            if(device.getName().startsWith("FireFly-"))
            {
                mmDevice = device;
                Log.d("ArduinoBT", "findBT found device named " + mmDevice.getName());
                Log.d("ArduinoBT", "device address is " + mmDevice.getAddress());
                break;
            }
        }
    }

使用这个:

 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
 mmDevice = mBluetoothAdapter.getRemoteDevice("00:06:66:46:5A:91");
 if (pairedDevices.contains(mmDevice))
    {
        statusText.setText("Bluetooth Device Found, address: " + mmDevice.getAddress() );
        Log.d("ArduinoBT", "BT is paired");
    }

我在输入我的蓝牙设备地址时遇到了问题。 原始代码可以找到设备并返回正确的地址,但是mmSocket.connect();会生成一个异常"java.io.IOException: Service discovery failed"

有什么建议吗?


1

@Backwards_Dave,只是出于好奇,试着连接45和46引脚,并使用这个简单的代码。我自己用过没有问题。你将能够从Arduino串行监视器发送数据并在那里读取它。

/*
Pinout:
45 --> BT module Tx
46 --> BT module Rx
*/
#include <SoftwareSerial.h>

SoftwareSerial mySerial(45, 46); // RX, TX

void setup()  
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);


  Serial.println("I am ready to send some stuff!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

此外,您在使用Arduino时使用的蓝牙模块是什么?HC-06吗?
编辑:刚刚用Mega2560进行了测试(没有1280),并且没有任何问题。
我相信问题出在引脚配置上。
等待您的反馈。

0

我认为这可能是蓝牙方面的问题...最好重新安装其驱动程序...因为上面给出的代码看起来是正确的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接