Hi there!
I try to communicate from my android to my Arduino with a bluetooth board connected. Sending messages from the board to the smartphone works fine. But sending data from the Smartphone to the board fails.
Hardware: Arduono Mega ADK, Sparkfun bluetooth Mathe Silver, 12V DC power supply, Samsung Galxy S (i9000) with Android 2.3.6. Arduino is connected to my Mac fpr the Serial Monitor
Setup:
Bluetooth GND --- Arduino GND near 5V
Bluetooth VCC --- Arduino 5V
Bluetooth TX-I --- Arduino PIN 2
Bluetooth RX-I --- Arduino PIN 3
The Arduino code:
#include <SoftwareSerial.h>
int bluetoothTx = 2; // for Device -> BT
int bluetoothRx = 3; // Connect BT-RXI to PIN: for: BT -> Device (works, also if you do not use BT-TX-O)
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
boolean doWrite = false;
boolean doRead = true;
void setup() {
//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() {
// write to device: works fine
if (doWrite) {
bluetooth.println(cnt);
delay(400);
}
// read from device: does not work :(
if (doRead) {
char toSend = (char)bluetooth.read();
Serial.println(toSend);
}
}
}
to Send is always the char of (char)-1. bluetooth.available() does always return 0, also if permanently request in a loop. the same for Serial.available(); It is strange sending data from the board the the connected Android device works fine. I monitor the baud rate 9600.
Here is how I send the data via Android. It is taken from a tuorial and should work fine.
public class MainActivity 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.activity_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) { }
}
});
//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.getAddress().equals("00:06:66:4B:44:3E")) {
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 {
final String msg = myTextbox.getText().toString();
Log.d("BT", "send to BT: " + msg);
if (mmOutputStream != null) {
new Thread(new Runnable() {
@Override
public void run() {
Log.d("BT", "sendText(): Writing message to outputstream: " + msg);
try {
mmOutputStream.write(msg.getBytes());
Log.d("BT", "sendText(): Writing message to outputstream completed.");
} catch (IOException e) {
Log.e("BT", "sendText(): Error: " + e);
}
}
}).start();
}
myLabel.setText("Data Sent " + msg);
}
void closeBT() throws IOException {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
}
}
The Android log tells me the data is really sent:
D/BT(24456): send to BT: testdata
D/BT(24456): sendText(): Writing message to outputstream: testdata
D/BLZ20_ASOCKWRP(24456): asocket_write
I/BLZ20_WRAPPER(24456): blz20_wrp_poll: nfds 2, timeout -1 ms
D/BLZ20_WRAPPER(24456): blz20_wrp_poll: transp poll : (fd 53) returned r_ev [POLLOUT ] (0x4)
D/BLZ20_WRAPPER(24456): blz20_wrp_poll: return 1
I//system/bin/btld(22030): btlif_bts_api_data_cb: btlif_bts_api_data_cb : hdl 32, len 8
I//system/bin/btld(22030): jw_if_rfcomm_cl_cback: jw_if_rfcomm_cl_cback event=BTA_JV_RFCOMM_WRITE_EVT
I//system/bin/btld(22030): bts_alloc_buf: hdr:0x40425a00, max 1712, offset 18, len 0
I//system/bin/btld(22030): bts_alloc_buf: peer mtu 127
I//system/bin/btld(22030): rfc_setup_rx_buf: pushed in queue p_buf #0: 0x40425a00, len:0, offset:18
D/BLZ20_WRAPPER(24456): blz20_wrp_write: wrote 8 bytes out of 8 on fd 53
D/BT(24456): sendText(): Writing message to outputstream completed.
Thank you for your ideas.
Best regards