I'm trying to receive data and print it on a label of my application, but I can not get it. Actually, I have 0 experience with Arduino. It's the first time I see this. I read this tutorial to receive data from an Arduino. In my Arduino I have this code:
#include <SoftwareSerial.h>
const int RX_PIN = 2;
const int TX_PIN = 3;
SoftwareSerial blueTooth(RX_PIN, TX_PIN);
char commandChar;
void setup () {
Serial.begin(57600);
Serial.println("Let's start!");
blueTooth.begin(9600);
blueTooth.println("Hello, world?");
}
void loop () {
if (blueTooth.available())
Serial.write(blueTooth.read());
if (blueTooth.available())
blueTooth.write(Serial.read());
}
My Android code is this:
public class MainActivity extends AppCompatActivity {
FrameLayout frame;
GifImageView imagen;
TextView mensaje,debug;
Button boton;
private TextToSpeech talk;
public static StringBuilder sb;
private static final String TAG = "conexionBluetooth";
ConnectedThread mConnectedThread;
BluetoothAdapter blueAdapter;
BluetoothDevice mDevice;
BluetoothSocket mSocket;
Handler handler;
final int MENSAJE_RECIBIDO = 1;
final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String MAC = "00:21:13:02:EA:07";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
talk = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
if(i == TextToSpeech.SUCCESS){
talk.setLanguage(Locale.US);
mensajeInicio();
}
}
});
debug = (TextView) findViewById(R.id.debug);
mensaje = (TextView) findViewById(R.id.mensajeApp);
frame = (FrameLayout) findViewById(R.id.androidIc);
imagen = (GifImageView) findViewById(R.id.imageBluethoot);
imagen.setVisibility(View.INVISIBLE);
frame.setVisibility(View.VISIBLE);
boton = (Button) findViewById(R.id.botonInicio);
Animation flotarArriba = new TranslateAnimation(
TranslateAnimation.ABSOLUTE, 0f,
TranslateAnimation.ABSOLUTE, 0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0.05f
);
flotarArriba.setDuration(1000);
flotarArriba.setRepeatCount(-1);
flotarArriba.setRepeatMode(Animation.REVERSE);
flotarArriba.setInterpolator(new LinearInterpolator());
mensaje.setAnimation(flotarArriba);
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boton.setEnabled(false);
mConnectedThread.write("0");
Toast.makeText(getApplicationContext(),"Data send to arduino",Toast.LENGTH_LONG).show();
}
});
handler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case MENSAJE_RECIBIDO:
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\r\n");
if (endOfLineIndex > 0) {
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
debug.setText(sbprint);
boton.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
}};
configBluetooth();
comprobarEstadoBluetooth();
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
BluetoothDevice device = blueAdapter.getRemoteDevice(MAC);
try{
mSocket = crearSocket(device);
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"ERROR!! No se ha logrado crear el enchufe! " + e.getMessage(),Toast.LENGTH_LONG).show();
finish();
}
blueAdapter.cancelDiscovery();
Log.d(TAG, "...Connecting...");
try{
mSocket.connect();
Log.d(TAG,"Connection OK!!");
} catch (IOException e) {
try{
mSocket.close();
} catch (IOException e1) {
Toast.makeText(getApplicationContext(),"Error fatal en el metodo onResume. Incapaz de cerrar conexion: " + e1.getMessage(),Toast.LENGTH_LONG).show();
finish();
}
}
mConnectedThread = new ConnectedThread(mSocket);
mConnectedThread.start();
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
try {
mSocket.close();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error fatal en el metodo onPause. Incapaz de cerrar conexion: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
private void enable() throws IOException {
boton.setText(getString(R.string.finalizar));
mensaje.setText(getString(R.string.mensajeActivo));
frame.setVisibility(View.INVISIBLE);
imagen.setVisibility(View.VISIBLE);
mensaje2();
boton.setText(getString(R.string.iniciar));
mensaje.setText(getString(R.string.pontelos));
frame.setVisibility(View.VISIBLE);
imagen.setVisibility(View.INVISIBLE);
mensaje1();
}
private void mensajeInicio(){talk.speak(getString(R.string.app_name) + getString(R.string.textApp) + getString(R.string.pontelos),TextToSpeech.QUEUE_FLUSH,null);}
private void mensaje1(){talk.speak(getString(R.string.pontelos),TextToSpeech.QUEUE_FLUSH,null);}
private void mensaje2(){talk.speak(getString(R.string.mensajeActivo),TextToSpeech.QUEUE_FLUSH,null);}
private void configBluetooth(){
Toast.makeText(getApplicationContext(),"Metodo llamado",Toast.LENGTH_LONG).show();
blueAdapter = BluetoothAdapter.getDefaultAdapter();
if(blueAdapter != null){
Set<BluetoothDevice> pairedDevices = blueAdapter.getBondedDevices();
if(pairedDevices.size() > 0){
for(BluetoothDevice device: pairedDevices){
if(device.getName().equals("HC-06")) {
mDevice = device;
Toast.makeText(getApplicationContext(), "Nombre del dispositivo: " + mDevice.getName() +
"\nDireccion MAC: " + mDevice.getAddress() + ".", Toast.LENGTH_LONG).show();
}
}
}
}
}
private void comprobarEstadoBluetooth(){
if(blueAdapter == null){
Toast.makeText(getApplicationContext(),"ERROR!!! No hay soporte Bluetooth!",Toast.LENGTH_LONG).show();
finish();
}else{
if(blueAdapter.isEnabled()){
Toast.makeText(getApplicationContext(),"Bluetooth encendido. . .",Toast.LENGTH_LONG).show();
}else{
Intent activarBTH = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(activarBTH, 1);
}
}
}
private BluetoothSocket crearSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 15){
try{
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, uuid);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return device.createRfcommSocketToServiceRecord(uuid);
}
private class ConnectedThread extends Thread {
private final InputStream mInStream;
private final OutputStream mOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mInStream = tmpIn;
mOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // 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 = mInStream.read(buffer); // Get number of bytes and message in "buffer"
handler.obtainMessage(MENSAJE_RECIBIDO, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
handler.handleMessage(new Message());
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
}
I notice the following behaviors:
- The application does not crash when it is executed.
- When I start the application, the bluetooth module of the Arduino flashes differently. (I guess it's because my app connectswith the board).
- Inside the Log Cat, it can be seen that the connection has been made correctly. . .
What could be missing here to print the data received from the Arduino? I do not know if it's me, or the handler method never runs. (public void handleMessage (Message msg))
Also note that in the serial monitor of the Arduino, the value that I command when pressing the button of the application is never printed...
UPDATE
Investigating on the internet about the module of my Bluetooth (HC-06) I found that;
- If the light of the module is constantly flashing, it is not paired with the phone.
- If the module light stays on, then it is already connected.
My concern is that when I open my application, to blink constantly, it blinks much slower. . . Could it be that I've never been able to connect?