You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

安卓蓝牙向Arduino发送单字符加整数时出现数据错误求助

Hey there! Let's work through this Bluetooth communication glitch between your Android app and Arduino—super common stuff once you nail down the edge cases.

First, let's break down the two main issues you're seeing:

1. Single character works, but character + integer fails

This almost always boils down to data formatting and parsing mismatches between your Android sender and Arduino receiver. When you send just a single character, the Arduino can read it easily as a single byte. But when you send a combo like A5, the Arduino might be trying to read it as separate bytes (first A, then 5) instead of a single complete command, or it's waiting for more data that never comes.

2. Duplicate data + unexpected -1 values

That -1 is a dead giveaway: it's what Serial.read() returns when there's no data left to read. The duplicate reads usually happen because either:

  • Your Android app is sending the data twice (like the Spinner's onItemSelected triggering once on initialization and once when you manually select the option)
  • Your Arduino code is reading in a loop without checking if there's actually data available first.

Here's how to fix this step by step:

Step 1: Fix the Android side's sending logic

  • Add a delimiter to your data: When sending combo commands (like character + integer), append a newline character (\n) to the end. This gives the Arduino a clear "end of message" marker. For example, send "A5\n" instead of "A5".
  • Prevent duplicate sends from Spinner: The Spinner's onItemSelected fires once when the view initializes (for the default selected item) and again when you tap to choose it. Add a flag to skip the initial trigger:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    private boolean isFirstLoad = true;

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (isFirstLoad) {
            isFirstLoad = false;
            return; // Skip the initial default selection send
        }
        String command = parent.getItemAtPosition(position).toString();
        // Append newline as delimiter
        byte[] data = (command + "\n").getBytes();
        bluetoothSocket.getOutputStream().write(data);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {}
});

Step 2: Rewrite the Arduino's reading logic to handle complete messages

Instead of reading single bytes with Serial.read(), use methods that read until your delimiter, and always check if data is available first:

void loop() {
    // Only read if there's data waiting
    if (Serial.available() > 0) {
        // Read until the newline delimiter we added
        String receivedCommand = Serial.readStringUntil('\n');
        // Trim any extra whitespace/newlines
        receivedCommand.trim();

        // Now parse the command
        if (receivedCommand.startsWith("A")) {
            // Extract the integer part after the character
            int numValue = receivedCommand.substring(1).toInt();
            // Do something with numValue here
            Serial.print("Received command: ");
            Serial.println(receivedCommand);
            Serial.print("Parsed number: ");
            Serial.println(numValue);
        }
        // Add other cases for your Spinner options here
    }
}

Step 3: Debug with logs/serial output

  • On Android, add log statements to confirm when and what data is being sent (check Logcat for this).
  • On Arduino, use Serial.print() to output every received message—this will tell you if the duplicate data is coming from the Android app or if the Arduino is reading leftover bytes.

These changes should eliminate the -1 values, stop duplicate reads, and let your combo character+integer commands work reliably. Let me know if you hit any snags with specific parts!

内容的提问来源于stack exchange,提问作者B way Ng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:02:23