Reputation: 21
Using various tutorials, I have managed to connect my Android phone to a HC-05 bluetooth module connected to an Arduino. What I'm trying to do is have 5 Buttons set up that will transmit a unique integer per button only when the button is held down, otherwise they will send a "0" when the button is released. ergo BUTTON1 sends a "1" when pressed and "0" when released, BUTTON2 sens a "2" when pressed and a "0" when released. Currently, I cannot figure out how to send ANY data over the connection. From reading and watching various tutorials I've gained a small understanding but seem to be missing something.
Towards the bottom of my code in the public void run(), i have set up an OnClickListener for one of my buttons to try to send...well something once its pressed just to see if I can send SOMETHING useful to the Arduino.
Here is where I have my OnClickListener. I believe I should be sending "T" to the Arduino.
pUpBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
String testr="T:";
byte[] msgBuffer = testr.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
e.printStackTrace();
}
}
});
Upvotes: 1
Views: 2484
Reputation: 6277
First
Basically as per your requirement you can not use onClickListner instead use onTouchListner
Example
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
//send integer value here.(pressed)
} else if (event.getAction() == MotionEvent.ACTION_UP) {
//Send zero here.(released)
}
}
};
here is a sample code for sending and receiving data from bluetoothSPP
this method is to connect bluetooth device to remote device
private void connectToDevice(BluetoothDevice mBTDevice) {
try {
SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
mBtSocket = mBTDevice.createRfcommSocketToServiceRecord(SPP_UUID);
mBtSocket.connect();
} catch (IOException e) {
Log.d("connectBT", "while connecting device");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
use this for sending bytes.
public void send(String data) {
byte[] buffer = data.getBytes();
try {
mOutputStream = mBtSocket.getOutputStream();
mOutputStream.write(buffer);
Log.d("message", data + " sent");
} catch (IOException e) {
e.printStackTrace();
}
}
use this function for sending Integers
public void send() {
byte[] buffer = new bytes[size];
buffer[0]=(byte)'1';//prepare data like this
..
..
try {
mOutputStream = mBtSocket.getOutputStream();
mOutputStream.write(buffer);
Log.d("message", " sent");
} catch (IOException e) {
e.printStackTrace();
}
}
Hope this helps :)
Upvotes: 2