2020-10-14 10:28 AM
When I'm sending data from computer it works perfectly- data is sent and STM's response is received over UART in RealTerm. However switching to bluetooth module and sending and receiving data from android app doesn't work as expected. For now I want to send ASCII data (for now just 0 and 1, but the goal is to send integers from 0 to 100). Perhaps it has something to do with message length or app's baud rate.
I also tried to send data as byte not byte array but it didn't work- when I sent 0 it worked fine but when I sent 1 I got 120 decimal on STM, 2 I got 128, 3 I got 248. When I tried sending the same data back to app every message started with [B@ followed by usually 7 characters.
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
switch (atoi(&Received)) {
case 0:
size = sprintf(Data, "STOP\n\r");
HAL_GPIO_WritePin(BLUE_LED_GPIO_Port, BLUE_LED_Pin, GPIO_PIN_RESET);
break;
case 1:
size = sprintf(Data, "START\n\r");
HAL_GPIO_WritePin(BLUE_LED_GPIO_Port, BLUE_LED_Pin, GPIO_PIN_SET);
break;
default:
size = sprintf(Data, "Odebrano nieznany znak: %c\n\r", Received);
break;
}
HAL_UART_Transmit_IT(&huart1, Data, size);
HAL_UART_Receive_IT(&huart1, &Received, 1);
HAL_GPIO_TogglePin(RED_LED_GPIO_Port, RED_LED_Pin);
public class MainActivity extends AppCompatActivity {
Button someButton;
ListView pairedDevListView;
Switch bluetoothSwitch;
BluetoothAdapter myBluetoothAdapter;
Intent bluetoothEnablingIntent;
TextView connectionStatusText;
SeekBar rightEnSeekBar, leftEnSeekBar;
SendReceive sendReceive;
BluetoothDevice[] bluetoothPairedDevArray;
int REQUEST_ENABLE_BLUETOOTH = 1;
int requestCodeForEnable;
static final int STATE_LISTENING = 1;
static final int STATE_CONNECTING = 2;
static final int STATE_CONNECTED = 3;
static final int STATE_CONNECTION_FAILED = 4;
static final int STATE_MESSAGE_RECEIVED = 5;
private static final String APP_NAME = "STM32";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message message) {
switch (message.what){
case STATE_LISTENING:
connectionStatusText.setText("Listening");
break;
case STATE_CONNECTING:
connectionStatusText.setText("Connecting");
break;
case STATE_CONNECTED:
connectionStatusText.setText("Connected");
break;
case STATE_CONNECTION_FAILED:
connectionStatusText.setText("Connection failed");
break;
case STATE_MESSAGE_RECEIVED:
byte[] readBuff = (byte[]) message.obj;
//String tempMsg = new String(readBuff, 0 , message.arg1);
String tempMsg = null;
try {
tempMsg = new String(readBuff, "ASCII");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), String.valueOf(readBuff), Toast.LENGTH_SHORT).show();
connectionStatusText.setText(tempMsg);
break;
}
return true;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothEnablingIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
requestCodeForEnable = 1;
if(!myBluetoothAdapter.isEnabled()){
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}
findViewByIds();
implementListeners();
}
private void findViewByIds() {
pairedDevListView = findViewById(R.id.pairedDevicesListView);
bluetoothSwitch = findViewById(R.id.btSwitch);
connectionStatusText = findViewById(R.id.statusTextView);
rightEnSeekBar = findViewById(R.id.rightSeekBar);
leftEnSeekBar = findViewById(R.id.leftSeekBar);
someButton = findViewById(R.id.button2);
}
private void implementListeners() {
//BLUETOOTH ENABLING SWITCH
bluetoothSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
if(myBluetoothAdapter == null){
Toast.makeText(getApplicationContext(),"Bluetooth is not supported on this device", Toast.LENGTH_LONG).show();
}
else{
if(!myBluetoothAdapter.isEnabled()){
startActivityForResult(bluetoothEnablingIntent, requestCodeForEnable);
}
}
}
else{
if(myBluetoothAdapter.isEnabled()){
myBluetoothAdapter.disable();
Toast.makeText(getApplicationContext(), "Bluetooth is disabled", Toast.LENGTH_LONG).show();
}
}
}
});
//CLICKING ON DEVICE FROM PAIRED DEVICE LIST
pairedDevListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ClientClass clientClass = new ClientClass(bluetoothPairedDevArray[i]);
clientClass.start();
connectionStatusText.setText("Connecting");
}
});
someButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String string = "1";
try {
sendReceive.write(string.getBytes("ASCII"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
}
//SHOWING PAIRED DEVICES WHEN SWITCH IS CHECKED
private void showPairedDevices() {
Set<BluetoothDevice> btDevices = myBluetoothAdapter.getBondedDevices();
bluetoothPairedDevArray = new BluetoothDevice[btDevices.size()];
String[] deviceNames = new String[btDevices.size()];
int index = 0;
if(btDevices.size() > 0){
for(BluetoothDevice device: btDevices){
deviceNames[index] = device.getName();
bluetoothPairedDevArray[index] = device;
index++;
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, deviceNames);
pairedDevListView.setAdapter(arrayAdapter);
}
}
//SHOWING POP UP MESSAGE
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(requestCode == requestCodeForEnable){
if(resultCode == RESULT_OK){
Toast.makeText(getApplicationContext(), "Bluetooth is enabled", Toast.LENGTH_LONG).show();
showPairedDevices();
}
else if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth enabling cancelled", Toast.LENGTH_LONG).show();
}
}
}
private class ClientClass extends Thread{
private BluetoothSocket socket;
private BluetoothDevice device;
public ClientClass(BluetoothDevice device1){
this.device = device1;
try {
socket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
myBluetoothAdapter.cancelDiscovery();
try {
socket.connect();
Message message = Message.obtain();
message.what = STATE_CONNECTED;
handler.sendMessage(message);
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
Message message = Message.obtain();
message.what = STATE_CONNECTION_FAILED;
handler.sendMessage(message);
}
}
}
private class SendReceive extends Thread {
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public SendReceive(BluetoothSocket socket) {
bluetoothSocket = socket;
InputStream tempIn = null;
OutputStream tempOut = null;
try {
tempIn = bluetoothSocket.getInputStream();
tempOut = bluetoothSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
inputStream = tempIn;
outputStream = tempOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = inputStream.read(buffer);
handler.obtainMessage(STATE_MESSAGE_RECEIVED, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes) {
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}