2012-04-26 132 views
18

我可以讓我的Android應用程序通過藍牙連接到我的Arduino。然而,它們之間不能傳輸數據。下面是我的設置和代碼:Android + Arduino藍牙數據傳輸

HTC的Android V2.2,藍牙伴侶黃金調制解調器,Arduino的兆(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發送任何數據。但是它們都連接在一起,因爲調制解調器上的綠燈亮起和熄滅,並且當我關閉連接時紅燈閃爍。 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/

+0

你的代碼工作正常看看的步驟:首先你發送一個連接請求到外部設備一旦信號被接受它將發回接受信號和連接成功,但我們無法週期性地獲取傳入的數據。連接成功的一段時間。那麼你能告訴我如何從其他外部設備定期獲取數據。在此先感謝... – 2012-12-03 08:45:03

+0

嗨Hi.I有Arduino設備,它向我發送Modbus RTU數據。如何通過藍牙讀取數據?我完成了藍牙配對。但是當我寫「mmInputStream.available()」時,它會返回'0'值。請儘可能幫助我。提前致謝。 – Lawrance 2013-08-30 10:45:37

回答

11

就解決了別人誰碰到這個頁面來了這個問題。

看來,我用數字引腳串行通信Arduino的我不喜歡,我用TX和RX用,而不是從http://jondontdoit.blogspot.com.au/2011/11/bluetooth-mate-tutorial.html採取了這種代碼,也似乎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); 
} 
-1

我認爲這可能是藍牙的一些故障..它更好地重新安裝其驅動程序..因爲上面給出的代碼看起來是正確的。

0

我能夠得到這個只運行替換本節之後:

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:服務發現失敗」

建議?

+0

不確定是否對不起:( – 2012-05-20 07:30:06

3

我得到了同樣的東西。我進入了「設置」 - >「無線和網絡」 - >「藍牙設置」並配對設備。當我回去重新運行我的代碼時,它連接了,沒有例外。我在我的用戶界面中放置了用於顯示配對設備的控件,我將查看是否可以通過我的用戶界面來管理配對設備。

0

對於任何人誰發現這個頁面,但使用上述硬編碼的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地址的文本文件,同時仍然允許從市場下載應用程序而無需自定義每個實例。

0

@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

如果您仍然在尋找答案,請嘗試更改軟件串行引腳。這是您正在使用的庫的一個衆所周知的限制。

並非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)。 Refs

希望這會有所幫助。