Receive data from an Arduino sensor for the Android app ( Android Studio)

Asked

Viewed 759 times

1

Good night! I need a help with the application I’m developing, I made the bluetooth connection of my Arduino with the android app and it’s all right, I can turn on and off small but I do not know how to receive data from my temperature sensor. Can someone help me ? I just need this step to finish my TCC.

Below follows my code in JAVA:

public class pg_minhafabrica extends AppCompatActivity {

Button btn_conectar;
Button btn_motor;
Button btn_recirculacao;
Button btn_mostratemp;
TextView view_temp;


private static final int SOLICITA_ATIVACAO = 1;
private static final int SOLICITA_CONEXAO = 2;
private static final int MESSAGE_READ = 3;

ConnectedThread connectedThread;

Handler mHandler;
StringBuilder dadosBluetooth = new StringBuilder();

BluetoothAdapter meuBLuetoothAdapter = null;
BluetoothDevice meuDevice = null;
BluetoothSocket meuSocket = null;

boolean conexao = false;

private static String MAC = null;

UUID MEU_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pg_minhafabrica);

    btn_conectar = (Button) findViewById(R.id.btn_conectar);
    btn_motor = (Button) findViewById(R.id.btn_motor);
    btn_recirculacao = (Button) findViewById(R.id.btn_recirculacao);
    btn_mostratemp = (Button)findViewById(R.id.btn_mostratemp);
    view_temp = (TextView) findViewById(R.id.view_temp);

    meuBLuetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (meuBLuetoothAdapter == null) {
        Toast.makeText(getApplicationContext(), "Seu aparelho não possui bluetooth", Toast.LENGTH_LONG).show();
    } else if (!meuBLuetoothAdapter.isEnabled()) {
        Intent ativaBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(ativaBluetooth, SOLICITA_ATIVACAO);
    }

    btn_conectar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (conexao){
                //desconectar
                try{
                    meuSocket.close();
                    conexao = false;
                    btn_conectar.setText("Conectar");
                    Toast.makeText(getApplicationContext(), "Bluetooth desconectado", Toast.LENGTH_LONG).show();
                }catch (IOException erro){
                    Toast.makeText(getApplicationContext(), "Ocorreu um erro:", Toast.LENGTH_LONG).show();
                }
            }else {
                //conectar
                Intent abreLista = new Intent(pg_minhafabrica.this, lista_dispositivos.class);
                startActivityForResult(abreLista, SOLICITA_CONEXAO);
            }
        }
    });

    btn_motor.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (conexao) {
               connectedThread.enviar("rele1");
            }else {
                Toast.makeText(getApplicationContext(), "Bluetooth não esta conectado", Toast.LENGTH_LONG).show();
            }
        }
    });

    btn_recirculacao.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (conexao) {
                connectedThread.enviar("rele2");
            }else {
                Toast.makeText(getApplicationContext(), "Bluetooth não esta conectado", Toast.LENGTH_LONG).show();
            }
        }
    });


    mHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {

            if (msg.what == MESSAGE_READ) {

                String recebidos = (String) msg.obj;

                dadosBluetooth.append(recebidos);

                int fimInformacao = dadosBluetooth.indexOf("}");

                if (fimInformacao > 0) {

                    String dadoscompletos = dadosBluetooth.substring(0, fimInformacao);

                    int tamInformacao = dadoscompletos.length();

                    if (dadosBluetooth.charAt(0) == '{') {

                        //{rele1rele2}

                        String dadosFinais = dadosBluetooth.substring(1, tamInformacao);

                        Log.d("Recebidos", dadosFinais);

                        if (dadosFinais.contains("rele1-on")) {
                            btn_motor.setText("MOTOR LIGADO");
                            Log.d("LIGADO", dadosFinais);
                        } else if (dadosFinais.contains("rele1-off")) {
                            btn_motor.setText("MOTOR DESLIGADO");
                            Log.d("DESLIGADO", dadosFinais);
                        }

                        if (dadosFinais.contains("rele2-on")) {
                            btn_recirculacao.setText("BOMBA LIGADA");
                        } else if (dadosFinais.contains("rele-off")) {
                            btn_recirculacao.setText("BOMBA DESLIGADA");
                        }


                    }

                    dadosBluetooth.delete(0, dadosBluetooth.length());
                }
            }
        }

    };

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {

        case SOLICITA_ATIVACAO:
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(getApplicationContext(), "Bluetooth ativado", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Bluetooth não ativado", Toast.LENGTH_LONG).show();
                finish();
            }
            break;

        case SOLICITA_CONEXAO:
            if (resultCode == Activity.RESULT_OK){
                MAC = data.getExtras().getString(lista_dispositivos.ENDERECO_MAC);

                meuDevice = meuBLuetoothAdapter.getRemoteDevice(MAC);

                try {
                     meuSocket = meuDevice.createRfcommSocketToServiceRecord(MEU_UUID);

                     meuSocket.connect();

                     conexao = true;

                     connectedThread = new ConnectedThread(meuSocket);
                     connectedThread.start();

                     btn_conectar.setText("Desconectar");

                }catch (IOException erro) {

                    conexao = false;

                    Toast.makeText(getApplicationContext(), "Ocorreu um erro:", Toast.LENGTH_LONG).show();
                }
            }else {
                Toast.makeText(getApplicationContext(), "Falha ao obter o MAC", Toast.LENGTH_LONG).show();
            }
    }
}

private class ConnectedThread extends Thread {

    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    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) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[1024];  // 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 = mmInStream.read(buffer);

                String dadosBt = new String(buffer, 0, bytes);

                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, dadosBt).sendToTarget();

            } catch (IOException e) {
                break;
            }
        }
    }

    public void enviar(String dadosenviar) {
        byte[] msgBuffer = dadosenviar.getBytes();
        try {
            mmOutStream.write(msgBuffer);
        } catch (IOException e) { }
    }

}

}

MY CODE ON THE ARDUINO:

#include <SoftwareSerial.h>
#include <OneWire.h>
#include <DallasTemperature.h>

SoftwareSerial bluetooth(10, 11);

OneWire pino(3);
DallasTemperature barramento(&pino);
DeviceAddress sensor;

#define rele1 5
#define rele2 6

String comando;

void setup() {
  Serial.begin(9600);
  barramento.begin();
  bluetooth.begin(9600);
  barramento.getAddress(sensor, 0);

  pinMode(rele1, OUTPUT);
  pinMode(rele2, OUTPUT);
}

 void loop() {

  barramento.requestTemperatures(); 
  float temperatura = barramento.getTempC(sensor);
  bluetooth.print(temperatura);
  delay(500);

  comando = "";

  if(bluetooth.available()) {
    while(bluetooth.available()){
      char caracter = bluetooth.read();

      comando += caracter;
      delay(10);

    }
    //Serial.print("Comando: ");
    //Serial.println(comando);

    if(comando.indexOf("rele1") >=0) {
      digitalWrite(rele1, !digitalRead(rele1));
      bluetooth.println("Vai liga/Desliga rele1");
    }
    if(digitalRead(rele1)){
      bluetooth.println("rele-on");
    } else{
      bluetooth.println("rele-off");
    }

    if(comando.indexOf("rele2") >=0) {
      digitalWrite(rele2, !digitalRead(rele2));
      bluetooth.println("Vai liga/Desliga rele2");
    }

    bluetooth.println("{");

    if(digitalRead(rele2)){
      bluetooth.println("rele-on");
    } else{
      bluetooth.println("rele-off");
    }

    bluetooth.println("}");
  }
}
  • Good night!!! Can anyone help me ?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.