'Receiving data from arduino to android application
I have been struggling for a long time with receiving data from the arduino. I know how to send data to arduino but I don't know how to receive it. My android application is very simple, once launched it connects directly to arduino. The code on the arduino side is working fine, I tested it with the Bluetooth Transfer app ready. Please help.
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
static final UUID mUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Button buttonON, buttonOFF;
TextView tV_received;
BluetoothSocket btSocket = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonON = (Button)findViewById(R.id.button_on);
buttonOFF = (Button)findViewById(R.id.button_off);
tV_received = (TextView) findViewById(R.id.tV_received);
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
System.out.println(btAdapter.getBondedDevices());
BluetoothDevice hc05 = btAdapter.getRemoteDevice("00:21:13:03:CC:90");
System.out.println(hc05.getName());
int counter = 0;
do {
try {
btSocket = hc05.createRfcommSocketToServiceRecord(mUUID);
System.out.println(btSocket);
btSocket.connect();
System.out.println(btSocket.isConnected());
} catch (IOException e) {
e.printStackTrace();
}
counter++;
} while(!btSocket.isConnected() && counter < 3);
try {
OutputStream outputStream = btSocket.getOutputStream();
outputStream.write(48);
} catch (IOException e) {
e.printStackTrace();
}
InputStream inputStream = null;
try {
inputStream = btSocket.getInputStream();
inputStream.skip(inputStream.available());
byte b = (byte) inputStream.read();
System.out.println((char) b);
} catch (IOException e) {
e.printStackTrace();
}
}
public void clickON (View view) {
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("1".toString().getBytes());
}
catch (IOException e)
{
}
}
}
public void clickOFF (View view) {
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("0".toString().getBytes());
}
catch (IOException e)
{
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
