2015-11-02 29 views
3

什麼是目前與Java應用程序連接到HC-05藍牙模塊(Arduino)的最佳實踐? Bluecove還是別的? 如果是這樣,是否有任何你可以推薦使用HC-05連接的Bluecove的例子?最佳實踐 - Java串行藍牙連接HC-05

+0

是你能夠在這個問題上過呢?我也對此感興趣。請告訴我們您是否取得了進展。 Thx – chris

+0

我想我曾經用[jSerialComm](http://fazecast.github.io/jSerialComm/)庫連接到藍牙設備,因爲那些藍牙設備也將被列爲串行設備。這是直接和容易做到的。唯一可能成爲問題的是,您可能需要一些適用於Windows的驅動程序。 – redxef

回答

3

前段時間我有同樣的問題。在此期間,我找到了一種通過java與HC-05通信的方式。我正在使用blueCove - 也許還有其他庫,但這對我很有用。這裏是我做的:

import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.bluetooth.DeviceClass; 
import javax.bluetooth.DiscoveryAgent; 
import javax.bluetooth.DiscoveryListener; 
import javax.bluetooth.LocalDevice; 
import javax.bluetooth.RemoteDevice; 
import javax.bluetooth.ServiceRecord; 
import javax.bluetooth.UUID; 
import javax.microedition.io.Connector; 
import javax.microedition.io.StreamConnection; 

public class HC05 { 

    boolean scanFinished = false; 
    RemoteDevice hc05device; 
    String hc05Url; 

    public static void main(String[] args) { 
     try { 
      new HC05().go(); 
     } catch (Exception ex) { 
      Logger.getLogger(HC05.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

    private void go() throws Exception { 
     //scan for all devices: 
     scanFinished = false; 
     LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, new DiscoveryListener() { 
      @Override 
      public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) { 
       try { 
        String name = btDevice.getFriendlyName(false); 
        System.out.format("%s (%s)\n", name, btDevice.getBluetoothAddress()); 
        if (name.matches("HC.*")) { 
         hc05device = btDevice; 
         System.out.println("got it!"); 
        } 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 

      @Override 
      public void inquiryCompleted(int discType) { 
       scanFinished = true; 
      } 

      @Override 
      public void serviceSearchCompleted(int transID, int respCode) { 
      } 

      @Override 
      public void servicesDiscovered(int transID, ServiceRecord[] servRecord) { 
      } 
     }); 
     while (!scanFinished) { 
      //this is easier to understand (for me) as the thread stuff examples from bluecove 
      Thread.sleep(500); 
     } 

     //search for services: 
     UUID uuid = new UUID(0x1101); //scan for btspp://... services (as HC-05 offers it) 
     UUID[] searchUuidSet = new UUID[]{uuid}; 
     int[] attrIDs = new int[]{ 
      0x0100 // service name 
     }; 
     scanFinished = false; 
     LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, searchUuidSet, 
       hc05device, new DiscoveryListener() { 
        @Override 
        public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) { 
        } 

        @Override 
        public void inquiryCompleted(int discType) { 
        } 

        @Override 
        public void serviceSearchCompleted(int transID, int respCode) { 
         scanFinished = true; 
        } 

        @Override 
        public void servicesDiscovered(int transID, ServiceRecord[] servRecord) { 
         for (int i = 0; i < servRecord.length; i++) { 
          hc05Url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false); 
          if (hc05Url != null) { 
           break; //take the first one 
          } 
         } 
        } 
       }); 

     while (!scanFinished) { 
      Thread.sleep(500); 
     } 

     System.out.println(hc05device.getBluetoothAddress()); 
     System.out.println(hc05Url); 

     //if you know your hc05Url this is all you need: 
     StreamConnection streamConnection = (StreamConnection) Connector.open(hc05Url); 
     OutputStream os = streamConnection.openOutputStream(); 
     InputStream is = streamConnection.openInputStream(); 

     os.write("1".getBytes()); //just send '1' to the device 
     os.close(); 
     is.close(); 
     streamConnection.close(); 
    } 
} 

在我的環境有一些可用的其他設備,但我過濾以HC的結果*。這是從NetBeans中的控制檯輸出:

run: 
BlueCove version 2.1.0 on winsock 
HC-05 (98D331FD157C) 
got it! 
Nintendo RVL-blabla(00000000FFFF) 
GT-N7100 (00000000EEEE) 
98D399999999 
btspp://98D399999999:1;authenticate=false;encrypt=false;master=false 
BlueCove stack shutdown completed 
BUILD SUCCESSFUL (total time: 14 seconds) 

一旦你知道你的HC-05的URL(btspp:// ...),你能不掃描所有設備,而無需搜索服務連接。這要快得多,代碼縮減到幾行。

這裏是我的Arduino的代碼做一些與數據:就當發送「1」,關閉,如果發送「0」切換板LED(引腳13):

/* 
* Bluetooth-Modul anschliessen: +5, GND, 
* Tx an Arduino Rx(Pin 0) 
* Rx an Arduino Tx(Pin 1) 
* 
* Per Handy mit App 'ArduDroid by Techbitar': 
* -Menü 'Connect me to a Bluetooth device 
* -Send Data "A" oder "B" schaltet die LED auf Pin 13 aus bzw. an 
* und gibt Rückmeldung 'LED:on' oder 'LEF:off'. 
* 
* https://www.youtube.com/watch?v=sXs7S048eIo 
* 
* Alternativ mit JavaCode: projekt 'MrBlue' 
*/ 

int ledPin = 13; 
int cmd = -1; 
int flag = 0; 

void setup() { 
    pinMode(ledPin, OUTPUT); 
    digitalWrite(ledPin, LOW); 
    Serial.begin(9600); 
} 

void loop() { 
    if (Serial.available() > 0) { 
    cmd = Serial.read(); 
    flag = 1; 
    } 

    if (flag == 1) { 
    if (cmd == '0') { 
     digitalWrite(ledPin, LOW); 
     Serial.println("LED: off"); 
    } else if (cmd == '1') { 
     digitalWrite(ledPin, HIGH); 
     Serial.println("LED: on"); 
    } else { 
     Serial.print("unknown command: "); 
     Serial.write(cmd); 
     Serial.print(" ("); 
     Serial.print(cmd, DEC); 
     Serial.print(")"); 

     Serial.println(); 
    } 

    flag = 0;  
    cmd = 65; 
    } 

    Serial.flush(); 
    delay(100); 
} 

這裏是看中我和我的HC-05之間的協議: enter image description here

我Arduino的烏諾和HC-05之間的連接: enter image description here

+0

我在Win7上得到了「輸入代碼」窗口......我不知道該插入什麼,因爲HC-05實際上並沒有產生任何代碼(並且我可以看看它)??? –

+0

I閱讀「嘗試使用代碼1234或0000」。 1234是我的設備上的默認設置。 – chris