0

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. . .

enter image description here

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?

  • 1
    If you are not connected to the HC-06 and try to work with the socket, the monitor of your Android applications would at least show an error. Habe you checked, if you get an IOException when opening the streams? Your exeption handler is empty – chrisl Apr 10 '18 at 18:49
  • 1
    And have you tried this with a bluetooth serial terminal app in your phone? So you can rule out a Problem with the arduino code vor wiring. – chrisl Apr 10 '18 at 19:04
  • Hello,I follow your advice: In effect, if I am not connected to the bluetooth (or if I connect, and the bluetooth module is badly connected) the application releases an error. Download what you suggested (Bluetooth termial), I could verify that I am connecting with the module HC-06. But I can not receive data at the end ... @chrisl – TwoDent Apr 10 '18 at 20:23
  • Then maybe you use the wrong baudrate. My HC-06 is configured for 9600 baud by standard, but in the web you see several, which use other baudrates by default. Try to use other baudrates (for example 57600 I think). Also you can configure the module for different baudrates by using AT commands – chrisl Apr 11 '18 at 14:55
  • Oh right! I changed that too @chrisl ! Serial and bluetooth begin at 9600 now! I forgot to add that in my answer – TwoDent Apr 11 '18 at 16:28
3

I don't think your code is correct:

void loop () {
 if (blueTooth.available())
    Serial.write(blueTooth.read());
  if (blueTooth.available())         <---- 
    blueTooth.write(Serial.read());
}

Shouldn't you be monitoring Serial.available on this line?

  • Oh, well, I made the change that you say but nothing happends :/ – TwoDent Apr 10 '18 at 14:11
0

I could solve it already !!!! It turns out that the bluetooth module was badly connected to the arduino !!!! I can already receive data! thank you very much for your comments, especially chrisl, for your suggestion to use the bluetooth serial monitor app! :)

I had connected the VCC to 5V ... that was what was bothering me, I read on the web that if you have it in 5V, as a self defense, the RX pin is completely blocked. The VCC must be connected to 3.3V.

EDIT: I forgot something very important! had to change the baud of bluetooth to 9600 like Serial! this part was very important too.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.