首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android + Arduino蓝牙数据传输

Android + Arduino蓝牙数据传输
EN

Stack Overflow用户
提问于 2012-04-26 13:02:47
回答 6查看 81.1K关注 0票数 23

我可以让我的Android应用程序通过蓝牙连接到我的Arduino。但是,它们之间不能传输数据。下面是我的设置和代码:

HTC Android v2.2,蓝牙配对金牌调制解调器,Arduino Mega (ATmega1280)

Android 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正在接收来自PC的串行数据,但无法将其发送到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/

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10327506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档