Send data of the integer type through the Bluetooth connection between android and arduino

0

I made a method to allow the sending of strings from android to arduino through bluetooth and I was successful! However, the question arose as to how to send data of type 'int', following the same idea.

What would be the code for this application? Below I make available what I did, both on android and arduino.

I was able to connect with the arduino, but when I move the seekBr the program closes and gives an error!

Anyone can help me thank you right away!

----------------------------------------------- ------------- No Android ----------------------------------- ---------------------

package com.example.seekbar1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;



  @SuppressLint("HandlerLeak")
public class MainActivity extends Activity {

  SeekBar seekBar;

  private BluetoothSocket btSocket = null;

  final int handlerState = 0;

  private static final int SolicitaAtivaçao = 1;

  private static final int SolicitaConexao = 2;

  Handler bluetoothIn;

  private ConnectedThread mConnectedThread;

  //Entrada das informações para fazer a interação entre o celular e o módulo bluetooth
  private BluetoothAdapter meuBluetooth = null;

  // SPP UUID service - isso deve funcionar para a maioria dos dispositivos
  private static final UUID MEU_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

  // String para o endereço MAC
  //quando usa lista de dispositivos, se não colocar igual a null da erro
  private static String MAC = null;

TextView textViewMedida, txtStringTamanho, txtString;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    //obtém o adaptador local bluetooth
    meuBluetooth = BluetoothAdapter.getDefaultAdapter();

    //Verifica se o didpositivo tem bluetooth
            if(meuBluetooth == null){
                //Se não tiver, a mensagem abaixo será mostrada e o programa será encerrado
                Toast.makeText(getApplicationContext(), "Seu dispositivo não possui bluetooth", Toast.LENGTH_LONG).show();
                finish();
                return;
            }

            //Se o bluetooth não estivver ativado, será solicitada a ativação do mesmo 
            //Através do intent, que inicia uma nova ação
            if(!meuBluetooth.isEnabled()){
                Intent solicita = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//Cria o intent
                startActivityForResult(solicita,SolicitaAtivaçao);//Starta o intent         
            }   

            seekBar = (SeekBar) findViewById(R.id.seekBar1);
            seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    try{

                    mConnectedThread.write(progress);
                    }catch(Exception e){
                        Toast.makeText(getApplicationContext(), "Erro"+e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            });


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    switch(requestCode){

    case SolicitaAtivaçao:
        if(resultCode ==Activity.RESULT_OK)//Se o bluetooth for ligado, a mensagem abaixo será mostrada
        {                                   //E o progrma continuará sendo executado
            Toast.makeText(getApplicationContext(), "O BLUETOOTH FOI LIGADO!", Toast.LENGTH_LONG).show();
        }else//Se o bluetooth não foi ativado, a mensagem abaixo será mostrada e o programa será fechado
        {
            Toast.makeText(getApplicationContext(), "O BLUETOOTH NÃO FOI LIGADO!", Toast.LENGTH_LONG).show();
            finish();
        }
        break;

    case SolicitaConexao:
        if(resultCode==Activity.RESULT_OK){             
            MAC = data.getExtras().getString(ListadeDispositivos.EnderecoMAC);

            //Para se ter um bluetoothdevice é necessário uilizar o BluetoothAdapter.getRemoteDevice(string)
            //Que representa um endereço Mac conhecido, que já foi apresentado no início
            BluetoothDevice device = meuBluetooth.getRemoteDevice(MAC);             
            try{
                //A função device.createRfcommSocketToServiceRecord(MEU_UUID) abre m conexão 
                //Entre o dispositivo e o módulo
                btSocket = device.createRfcommSocketToServiceRecord(MEU_UUID);
                //É iniciada a saída d dados do dispositivo
                btSocket.connect(); 

                //Se der tudo certo na hora da conexão, irá aparecer a tela do controle
                if(btSocket!=null){
                Toast.makeText(getApplicationContext(), "A CONEXÃO FOI BEM SUCEDIDA!", Toast.LENGTH_LONG).show();

                mConnectedThread = new ConnectedThread(btSocket);
                mConnectedThread.start();

                }
            }catch(IOException e){
                Toast.makeText(getApplicationContext(), "ERRO AO FAZER CONEXÃO", Toast.LENGTH_LONG).show();
            }   

        }else{
            Toast.makeText(getApplicationContext(), "Falha ao obter o endereço MAC", Toast.LENGTH_LONG).show();
        }
    break;
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.Conectar) {

        conectar();

        return true;
    }
    if (id ==R.id.Desconectar){

        if(btSocket !=null){

        desconectar();
        }else{
            Toast.makeText(MainActivity.this, "O módulo bluetooth não está conectado", Toast.LENGTH_LONG).show();
        }

        return true;
    }
    return super.onOptionsItemSelected(item);
}

//Definição da função conectar
public void conectar(){     
    Intent abreLista = new Intent(MainActivity.this,ListadeDispositivos.class);
    startActivityForResult(abreLista, SolicitaConexao);     
}

//Definição da função desconectar
public void desconectar(){
    try{
        btSocket.close();//Fecha a conexão
        btSocket = null;//E a conexão volta a ser nula

    }catch(IOException e){

    }
}



  private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        //creation of the connect thread
        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            try {
                //Create I/O streams for connection
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[256];
            int bytes; 

            // Keep looping to listen for received messages
            while (true) {
                try {
                    bytes = mmInStream.read(buffer);            //read bytes from input buffer
                    String readMessage = new String(buffer, 0, bytes);
                    // Send the obtained bytes to the UI Activity via handler
                    bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
                } catch (IOException e) {
                    break;
                }
            }
        }
        //Usado para enviar mensagens
        public void write(int input) {
            try {
                mmOutStream.write(input);                //write bytes over BT connection via outstream
            } catch (IOException e) {
                //if you cannot write, close the application
                Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
                finish();

              }
            }
        }

    }

----------------------------------------------- ------------- No arduino ----------------------------------- ---------------------

void leDadosSerial() {

 // Le dados da porta serial 1

while (Serial1.available()) {

char caract = (char)Serial1.read();
    
asked by anonymous 24.12.2015 / 13:34

0 answers