首页 > 解决方案 > 通过蓝牙向 STM32F411 发送数据

问题描述

我正在尝试通过蓝牙将数据发送到 stm32f411 板。我正在使用通过 UART 接口进行通信的 HC-05 v2 蓝牙模块。当我从计算机发送数据时,它工作得很好——发送数据并通过 RealTerm 中的 UART 接收 STM 的响应。但是,切换到蓝牙模块并从 android 应用程序发送和接收数据无法按预期工作。现在我想发送 ASCII 数据(现在只有 0 和 1,但目标是发送从 0 到 100 的整数)。也许它与消息长度或应用程序的波特率有关。

我也尝试将数据作为字节而不是字节数组发送,但它不起作用 - 当我发送 0 时它工作正常,但当我发送 1 时,我在 STM 上得到 120 十进制,2 我得到 128,3 我得到 248。当我尝试将相同的数据发送回应用程序,每条以 [B@ 开头的消息通常后跟 7 个字符。

我的安卓工作室代码:

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();
        }
    }
}

}

我的STM代码:

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);

}

标签: javaandroidbluetoothstm32uart

解决方案


推荐阅读