Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通过蓝牙向STM32F411发送数据_Java_Android_Bluetooth_Stm32_Uart - Fatal编程技术网

Java 通过蓝牙向STM32F411发送数据

Java 通过蓝牙向STM32F411发送数据,java,android,bluetooth,stm32,uart,Java,Android,Bluetooth,Stm32,Uart,我正在尝试通过蓝牙将数据发送到stm32f411板。我使用的是HC-05 v2蓝牙模块,通过UART接口进行通信。当我从计算机发送数据时,它工作得很好——数据被发送,STM的响应通过RealTerm中的UART接收。然而,切换到蓝牙模块并从android应用程序发送和接收数据并不像预期的那样工作。现在我想发送ASCII数据(现在只发送0和1,但目标是发送0到100的整数)。也许这与消息长度或应用程序的波特率有关 我还尝试以字节而不是字节数组的形式发送数据,但它不起作用-当我发送0时,效果很好,但

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

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

我的android studio代码:

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

}

如果您简化了您的问题和设置,这将很有帮助。在这个问题中,不清楚您是否有两个问题(HC-05不工作和二进制数据不工作)。不清楚使用什么设置进行了什么测试。要简化设置,请将问题隔离到HC-05、Android或STM32F411。如果您的计算机支持蓝牙,您可以直接连接到HC-05模块。否则,请搜索合适的Android应用程序。您也可以将HC-05模块连接到USB到串行转换器,然后连接到com计算机。一旦你知道哪个组件有问题,请回到这里。HC-05和STM正在工作。我认为问题在于从应用程序传输数据-我的问题是我想发送ASCII编码的数字1-100,但就像我说的,即使在getBytes()中,应用程序似乎也在发送其他数据方法我指定了字符集。如果问题是Android应用程序,STM32F411的所有代码、问题标题和说明是关于什么的?我建议您使用USB到串行转换器,将HC-05连接回您的计算机和RealTerm,并在新问题中描述问题和设置。
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);