Merging 2 Serial Communication codes

Hello everyone,

I am currently working on a project where i need to receive data from a Hc-05 Bluetooth transmitter and also from a GY-521 MPU6050 Gyroscope module. The code below works well on each module alone, the problem comes in when i try to merge the 2 codes together. I tried everything, but nothing seems to work. I am a beginner with Arduino and i 'd like to know how could i merge the 2 codes together and receive data from the 2 modules at the same time .

Thank you anticipated!
MPU6050:

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high
#define OUTPUT_READABLE_YAWPITCHROLL
#define INTERRUPT_PIN 2  
#define LED_PIN 13 
bool blinkState = false;
bool dmpReady = false;  
uint8_t mpuIntStatus;   
uint8_t devStatus;      
uint16_t packetSize;    
uint16_t fifoCount;     
uint8_t fifoBuffer[64]; 

Quaternion q;           
VectorInt16 aa;         
VectorInt16 aaReal;     
VectorInt16 aaWorld;    
VectorFloat gravity;    
float euler[3];         
float ypr[3];           

uint8_t teapotPacket[14] = { '

HC05:

byte payloadData[32] = {0};
byte Attention = 0;
byte checksum = 0;
byte generatedchecksum = 0;
int  Plength;
int throttle = 0;
int throttlePin = 3;

void setup() {
  Serial.begin(57600);
  Serial.println("Attention Values");  
  delay(5000);
  analogWrite(throttlePin, 255);
  delay(1000);
  analogWrite(throttlePin, 0);
  
  pinMode(throttlePin, OUTPUT);

}
byte ReadOneByte()
{
  int ByteRead;
  while (!Serial.available());
  ByteRead = Serial.read();
  return ByteRead;
}
void loop()
{
  while (1) {
    if (ReadOneByte() == 170)
    {
      if (ReadOneByte() == 170)
      {
        Plength = ReadOneByte();
        if (Plength == 32)
        {
          generatedchecksum = 0;
          for (int i = 0; i < Plength; i++)
          {
            payloadData[i]     = ReadOneByte();       
            generatedchecksum  += payloadData[i] ;
          }
          generatedchecksum = 255 - generatedchecksum;
          checksum  = ReadOneByte();

          if (checksum == generatedchecksum)
          {
            if (payloadData[28] == 4)
            {
              Attention = payloadData[29];
              Serial.println(Attention, DEC);
              if (Attention > 50)
              {
                analogWrite(throttlePin , 0);
              }
              else {
                analogWrite(throttlePin , 254);
              }
            }
          }
        }
      }
    }
  }
}

Edit: i reduced the number of characters so i can post code previews.

hc05codeArdu.ino (1.68 KB)

mpu6050ARDU.ino (17.9 KB)

, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

volatile bool mpuInterrupt = false;   
void dmpDataReady() {
  mpuInterrupt = true;
}

const int inainte = 4;
const int inapoi = 6;
const int stanga = 5;
const int dreapta = 7;

int yaw      = 255 / 2;
int pitch    = 255 / 2;
int roll      = 255 / 2;

int yawPin        = 8;
int pitchPin      = 9;
int rollPin      = 10;

void setup() {
  pinMode (inainte, OUTPUT);
  pinMode (inapoi, OUTPUT);
  pinMode (stanga, OUTPUT);
  pinMode (dreapta, OUTPUT);
  // join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000);
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif
  Serial.begin(115200);

pinMode( yawPin,      OUTPUT );
  pinMode( pitchPin,    OUTPUT );
  pinMode( rollPin,      OUTPUT );

while (!Serial);
 
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);

Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

Serial.println(F("\nSend any character to begin DMP programming and demo: "));
  while (Serial.available() && Serial.read());
  while (!Serial.available());               
  while (Serial.available() && Serial.read());

Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();
  mpu.setXGyroOffset(220);
  mpu.setYGyroOffset(76);
  mpu.setZGyroOffset(-85);
  mpu.setZAccelOffset(1788);
  if (devStatus == 0) {
    mpu.CalibrateAccel(6);
    mpu.CalibrateGyro(6);
    mpu.PrintActiveOffsets();
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
    Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
    Serial.println(F(")..."));
    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();

Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;

packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }

pinMode(LED_PIN, OUTPUT);
}

void loop() {
  if (!dmpReady) return;

while (!mpuInterrupt && fifoCount < packetSize) {
    if (mpuInterrupt && fifoCount < packetSize) {
      fifoCount = mpu.getFIFOCount();
    }
 
  }
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();

fifoCount = mpu.getFIFOCount();
  if (fifoCount < packetSize) {
 
  }
  else if ((mpuIntStatus & (0x01 << MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));

} else if (mpuIntStatus & (0x01 << MPU6050_INTERRUPT_DMP_INT_BIT)) {

while (fifoCount >= packetSize) {
      mpu.getFIFOBytes(fifoBuffer, packetSize);
 
      fifoCount -= packetSize;
    }

#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    Serial.print("ypr\t");
    Serial.print(ypr[0] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr[1] * 180 / M_PI);
    Serial.print("\t");
    Serial.println(ypr[2] * 180 / M_PI);
#endif

#ifdef OUTPUT_TEAPOT
    teapotPacket[2] = fifoBuffer[0];
    teapotPacket[3] = fifoBuffer[1];
    teapotPacket[4] = fifoBuffer[4];
    teapotPacket[5] = fifoBuffer[5];
    teapotPacket[6] = fifoBuffer[8];
    teapotPacket[7] = fifoBuffer[9];
    teapotPacket[8] = fifoBuffer[12];
    teapotPacket[9] = fifoBuffer[13];
    Serial.write(teapotPacket, 14);
    teapotPacket[11]++;
#endif
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
  }
  if ((ypr[2] * 180 / M_PI) < -20) {
    digitalWrite(dreapta, LOW);
    digitalWrite(stanga, HIGH);
    roll = (ypr[2] * 180 / M_PI);
  }
  if ((ypr[2] * 180 / M_PI) > 20) {
    digitalWrite(dreapta, HIGH);
    digitalWrite(stanga, LOW);
    roll = -(ypr[2] * 180 / M_PI);
  }
  if (ypr[2] * 180 / M_PI >= -20 && ypr[2] * 180 / M_PI <= 20) {
    digitalWrite(dreapta, LOW);
    digitalWrite(stanga, LOW);
    roll = 0;
  }

if ((ypr[1] * 180 / M_PI) < 15) {
    digitalWrite(inapoi, LOW);
    digitalWrite(inainte, HIGH);
    pitch = ypr[1] * 180 / M_PI;
  }
  if ( (ypr[1] * 180 / M_PI) > 45) {
    digitalWrite(inapoi, HIGH);
    digitalWrite(inainte, LOW);
    pitch = -(ypr[1] * 180 / M_PI);

}
  if (ypr[1] * 180 / M_PI >= 15  && ypr[1] * 180 / M_PI <= 45) {
    digitalWrite(inainte, LOW);
    digitalWrite(inapoi, LOW);
    pitch = 0;
  }

analogWrite( throttlePin,  throttle );
  analogWrite( yawPin,      yaw      );
  analogWrite( pitchPin,    pitch    );
  analogWrite( rollPin,      roll    );
}


HC05:

§DISCOURSE_HOISTED_CODE_1§


Edit: i reduced the number of characters so i can post code previews.

![scheme.png|1920x1080](upload://qhhGTTEbBmmX2YeWodUywaqBiyD.png)

[hc05codeArdu.ino|attachment](upload://agyrEtpCG3Ba8Ieg3G26Zxxp7wH.ino) (1.68 KB)

[mpu6050ARDU.ino|attachment](upload://61H9vqW9Rw00lBlt29uxWI3WnR3.ino) (17.9 KB)

![scheme.png|1920x1080](upload://qhhGTTEbBmmX2YeWodUywaqBiyD.png)

Your diagram shows the HC05 connected to Serial1 but the stand alone code is not using that. When you tried to combine the two codes, did you use Serial1?

I suggest that you reduce the size of the mpu6050 code so that you can get your best attempt to merge the two codes into an inline posting. Attached code will have fewer people looking at it.

If you forget about the HC05 for a moment, but just use the serial code from its example and use the serial monitor for input, can you merge the two codes?

cattledog:
Your diagram shows the HC05 connected to Serial1 but the stand alone code is not using that. When you tried to combine the two codes, did you use Serial1?

I suggest that you reduce the size of the mpu6050 code so that you can get your best attempt to merge the two codes into an inline posting. Attached code will have fewer people looking at it.

If you forget about the HC05 for a moment, but just use the serial code from its example and use the serial monitor for input, can you merge the two codes?

When i merged the 2 codes, i used Serial1 for Hc05. What do you mean by forgetting about the HC05 exactly? Serial Monitors shows data correctly as long as i test the modules one by one.

Both sketches are programmed in a blocking fashion, there is no way to combine them.

Search for non-blocking variants to combine, or change the sketches.

Rewriting them from scratch would be the best option.

Can I have the answers to the following questions?

1. MPU6050 is a 3-axis Gyroscope combined with 3-axis accelerometer and Motion Processor. Write down the names of the parameters that you want to measure by it and store them into variables.

2. What device are you interfacing via BT? What information you want to receive via BT and what are the usages of those information? Are you interfacing Android Phone via BT?

3. Are you using Arduino MEGA?

Attached pls find an attempt to combine them using non-blocking code.

I don’t have your libs so I didn’t try to compile it. If/when you have compile errors, pls use the “Copy error messages” button to help debug it.

HC05_MPU_combined.ino (11.2 KB)

GolamMostafa:
Can I have the answers to the following questions?

1. MPU6050 is a 3-axis Gyroscope combined with 3-axis accelerometer and Motion Processor. Write down the names of the parameters that you want to measure by it and store them into variables.

2. What device are you interfacing via BT? What information you want to receive via BT and what are the usages of those information? Are you interfacing Android Phone via BT?

3. Are you using Arduino MEGA?

  1. I need the yaw , pitch and roll , which are in the above code: ypr[0], ypr[1] and ypr[2]
    2.It’s a Neurosky Mindwave mobile 2 and i only need the attention level sent to the BT
    3.Yes
    Thank you for the reply!

Blackfin:
Attached pls find an attempt to combine them using non-blocking code.

I don't have your libs so I didn't try to compile it. If/when you have compile errors, pls use the "Copy error messages" button to help debug it.

I will test it and will follow up with an answer! Thank you very much !

xlorianx:
I will test it and will follow up with an answer! Thank you very much !

Ok, so on the first compilation i get this error:

Arduino: 1.8.13 (Windows 10), Board: "Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"





















C:\Users\kodie\Desktop\HC05_MPU_combined\HC05_MPU_combined.ino: In function 'void serialRX_HC05()':

HC05_MPU_combined:242:39: error: expected ';' before 'ST_ST_CHECKSUM'

                         stateRX_HC05  ST_ST_CHECKSUM;

                                       ^~~~~~~~~~~~~~

HC05_MPU_combined:247:21: error: expected ':' before 'if'

                     if( ch == (0xff - generatedchecksum) )

                     ^~

HC05_MPU_combined:262:36: error: 'ST_ST_HDR1' was not declared in this scope

                     stateRX_HC05 = ST_ST_HDR1;

                                    ^~~~~~~~~~

C:\Users\kodie\Desktop\HC05_MPU_combined\HC05_MPU_combined.ino:262:36: note: suggested alternative: 'ST_HDR1'

                     stateRX_HC05 = ST_ST_HDR1;

                                    ^~~~~~~~~~

                                    ST_HDR1

C:\Users\kodie\Desktop\HC05_MPU_combined\HC05_MPU_combined.ino: In function 'void data_getMPU6050()':

HC05_MPU_combined:279:13: error: 'stateRX_MPU' was not declared in this scope

     switch( stateRX_MPU )

             ^~~~~~~~~~~

C:\Users\kodie\Desktop\HC05_MPU_combined\HC05_MPU_combined.ino: In function 'void ProcessDMP(uint16_t)':

HC05_MPU_combined:358:5: error: 'digtalWrite' was not declared in this scope

     digtalWrite(LED_PIN, blinkState);

     ^~~~~~~~~~~

C:\Users\kodie\Desktop\HC05_MPU_combined\HC05_MPU_combined.ino:358:5: note: suggested alternative: 'digitalWrite'

     digtalWrite(LED_PIN, blinkState);

     ^~~~~~~~~~~

     digitalWrite

exit status 1

expected ';' before 'ST_ST_CHECKSUM'



This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

i am guessing it's because we're missing an '=' sign between stateRX_HC05 and ST_ST_CHECKSUM on line 242; Also is ST_ST_CHECKSUM intended or should it be ST_CHECKSUM (same for ST_ST_HDR1 on line 262)? if so we're getting a ST_ST_CHECKSUM (and ST_ST_HDR1)not declared error, but if i rename it to ST_CHECKSUM (ST_HDR1 respectively) assuming they were typos , the program compiles to line 279 where i am getting :

Arduino: 1.8.13 (Windows 10), Board: "Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"





















C:\Users\kodie\Desktop\HC05_MPU_combined\HC05_MPU_combined.ino: In function 'void data_getMPU6050()':

HC05_MPU_combined:279:13: error: 'stateRX_MPU' was not declared in this scope

     switch( stateRX_MPU )

             ^~~~~~~~~~~

C:\Users\kodie\Desktop\HC05_MPU_combined\HC05_MPU_combined.ino: In function 'void ProcessDMP(uint16_t)':

HC05_MPU_combined:358:5: error: 'digtalWrite' was not declared in this scope

     digtalWrite(LED_PIN, blinkState);

     ^~~~~~~~~~~

C:\Users\kodie\Desktop\HC05_MPU_combined\HC05_MPU_combined.ino:358:5: note: suggested alternative: 'digitalWrite'

     digtalWrite(LED_PIN, blinkState);

     ^~~~~~~~~~~

     digitalWrite

exit status 1

'stateRX_MPU' was not declared in this scope



This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

OK, sorry about that. It’s not my practice to post defective code. I usually try to debug and at least make it compile before posting.

Try the attached.

HC05_MPU_combined.ino (11.3 KB)

Blackfin:
OK, sorry about that. It's not my practice to post defective code. I usually try to debug and at least make it compile before posting.

Try the attached.

Don't worry about it, i really appreciate that you took the time to help me! This second code you sent me compiles without problems, the gyroscope works as intended, but on the BT serial monitor(57600) i am getting the following characters and does not receive the attention values: ⸮"k⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮Ô⸮⸮!9⸮⸮w⸮Co⸮íg⸮9⸮⸮⸮Kʭg⸮⸮)⸮⸮= և1⸮!sȈ⸮⸮⸮⸮⸮í⸮⸮"

Could it be because the hc05 BT works on different baud rate (57600) than the Gyro(115200)?i noticed there is no Serial.begin(57600) for the BT in the code . Also Souldn't the "Serial" code begin with "Serial1" when talking about HC05 since it is connected in the rx1 tx1 of the mega? Thank you!

xlorianx:
Don't worry about it, i really appreciate that you took the time to help me! This second code you sent me compiles without problems, the gyroscope works as intended, but on the BT serial monitor(57600) i am getting the following characters and does not receive the attention values: ⸮"k⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮Ô⸮⸮!9⸮⸮w⸮Co⸮íg⸮9⸮⸮⸮Kʭg⸮⸮)⸮⸮= և1⸮!sȈ⸮⸮⸮⸮⸮í⸮⸮"

Could it be because the hc05 BT works on different baud rate (57600) than the Gyro(115200)?i noticed there is no Serial.begin(57600) for the BT in the code . Also Souldn't the "Serial" code begin with "Serial1" when talking about HC05 since it is connected in the rx1 tx1 of the mega? Thank you!

I'm not clear on the "Gyro(115200)" part; from the look of the code it appears to be an I2C interface and the Serial port in that code simply sends informative messages to the user. For example:

.
.
.
Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);

  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  Serial.println(F("\nSend any character to begin DMP programming and demo: "));
  while (Serial.available() && Serial.read());
.
.
.

Similarly, I didn't look that deeply at the HC05 side of things. I see the use of Serial.prints in what appears to be a purely informative messages like:

.
.
.
void setup() {
  Serial.begin(57600);
  Serial.println("Attention Values"); 
  delay(5000);
  analogWrite(throttlePin, 255);
.
.
.

and

.
.
.
            if (payloadData[28] == 4)
            {
              Attention = payloadData[29];
              Serial.println(Attention, DEC);
.
.
.

I didn't differentiate the serial port code use for each because the example code you provided didn't do any differentiating (that I could see.) I also didn't look at your Fritzing diagram; probably my bad to be fair your code did not use Serial1 (as mentioned by cattledog in reply #1; I just grabbed the code and started working without reading your reply #2. My bad, I suppose.

You can change all instances of Serial to Serial1 and change the baud rate from 115200 back to 57600 and see if that works.

The attached should address the Serial1 issue, assuming I didn’t accidentally break something else.

HC05_MPU_combined.ino (11.5 KB)

Blackfin:
The attached should address the Serial1 issue, assuming I didn’t accidentally break something else.

Wow , this is so close to working now, this new version seems to be connecting the hc05 and gyro alright, now there is absolutely nothing displayed on the 115200 nor on the 57600 serial monitors. Even though the gyro does not display any data on the serial monitor, i know for sure it’s working since i connected some leds to indicate the movement of the Gyro and they light up correctly. I am not sure if the Hc05 collects any data from the neurosky headset. Judging by the looks of it, it sends maxvalue to the throttlepin and not the attention value collected from the headset . Could it be an issue related to the Serial monitor not displaying any data? Anyway this is super close to making it work. I also made some minor adjustments to the code so it is easier to understand the goal of it. Attached the minor editted version. Thank you very much again!

HC05_MPU_combinedv2.ino (11.5 KB)

In this attempt (based on your modified version just posted), all serial “prints” are changed to the main serial monitor at 115200. The HC05 is now receive-only (no messages are sent to it…)

HC05_MPU_combinedv2.ino (11.7 KB)

Blackfin:
In this attempt (based on your modified version just posted), all serial "prints" are changed to the main serial monitor at 115200. The HC05 is now receive-only (no messages are sent to it...)

Unfortunately i can not check out this one, when i try to compile it, i am getting this error:

Arduino: 1.8.13 (Windows 10), Board: "Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"





















C:\Users\kodie\Desktop\HC05_MPU_combinedv2.5\HC05_MPU_combinedv2.5.ino: In function 'void setup()':

HC05_MPU_combinedv2.5:89:5: error: 'serialConsole' was not declared in this scope

     serialConsole->begin(115200);

     ^~~~~~~~~~~~~

C:\Users\kodie\Desktop\HC05_MPU_combinedv2.5\HC05_MPU_combinedv2.5.ino: In function 'void setupHC05()':

HC05_MPU_combinedv2.5:108:5: error: 'serialConsole' was not declared in this scope

     serialConsole->println("Attention Values");

     ^~~~~~~~~~~~~

C:\Users\kodie\Desktop\HC05_MPU_combinedv2.5\HC05_MPU_combinedv2.5.ino: In function 'void setupMPU()':

HC05_MPU_combinedv2.5:139:5: error: 'serialConsole' was not declared in this scope

     serialConsole->println(F("Initializing I2C devices..."));

     ^~~~~~~~~~~~~

C:\Users\kodie\Desktop\HC05_MPU_combinedv2.5\HC05_MPU_combinedv2.5.ino: In function 'void serialRX_HC05()':

HC05_MPU_combinedv2.5:260:29: error: 'serialConsole' was not declared in this scope

                             serialConsole->println(Attention, DEC);

                             ^~~~~~~~~~~~~

C:\Users\kodie\Desktop\HC05_MPU_combinedv2.5\HC05_MPU_combinedv2.5.ino: In function 'void data_getMPU6050()':

HC05_MPU_combinedv2.5:311:21: error: 'serialConsole' was not declared in this scope

                     serialConsole->println(F("FIFO overflow!"));

                     ^~~~~~~~~~~~~

C:\Users\kodie\Desktop\HC05_MPU_combinedv2.5\HC05_MPU_combinedv2.5.ino: In function 'void ProcessDMP(uint16_t)':

HC05_MPU_combinedv2.5:348:5: error: 'serialConsole' was not declared in this scope

     serialConsole->print("ypr\t");

     ^~~~~~~~~~~~~

exit status 1

'serialConsole' was not declared in this scope



This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Change this:

HardwareSerial *serialPC = (HardwareSerial *)&Serial;

to

HardwareSerial *serialConsole = (HardwareSerial *)&Serial;

Blackfin:
Change this:

HardwareSerial *serialPC = (HardwareSerial *)&Serial;

to

HardwareSerial *serialConsole = (HardwareSerial *)&Serial;

I changed the line and now it compiles and runs with Attention values and Gyroscope values mix- printed on baud 115200 . But it works! I will try to separate print Attention on baud 57600 and then everything should work fine. Thank you very much taking the time to help me with this ! I really owe you big time!

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.