Android App通过HC-05向Arduino Uno蓝牙传数据失败求助
蓝牙发送数据到Arduino Uno失败问题排查
问题描述
我尝试通过自研Android App向Arduino Uno发送蓝牙数据,但设备未接收到数据。使用第三方串口蓝牙终端App发送相同信息可成功,因此问题出在我的Android代码中。以下是发送数据的代码:
public void SetAllAngles_click(View view) { try { EditText angleInput = findViewById(R.id.angleInputTXT); String a = angleInput.getText().toString(); if (bluetoothSocket != null && bluetoothSocket.isConnected()) { OutputStream outputStream = bluetoothSocket.getOutputStream(); if (outputStream != null) { String data = a + "," + a + "," + a + "," + a + "," + a + ",false"; outputStream.write(data.getBytes()); Toast.makeText(MainActivity.this, "Data sent successfully", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "OutputStream is null", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "Bluetooth connection is not established", Toast.LENGTH_SHORT).show(); } } catch (IOException e) { Toast.makeText(MainActivity.this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } }
代码始终提示“Data sent successfully”,但Arduino Uno未接收到数据。
解决方案
添加数据结束标记:Arduino串口读取逻辑通常依赖换行符(
\n)或回车符(\r)判断数据是否完整,第三方终端会自动添加该标记。修改数据字符串:String data = a + "," + a + "," + a + "," + a + "," + a + ",false\n";强制刷新输出流:写完数据后调用
flush(),确保缓冲区数据立即发送,避免滞留:outputStream.write(data.getBytes()); outputStream.flush(); // 新增刷新操作统一字符编码:明确指定编码格式,确保和Arduino端解析逻辑一致(默认UTF-8):
outputStream.write(data.getBytes(StandardCharsets.UTF_8));注意:需导入
java.nio.charset.StandardCharsets包验证数据格式匹配:检查Arduino端的解析代码,确认其能正确处理你发送的逗号分隔格式,尤其是最后一个
false的字符串格式是否符合预期,避免解析失败导致“未收到数据”的假象。
内容的提问来源于stack exchange,提问作者Ricardo Moreira
相关产品推荐
相关产品推荐

