[英]Communication Bluetooth android-arduino
我已经修改了可以在android sdk示例版本2.1中找到的android应用“蓝牙聊天”。该应用建立了与arduino的蓝牙连接,并且当我使用该应用发送0或1时,arduino发送了一条简单消息“您已按下0或1“。 如果我使用eclipse的调试进行测试,则可以使用,但是当我使用智能手机进行测试时,显示的结果却不同,arduino的字符串是零散的
示例:智能手机:0-> arduino“您已按下0或1”智能手机显示:“ y”“ ou pr”
字符串的其余部分丢失或未在显示屏中显示。 你能帮助我吗? logcat中没有错误,只有此错误。
这是代码:
public class BluetoothLampService {
// Debugging
private static final String TAG = "BluetoothLampService";
private static final boolean D = true;
// Name for the SDP record when creating server socket
private static final String NAME = "BluetoothLamp";
// Unique UUID for this application - Standard SerialPortService ID
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Member fields
private final BluetoothAdapter Adapter;
private final Handler Handler;
// private AcceptThread AcceptThread;
private ConnectThread ConnectThread;
private ConnectedThread ConnectedThread;
private int State;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
/**
* Constructor. Prepares a new BluetoothChat session.
* @param context The UI Activity Context
* @param handler A Handler to messages back to the UI Activity
*/
public BluetoothLampService(Context context, Handler handler) {
Adapter = BluetoothAdapter.getDefaultAdapter();
State = STATE_NONE;
Handler = handler;
}
/**
* Set the current state of the chat connection
* @param state An integer defining the current connection state
*/
private synchronized void setState(int state) {
State = state;
// Give the new state to the Handler so the UI Activity can update
Handler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
/**
* Return the current connection state. */
public synchronized int getState() {
return State;
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
// Cancel any thread attempting to make a connection
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
// Cancel any thread currently running a connection
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// Start the thread to listen on a BluetoothServerSocket
// if (AcceptThread == null) {
// AcceptThread = new AcceptThread();
// AcceptThread.start();
// }
setState(STATE_LISTEN);
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
* @param device The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device) {
// Cancel any thread attempting to make a connection
if (State == STATE_CONNECTING) {
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
}
// Cancel any thread currently running a connection
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// Start the thread to connect with the given device
ConnectThread = new ConnectThread(device);
ConnectThread.start();
setState(STATE_CONNECTING);
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket The BluetoothSocket on which the connection was made
* @param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
// Cancel the thread that completed the connection
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
// Cancel any thread currently running a connection
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// Cancel the accept thread because we only want to connect to one device
// if (AcceptThread != null) {AcceptThread.cancel(); AcceptThread = null;}
// Start the thread to manage the connection and perform transmissions
ConnectedThread = new ConnectedThread(socket);
ConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = Handler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.DEVICE_NAME, device.getName());
msg.setData(bundle);
Handler.sendMessage(msg);
setState(STATE_CONNECTED);
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (ConnectThread != null) {ConnectThread.cancel(); ConnectThread = null;}
if (ConnectedThread != null) {ConnectedThread.cancel(); ConnectedThread = null;}
// if (AcceptThread != null) {AcceptThread.cancel(); AcceptThread = null;}
setState(STATE_NONE);
}
/**
* Write to the ConnectedThread in an unsynchronized manner
* @param out The bytes to write
* @see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (State != STATE_CONNECTED) return;
r = ConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = Handler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Unable to connect device");
msg.setData(bundle);
Handler.sendMessage(msg);
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = Handler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Device connection was lost");
msg.setData(bundle);
Handler.sendMessage(msg);
}
/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
*/
/*
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket ServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
tmp = Adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
}
ServerSocket = tmp;
}
public void run() {
//Looper.prepare();
setName("AcceptThread");
BluetoothSocket socket = null;
// Listen to the server socket if we're not connected
while (State != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = ServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothLampService.this) {
switch (State) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
}
break;
}
}
}
}
// Looper.loop();
}
public void cancel() {
try {
ServerSocket.close();
} catch (IOException e) {
}
}
}
*/
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket Socket;
private final BluetoothDevice Device;
public ConnectThread(BluetoothDevice device) {
Device = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
Socket = tmp;
}
public void run() {
Looper.prepare();
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
Adapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
Socket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
Socket.close();
} catch (IOException e2) {}
// Start the service over to restart listening mode
BluetoothLampService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothLampService.this) {
ConnectThread = null;
}
// Start the connected thread
connected(Socket, Device);
Looper.loop();
}
public void cancel() {
try {
Socket.close();
} catch (IOException e) {
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket Socket;
private final InputStream InStream;
private final OutputStream OutStream;
public ConnectedThread(BluetoothSocket socket) {
Socket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
InStream = tmpIn;
OutStream = tmpOut;
}
public void run() {
Looper.prepare();
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
// FUNZIONANTE
bytes = InStream.read(buffer);
Log.i("BYTES", Integer.toString(bytes));
//String dati = new String(buffer);
//fine aggiunto da me
// Send the obtained bytes to the UI Activity
Handler.obtainMessage(MainActivity.MESSAGE_READ, 27, -1, buffer).sendToTarget();//buffer
} catch (IOException e) {
connectionLost();
break;
}
}
Looper.loop();
}
/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
OutStream.write(buffer);
// Share the sent message back to the UI Activity
Handler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
}
}
public void cancel() {
try {
Socket.close();
} catch (IOException e) {
}
}
}
}
您是否已经在清单文件上授予了对Android应用程序的许可?
使用权限android:name =“ android.permission.BLUETOOTH” /
使用权限android:name =“ android.permission.BLUETOOTH_ADMIN” /
然后,还要检查arduino串行连接上的串行波特率。
请尝试先从Android手机的设置中明确配对设备。 通常配对代码为1234
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.