I am trying to send data from app to arduino as well as send data from arduino to app. I am using Andriod Studio for the app. Arduino uno for mcu. I was able to successfully send data to hc-05 but inputstream.read() cant receive any data from arduino. Can you help me what's wrong. I get the code from youtube Bluetooth for Android and Arduino HC-05 Module, Java implementation - YouTube his code works in him but when I tried it to mine it won't work.
Here is the code in the arduino ino file:
byte receivedData;
int i=0;
void setup() {
Serial.begin(9600);
}
void loop() {
if(Serial.available()>0) {
receivedData = Serial.read();
if(receivedData==48){
for(int i =65;i<=90;i++){
Serial.print((char)i);
delay(100);
}
}
}
}
delay(100);
}
and here is the code for the app in android studio
package com.example.try1;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
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");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
System.out.println(btAdapter.getBondedDevices());
BluetoothDevice hc05 = btAdapter.getRemoteDevice("98:D3:61:F5:BC:71");
System.out.println(hc05.getName());
BluetoothSocket btSocket = null;
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);
//send 0 to arduino
try {
OutputStream outputStream = btSocket.getOutputStream();
outputStream.write(48);
} catch (IOException e) {
e.printStackTrace();
}
//receive data(ABCDEF...) from arduino
InputStream inputStream = null;
try {
inputStream = btSocket.getInputStream();
inputStream.skip(inputStream.available());
for (int i = 0; i < 26; i++) {
byte b = (byte) inputStream.read();
System.out.println((char) b);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
btSocket.close();
System.out.println(btSocket.isConnected());
} catch (IOException e) {
e.printStackTrace();
}
}
}