Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/185.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Can';t连接到蓝牙设备(从手机到HC-05)_Android_Bluetooth_Arduino_Processing - Fatal编程技术网

Android Can';t连接到蓝牙设备(从手机到HC-05)

Android Can';t连接到蓝牙设备(从手机到HC-05),android,bluetooth,arduino,processing,Android,Bluetooth,Arduino,Processing,我从这个网站下载了代码草图6:发送接收字节:我可以看到“设备发现:(设备名称)并在我的屏幕上找到。但我无法连接到设备(我尝试从Galaxy s4连接到HC05蓝牙模块)。(我从未见过紫色屏幕。我刚刚看到绿色,我想问题是在“foundDevice=true;“请检查一下。这是我最后一年的项目,没有它我什么都做不了:( `/*SendReceiveBytes:ScottC于2013年3月25日使用 正在处理版本2.0b8 在三星Galaxy SII上测试,Android版本为2.3.4 androi

我从这个网站下载了代码草图6:发送接收字节:我可以看到“设备发现:(设备名称)并在我的屏幕上找到。但我无法连接到设备(我尝试从Galaxy s4连接到HC05蓝牙模块)。(我从未见过紫色屏幕。我刚刚看到绿色,我想问题是在“foundDevice=true;“请检查一下。这是我最后一年的项目,没有它我什么都做不了:(

`/*SendReceiveBytes:ScottC于2013年3月25日使用 正在处理版本2.0b8 在三星Galaxy SII上测试,Android版本为2.3.4 androidadk-api10sdk平台*/

导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.widget.Toast;
导入android.view.Gravity;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入java.util.UUID;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入android.os.Handler;
导入android.os.Message;
导入android.util.Log;
导入android.bluetooth.BluetoothServerSocket;
导入android.bluetooth.BluetoothSocket;
公共蓝牙插座;
boolean foundDevice=false;//为true时,屏幕变为绿色。
布尔值bDisconnected=false;//为true时,屏幕变为紫色。
字符串serverName=“ArduinoBasicsServer”;
//处理程序使用的消息类型
公共静态最终int消息_WRITE=1;
公共静态最终int消息_READ=2;
字符串readMessage=“”;
//获取默认的蓝牙适配器
BluetoothAdapter bluetooth=BluetoothAdapter.getDefaultAdapter();
/*setup()中的startActivityForResult()启动
用于请求用户打开蓝牙的活动。
执行此操作时,将调用以下onActivityResult()方法
活动退出*/
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
if(requestCode==0){
if(resultCode==RESULT\u OK){
ToastMaster(“蓝牙已打开”);
} 
否则{
主持人(“你需要打开蓝牙!!!”;
}
}
}
/*创建一个BroadcastReceiver,稍后用于
接收范围内蓝牙设备的名称*/
BroadcastReceiver MyDiscoveryr=新的myOwnBroadcastReceiver();
/*创建一个BroadcastReceiver,稍后用于
确定蓝牙设备是否已连接*/
BroadcastReceiver checkIsConnected=新建myOwnBroadcastReceiver();
//从套接字获取信息的处理程序
私有最终处理程序mHandler=新处理程序(){
@凌驾
公共无效handleMessage(消息消息消息){
开关(msg.what){
案例信息\u写入:
//写东西的时候做点什么
打破
案例信息如下:
//从msg.obj获取字节
字节[]readBuf=(字节[])msg.obj;
//从缓冲区中的有效字节构造字符串
readMessage=新字符串(readBuf,0,msg.arg1);
打破
}
}
};
无效设置(){
方向(景观);
/*如果未启用蓝牙,请询问用户权限以启用它*/
如果(!bluetooth.isEnabled()){
意向请求Bluetooth=新意向(BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(请求蓝牙,0);
}
/*如果蓝牙现在已启用,则注册广播接收器以报告任何
查找到蓝牙设备,然后开始查找*/
如果(bluetooth.isEnabled()){
registerReceiver(MyDiscoveryr、new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(检查已连接,新的意向过滤器(BluetoothDevice.ACTION\u ACL\u CONNECTED));
//如果蓝牙发现尚未启动,则启动蓝牙发现
如果(!bluetooth.isDiscovery()){
bluetooth.startDiscovery();
}
}
}
作废提款(){
//如果找到设备,则显示绿色屏幕,
//连接到设备时显示紫色屏幕
如果(设备){
如果(b断开连接){
背景(170,50,255);//紫色屏幕
}
否则{
背景(1025510);//绿色屏幕
}
}
//显示从Arduino收到的任何信息
文本(readMessage,10,10);
}
/*此广播接收器将显示发现的蓝牙设备*/
公共类myOwnBroadcastReceiver扩展了BroadcastReceiver{
连接到蓝牙连接;
@凌驾
公共void onReceive(上下文、意图){
String action=intent.getAction();
演讲会主持人(“行动:+行动);
//找到Bluetooth设备的通知
if(BluetoothDevice.ACTION_FOUND.equals(ACTION)){
//显示发现的设备的名称
String discoveredDeviceName=intent.getStringExtra(BluetoothDevice.EXTRA\u名称);
演讲会主持人(“发现:+发现设备名称);
//显示有关查找到的设备的详细信息
BluetoothDevice DiscoveryDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA\u设备);
ToastMaster(“getAddress()=”+discoveredDevice.getAddress());
ToastMaster(“getName()=”+discoveredDevice.getName());
int-bondyState=discoveredDevice.getBondState();
演讲会主持人(“getBondState()=”+bondyState);
字符串mybondState;
开关(bondyState){
案例10:
mybondState=“BOND\u NONE”;
打破
案例11:
mybondState=“BOND\u BONDING”;
打破
案例12:
mybondState=“BOND\u BOND”;
打破
违约:
mybondState=“无效的债券状态”;
打破
}
演讲会主持人(“getBondState()=”+mybondState);
//将foundDevice更改为true,这将使屏幕变为绿色
foundDevice=true;
//连接到发现的蓝牙设备(请参阅edbtslave)
if(discoveredDeviceName.equals(“seeedbtsave”)){
ToastMaster(“立即连接您!!”;
未注册接收人(MyDiscoveryer);
connectBT=新的ConnectToBluetooth(发现的设备);
//以新线程连接到设备
新线程(connectBT.start();
}
}
//蓝牙设备是否已连接的通知
if(BluetoothDevice.ACTION\u ACL\u CONNECTED.equals(ACTION)){
演讲会主持人(“已连接”);
while(scSocket==null){
//无所事事
}
演讲会主持人(“scSocket”+scSocket);
bDisconnected=true;//将屏幕变成紫色
如果
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.util.UUID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
public BluetoothSocket scSocket;


boolean foundDevice=false; //When true, the screen turns green.
boolean BTisConnected=false; //When true, the screen turns purple.
String serverName = "ArduinoBasicsServer";

// Message types used by the Handler
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_READ = 2;
String readMessage="";

//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

/*The startActivityForResult() within setup() launches an 
 Activity which is used to request the user to turn Bluetooth on. 
 The following onActivityResult() method is called when this 
 Activity exits. */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 if (requestCode==0) {
 if (resultCode == RESULT_OK) {
 ToastMaster("Bluetooth has been switched ON");
 } 
 else {
 ToastMaster("You need to turn Bluetooth ON !!!");
 }
 }
}


/* Create a BroadcastReceiver that will later be used to 
 receive the names of Bluetooth devices in range. */
BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();


/* Create a BroadcastReceiver that will later be used to
 identify if the Bluetooth device is connected */
BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();


// The Handler that gets information back from the Socket
private final Handler mHandler = new Handler() {
 @Override
 public void handleMessage(Message msg) {
 switch (msg.what) {
 case MESSAGE_WRITE:
 //Do something when writing
 break;
 case MESSAGE_READ:
 //Get the bytes from the msg.obj
 byte[] readBuf = (byte[]) msg.obj;
 // construct a string from the valid bytes in the buffer
 readMessage = new String(readBuf, 0, msg.arg1);
 break;
 }
 }
};


void setup() {
 orientation(LANDSCAPE);
 /*IF Bluetooth is NOT enabled, then ask user permission to enable it */
 if (!bluetooth.isEnabled()) {
 Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
 startActivityForResult(requestBluetooth, 0);
 }


 /*If Bluetooth is now enabled, then register a broadcastReceiver to report any
 discovered Bluetooth devices, and then start discovering */
 if (bluetooth.isEnabled()) {
 registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
 registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

 //Start bluetooth discovery if it is not doing so already
 if (!bluetooth.isDiscovering()) {
 bluetooth.startDiscovery();
 }
 }
}


void draw() {
 //Display a green screen if a device has been found,
 //Display a purple screen when a connection is made to the device
 if (foundDevice) {
 if (BTisConnected) {
 background(170, 50, 255); // purple screen
 }
 else {
 background(10, 255, 10); // green screen
 }
 }

 //Display anything received from Arduino
 text(readMessage, 10, 10);
}


/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
 ConnectToBluetooth connectBT;

 @Override
 public void onReceive(Context context, Intent intent) {
 String action=intent.getAction();
 ToastMaster("ACTION:" + action);

 //Notification that BluetoothDevice is FOUND
 if (BluetoothDevice.ACTION_FOUND.equals(action)) {
 //Display the name of the discovered device
 String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
 ToastMaster("Discovered: " + discoveredDeviceName);

 //Display more information about the discovered device
 BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
 ToastMaster("getAddress() = " + discoveredDevice.getAddress());
 ToastMaster("getName() = " + discoveredDevice.getName());

 int bondyState=discoveredDevice.getBondState();
 ToastMaster("getBondState() = " + bondyState);

 String mybondState;
 switch(bondyState) {
 case 10: 
 mybondState="BOND_NONE";
 break;
 case 11: 
 mybondState="BOND_BONDING";
 break;
 case 12: 
 mybondState="BOND_BONDED";
 break;
 default: 
 mybondState="INVALID BOND STATE";
 break;
 }
 ToastMaster("getBondState() = " + mybondState);

 //Change foundDevice to true which will make the screen turn green
 foundDevice=true;

 //Connect to the discovered bluetooth device (SeeedBTSlave)
 if (discoveredDeviceName.equals("SeeedBTSlave")) {
 ToastMaster("Connecting you Now !!");
 unregisterReceiver(myDiscoverer);
 connectBT = new ConnectToBluetooth(discoveredDevice);
 //Connect to the the device in a new thread
 new Thread(connectBT).start();
 }
 }

 //Notification if bluetooth device is connected
 if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
 ToastMaster("CONNECTED _ YAY");

 while (scSocket==null) {
 //do nothing
 }
 ToastMaster("scSocket" + scSocket);
 BTisConnected=true; //turn screen purple 
 if (scSocket!=null) {
 SendReceiveBytes sendReceiveBT = new SendReceiveBytes(scSocket);
 new Thread(sendReceiveBT).start();
 String red = "r";
 byte[] myByte = stringToBytesUTFCustom(red);
 sendReceiveBT.write(myByte);
 }
 }
 }
}
public static byte[] stringToBytesUTFCustom(String str) {
 char[] buffer = str.toCharArray();
 byte[] b = new byte[buffer.length << 1];
 for (int i = 0; i < buffer.length; i++) {
 int bpos = i << 1;
 b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
 b[bpos + 1] = (byte) (buffer[i]&0x00FF);
 }
 return b;
}

public class ConnectToBluetooth implements Runnable {
 private BluetoothDevice btShield;
 private BluetoothSocket mySocket = null;
 private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

 public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
 btShield = bluetoothShield;
 try {
 mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
 }
 catch(IOException createSocketException) {
 //Problem with creating a socket
 Log.e("ConnectToBluetooth", "Error with Socket");
 }
 }

 @Override
 public void run() {
 /* Cancel discovery on Bluetooth Adapter to prevent slow connection */
 bluetooth.cancelDiscovery();

 try {
 /*Connect to the bluetoothShield through the Socket. This will block
 until it succeeds or throws an IOException */
 mySocket.connect();
 scSocket=mySocket;
 } 
 catch (IOException connectException) {
 Log.e("ConnectToBluetooth", "Error with Socket Connection");
 try {
 mySocket.close(); //try to close the socket
 }
 catch(IOException closeException) {
 }
 return;
 }
 }

 /* Will cancel an in-progress connection, and close the socket */
 public void cancel() {
 try {
 mySocket.close();
 } 
 catch (IOException e) {
 }
 }
}


private class SendReceiveBytes implements Runnable {
 private BluetoothSocket btSocket;
 private InputStream btInputStream = null;
 private OutputStream btOutputStream = null;
 String TAG = "SendReceiveBytes";

 public SendReceiveBytes(BluetoothSocket socket) {
 btSocket = socket;
 try {
 btInputStream = btSocket.getInputStream();
 btOutputStream = btSocket.getOutputStream();
 } 
 catch (IOException streamError) { 
 Log.e(TAG, "Error when getting input or output Stream");
 }
 }


 public void run() {
 byte[] buffer = new byte[1024]; // buffer store for the stream
 int bytes; // bytes returned from read()

 // Keep listening to the InputStream until an exception occurs
 while (true) {
 try {
 // Read from the InputStream
 bytes = btInputStream.read(buffer);
 // Send the obtained bytes to the UI activity
 mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
 .sendToTarget();
 } 
 catch (IOException e) {
 Log.e(TAG, "Error reading from btInputStream");
 break;
 }
 }
 }


 /* Call this from the main activity to send data to the remote device */
 public void write(byte[] bytes) {
 try {
 btOutputStream.write(bytes);
 } 
 catch (IOException e) { 
 Log.e(TAG, "Error when writing to btOutputStream");
 }
 }


 /* Call this from the main activity to shutdown the connection */
 public void cancel() {
 try {
 btSocket.close();
 } 
 catch (IOException e) { 
 Log.e(TAG, "Error when closing the btSocket");
 }
 }
}


/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay) {
 Toast myMessage = Toast.makeText(getApplicationContext(), 
 textToDisplay, 
 Toast.LENGTH_SHORT);
 myMessage.setGravity(Gravity.CENTER, 0, 0);
 myMessage.show();
}`
#include <SoftwareSerial.h>

//#define uint8 unsigned char 
//#define uint16 unsigned int
//#define uint32 unsigned long int

#define RxD 6 // This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
#define TxD 7 // This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)

#define DEBUG_ENABLED 1
Servo myservo ;

int led = 9 ;

SoftwareSerial blueToothSerial(RxD, TxD);


/*----------------------SETUP----------------------------*/
void setup() { 
myservo.attach(10);
myservo.write(0);

Serial.begin(9600);//low Serial communication via USB cable to computer (if required)
pinMode(RxD, INPUT); // Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6
pinMode(TxD, OUTPUT); // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
pinMode(13, OUTPUT); // Use onboard LED if required.
pinMode(9,OUTPUT);
setupBlueToothConnection(); //Used to initialise the Bluetooth shield


} 


/*----------------------LOOP----------------------------*/
void loop() { 
digitalWrite(13, LOW); //Turn off the onboard Arduino LED
char recvChar;
while (1) {
if (blueToothSerial.available()) {//check if there's any data sent from the remote bluetooth shield
recvChar = blueToothSerial.read();
Serial.print(recvChar); // Print the character received to the Serial Monitor (if required)

//If the character received = 'r' , then change the RGB led to display a RED colour
if (recvChar=='r') {
  myservo.write(100);
// Send32Zero(); // begin
// DataDealWithAndSend(255, 0, 0); // first node data
// Send32Zero(); // send to update data
digitalWrite(led,HIGH);
delay(500);

}

//If the character received = 'g' , then change the RGB led to display a GREEN colour
if (recvChar=='g') {
  digitalWrite(led,LOW);
  myservo.write(50);


}

//If the character received = 'b' , then change the RGB led to display a BLUE colour
if (recvChar=='b') {
// Send32Zero(); // begin
// DataDealWithAndSend(0, 0, 255); // first node data
// Send32Zero(); // send to update data
digitalWrite(led,HIGH);
myservo.write(180);
}

//If the character received = 'x' , then turn RGB led OFF
if (recvChar=='x') {
// Send32Zero(); // begin
// DataDealWithAndSend(0, 0, 0); // first node data
// Send32Zero(); // send to update data
digitalWrite(led,LOW);
myservo.write(0);
}
}

//You can use the following code to deal with any information coming from the Computer (serial monitor)
if (Serial.available()) {
recvChar = Serial.read();

//This will send value obtained (recvChar) to the phone. The value will be displayed on the phone.
blueToothSerial.print(recvChar);
}
}
} 



//The following code is necessary to setup the bluetooth shield ------copy and paste----------------
void setupBlueToothConnection()
{
blueToothSerial.begin(9600);// BluetoothBee BaudRate to default baud rate 38400
blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
blueToothSerial.print("\r\n+STNA=HC-05\r\n"); //set the bluetooth name as "SeeedBTSlave"
blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
delay(2000); // This delay is required.
blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable 
Serial.println("The slave bluetooth is inquirable!");
delay(2000); // This delay is required.
blueToothSerial.flush();
}