Trouble with Bluetooth connection


#1

Hi guys, I’m doing a project in which I have to make my phone communicate with the mbot. It connects and also receives the characters (in fact it lights up red) but does not receive the characters I want (‘f’, ‘b’, etc …). Furthermore, when I connect the mbot to the PC (for debug on the serial monitor) the Bluetooth communication is stopped and the module turns off, preventing me from viewing the characters I receive. Can you tell me why? This is my code:

#include <MeMCore.h>
#include <Arduino.h>
#include <Wire.h>
#include <SoftwareSerial.h>
#include "src/bluetoothhc.h"
#include "src/HC06.h"

BluetoothClassHC bluetoothhc;

MeRGBLed rgbled_7(7, 2);

MeDCMotor motor_9(9);
MeDCMotor motor_10(10);

char character = 'x';
int speed = 150;

void move(int direction, int speed) {
  int leftSpeed = 0;
  int rightSpeed = 0;
  if(direction == 1) {
    leftSpeed = speed;
    rightSpeed = speed;
  } else if(direction == 2) {
    leftSpeed = -speed;
    rightSpeed = -speed;
  } else if(direction == 3) {
    leftSpeed = -speed;
    rightSpeed = speed;
  } else if(direction == 4) {
    leftSpeed = speed;
    rightSpeed = -speed;
  }
  motor_9.run((9) == M1 ? -(leftSpeed) : (leftSpeed));
  motor_10.run((10) == M1 ? -(rightSpeed) : (rightSpeed));
}

void setup() {
  Serial.begin(115200);

  rgbled_7.fillPixelsBak(0, 2, 1);

  bluetoothhc.inithc(0,1, "BTSlave", 1234);
}

void loop() {
  if (bluetoothhc.dataLineAvailableHc()) {
    move(1, 50 / 100.0 * 255);
    delay(3);
    move(1, 0);
    character = bluetoothhc.readDataLineHc();

    rgbled_7.setColor(0, 255, 0, 0);
    rgbled_7.show();

    delay(200);

    rgbled_7.setColor(0, 0, 0, 0);
    rgbled_7.show();

    Serial.print("Character: ");
    Serial.println(character);
    
    if (character == 'f') {
      rgbled_7.setColor(0, 0, 255, 0);
      rgbled_7.show();

      move(1, speed);
      delay(3);
      move(1, 0);
    } else if (character == 'b') {
      rgbled_7.setColor(0, 0, 0, 255);
      rgbled_7.show();

      move(2, speed);
      delay(3);
      move(2, 0);
    } else if (character == 'l') {
      rgbled_7.setColor(0, 255, 255, 0);
      rgbled_7.show();

      move(3, speed);
      delay(3);
      move(3, 0);
    } else if (character == 'r') {
      rgbled_7.setColor(0, 0, 255, 255);
      rgbled_7.show();

      move(4, speed);
      delay(3);
      move(4, 0);
    }
  }

  _loop();
}

void _loop() {
  bluetoothhc.bluetoothLoopHc();
}

thanks in advance!


#2

Hey! I think your best bet is to contact Makeblock Support. The Bluetooth module turning off when it connects to a PC is normal, and I don’t think the exact characters are read, and something else is read because of the way it sends the data via Bluetooth.


#3

@3pp0 I don’t quite understand what you mean by it receiving characters but not the ones you want, can you explain a bit more?

This is probably a hardware feature. The Bluetooth is probably designed to turn off when connected via serial to prevent multiple connections or weird bugs that could occur when uploading code from Bluetooth and serial.

@mblockAI


#4

This is an automated AI response. Verify important information.

Okay, I can definitely help with this! This is a common set of problems when mixing Bluetooth and Serial Monitor debugging on Arduino-based boards like the mBot’s mCore.

Let’s break down the issues and the code:

Issue 1: Bluetooth Stops When Connected to PC (Serial Monitor)

  • Cause: This is the most critical point. You are initializing the Bluetooth module using bluetoothhc.inithc(0, 1, "BTSlave", 1234);. Pins 0 (RX) and 1 (TX) on the mCore board (and most Arduino Uno compatible boards) are the hardware serial pins. These are the exact same pins used for USB communication with the PC.
    When you initialize Serial.begin(115200);, you are telling the mBot to use pins 0 and 1 to talk to the PC. When you initialize bluetoothhc.inithc(0, 1, ...), you are also telling it to use pins 0 and 1 to talk to the Bluetooth module.
    You cannot have both active simultaneously on the same pins. When you plug in the USB cable, the USB-to-serial chip connection takes precedence or interferes, effectively disabling the Bluetooth module connected to those same pins.
  • Solution: You need to use SoftwareSerial for your Bluetooth module. This allows you to define other digital pins to act as RX and TX for Bluetooth communication, leaving the hardware pins (0 and 1) free for USB debugging.
    1. Hardware Change: Connect the Bluetooth module’s TX pin to a digital pin on the mBot (e.g., pin 2) and the module’s RX pin to another digital pin (e.g., pin 3). Make sure these pins are available and suitable on the specific port you plugged the module into on the mBot. Check the mBot port documentation.
    2. Code Change:
      • Include the SoftwareSerial library: #include <SoftwareSerial.h> (You already have this).
      • Create a SoftwareSerial object before setup(): SoftwareSerial myBlueSerial(2, 3); // RX, TX - Use the pins you connected to
      • You will likely need to modify how your bluetoothhc library is initialized. Looking at its name (bluetoothhc, HC06.h), it probably expects a Serial object (either hardware Serial or a SoftwareSerial object). Without seeing the library’s inithc definition, it’s hard to be certain, but you might need to:
        • Pass the myBlueSerial object to the library’s initialization function.
        • Or, the library might have a different initialization function that takes pin numbers for SoftwareSerial.
        • Alternatively, and often easier: If the bluetoothhc library isn’t flexible, you can manage the Bluetooth communication directly using your myBlueSerial object:
          #include <MeMCore.h>
          #include <SoftwareSerial.h> // Use SoftwareSerial
          
          // Define pins for Software Serial
          const int BLUETOOTH_RX_PIN = 2; // Connect to BT TX
          const int BLUETOOTH_TX_PIN = 3; // Connect to BT RX
          SoftwareSerial bluetoothSerial(BLUETOOTH_RX_PIN, BLUETOOTH_TX_PIN);
          
          MeRGBLed rgbled_7(7, 2);
          MeDCMotor motor_9(9);
          MeDCMotor motor_10(10);
          
          char character = 'x';
          int speed = 150;
          
          // ... (keep your move function) ...
          
          void setup() {
            Serial.begin(9600); // For PC debugging via USB
            bluetoothSerial.begin(9600); // Default for HC-06 often 9600. Check your module!
            Serial.println("mBot Ready. Waiting for Bluetooth connection...");
            // No need for bluetoothhc.inithc if managing directly
          }
          
          void loop() {
            // Check if data is available from Bluetooth
            if (bluetoothSerial.available()) {
              character = bluetoothSerial.read(); // Read the character
          
              // --- Debugging Output ---
              Serial.print("Received via Bluetooth: ");
              Serial.println(character);
              // --- End Debugging ---
          
              // Indicate reception (e.g., quick green flash)
              rgbled_7.setColor(0, 0, 255, 0); // Green
              rgbled_7.show();
              delay(50);
              rgbled_7.setColor(0, 0, 0, 0); // Off
              rgbled_7.show();
          
          
              // --- Your Command Logic ---
              if (character == 'f') {
                 Serial.println("Command: Forward");
                 rgbled_7.setColor(0, 0, 255, 0); // Green for 'f'
                 rgbled_7.show();
                 move(1, speed);
                 delay(100); // Maybe move for a short duration? Or until 's' (stop)?
                 move(1, 0);
                 rgbled_7.setColor(0, 0, 0, 0); // Off
                 rgbled_7.show();
              } else if (character == 'b') {
                 Serial.println("Command: Backward");
                 rgbled_7.setColor(0, 0, 0, 255); // Blue for 'b'
                 rgbled_7.show();
                 move(2, speed);
                 delay(100);
                 move(2, 0);
                 rgbled_7.setColor(0, 0, 0, 0); // Off
                 rgbled_7.show();
              } else if (character == 'l') {
                 Serial.println("Command: Left");
                 rgbled_7.setColor(0, 255, 255, 0); // Yellow for 'l'
                 rgbled_7.show();
                 move(3, speed);
                 delay(100);
                 move(3, 0);
                 rgbled_7.setColor(0, 0, 0, 0); // Off
                 rgbled_7.show();
              } else if (character == 'r') {
                 Serial.println("Command: Right");
                 rgbled_7.setColor(0, 0, 255, 255); // Magenta for 'r'
                 rgbled_7.show();
                 move(4, speed);
                 delay(100);
                 move(4, 0);
                 rgbled_7.setColor(0, 0, 0, 0); // Off
                 rgbled_7.show();
              } else {
                 Serial.println("Command: Unknown");
                 // Optional: Indicate unknown command (e.g., quick red flash)
                 rgbled_7.setColor(0, 255, 0, 0); // Red
                 rgbled_7.show();
                 delay(50);
                 rgbled_7.setColor(0, 0, 0, 0); // Off
                 rgbled_7.show();
              }
            }
          
            // You might not need the _loop() or bluetoothLoopHc() if using standard SoftwareSerial
          }
          
          // Remove void _loop() and its call in loop() if not using the bluetoothhc library
          
          // --- Keep your move function ---
          void move(int direction, int speed) {
            // ... (your existing move function code is likely okay, but check the M1/M2 logic)
            // A common way to write this for mBot:
            int leftSpeed = 0;
            int rightSpeed = 0;
            if(direction == 1) { // Forward
              leftSpeed = -speed; // Motor 1 (M1) is often reversed
              rightSpeed = speed;
            } else if(direction == 2) { // Backward
              leftSpeed = speed;
              rightSpeed = -speed;
            } else if(direction == 3) { // Left Turn
              leftSpeed = speed;
              rightSpeed = speed;
            } else if(direction == 4) { // Right Turn
              leftSpeed = -speed;
              rightSpeed = -speed;
            } else if (direction == 0) { // Stop
               leftSpeed = 0;
               rightSpeed = 0;
            }
            motor_9.run(leftSpeed);  // Assuming motor_9 is Left Motor connected to M1
            motor_10.run(rightSpeed); // Assuming motor_10 is Right Motor connected to M2
          }
          

Issue 2: Not Receiving the Desired Characters (‘f’, ‘b’, etc.)

  • Cause 1 (Related to Issue 1): The serial conflict might be corrupting the data even when the USB is not plugged in, or the bluetoothhc library isn’t reading it correctly under these conditions. Solving Issue 1 often solves this too.
  • Cause 2 (App Sending Different Data): How are you sending the characters from your phone?
    • Make sure the app is sending only the single character (‘f’, ‘b’, ‘l’, ‘r’) and not extra characters like newline (\n) or carriage return (\r). Some apps send f\n when you press a button labeled “f”.
    • Your code currently reads only one character at a time with readDataLineHc() (or bluetoothSerial.read() in my example). If the phone sends “forward” or “f\n”, you’ll only process the ‘f’ (which is good) but might get unexpected behavior on the next loop iteration if the ‘\n’ is read then.
    • Test with a Standard App: Try using a generic “Bluetooth Serial Terminal” app on your phone first. These apps let you type and send specific characters/strings, making it easier to debug if the problem is the Arduino code or your specific control app. Send just ‘f’, then just ‘b’, etc., and see if the correct actions happen (and check the Serial Monitor with the SoftwareSerial fix).
  • Cause 3 (Code Logic):
    • Suspicious move call: In your original loop, you have move(1, 50 / 100.0 * 255); delay(3); move(1, 0); before you even read the character (character = bluetoothhc.readDataLineHc();). This means the robot briefly jerks forward every time any data is received from Bluetooth, regardless of what character it is. This is likely not intended and should be removed from that position.
    • LED Indication: You have a red LED flash (rgbled_7.setColor(0, 255, 0, 0);) after reading the character but before the if/else if checks. This confirms that bluetoothhc.dataLineAvailableHc() is becoming true and readDataLineHc() is being called. This is good information! It means data is arriving. The problem is likely what data it is, or the comparison logic.
    • Debugging: Use Serial.print("Character: "); Serial.println(character); (once you have SoftwareSerial working) to see exactly what character value the mBot is receiving. Is it ‘f’ (ASCII 102) or something else?

Summary and Recommendations:

  1. Fix the Serial Conflict: This is the highest priority. Switch to using SoftwareSerial on different pins (e.g., 2 and 3) for Bluetooth. Connect the module accordingly. Update your code to use the SoftwareSerial object (either directly or by configuring your bluetoothhc library if possible).
  2. Use Serial Monitor for Debugging: With SoftwareSerial active for Bluetooth, you can now safely use Serial.begin() and Serial.println() to print the received characters and other debug messages to the Arduino IDE Serial Monitor via the USB cable.
  3. Verify Sent Characters: Use a generic Bluetooth Serial Terminal app to send single, specific characters (‘f’, ‘b’, ‘l’, ‘r’) to confirm the mBot receives and processes them correctly.
  4. Clean Up loop() Logic: Remove the move command that runs unconditionally whenever data arrives. Ensure your LED indicators correctly reflect the received command inside the if/else if blocks.
  5. Check Motor Logic: Double-check which motor is connected to M1/M9 and M2/M10 and whether they need positive or negative speed values to go forward using the move function. My example move function uses a common mBot convention, but verify it for your setup.

Implementing the SoftwareSerial change should allow you to debug effectively using the Serial Monitor and pinpoint why the specific characters aren’t triggering the desired actions. Good luck!