IMU data not printed when there are some other data is also printed

hello everyone,

I am having problem with transmitting IMU data along with other data via serial communication in Arduinio mega.
So, when I have only IMU data, it prints the IMU data properly but if i have some other data also being printed, see below i am also printing random number(this is just an example, actually i am transmitting encoders readings), then only random number is getting printed. It does not print any imu data at all.

I have to transmit around 10 data from IMU but here i am trying with only one and it is still not working.

#include <UM7.h>  // um7 arduino binary parser
UM7 imu;
float random_number1;

void setup() {  
  // put your setup code here, to run once:
  Serial.begin(57600);
  randomSeed(analogRead(0));
  Serial2.begin(57600);

}

void PublishImuData()
{
 if (Serial2.available() > 0) {
    if (imu.encode(Serial2.read())) {  // Reads byte from buffer.  Valid packet returns true.
     Serial.print("quat A = ");
     Serial.println(imu.quat_A/29789.09091);   
}
}}

void loop()
{  
  PublishImuData();
  random_number1 = random(10,300);
  Serial.print("random number = ");
  Serial.println(random_number1);
}

Because the random number printing is slowing down the processing of IMU bytes to below the rate
they are arriving. Change the 'if' at the head of PublishImuData() to a 'while' so it can keep up. Change
the baud rate for Serial to 115200 will help too.

random_number1 = random(10,300);

The random() function doesn't return a float.

while (Serial2.available() > 0)

This worked. Thank you MarkT. But it lowered the other data frequency significantly. Is there a way to resolve this? Can i achieve same result without using while?

Actually I am connecting all the data from Arduino to ROS(code is changed as per ROS but idea remains same). I have 4 publisher and 3 subscriber connected via serial communication. So, rate of other data transmission is also important to me. if you wish to review my code in ROS, i can upload it.

Also, regarding baud rate, if i keep it to 115200, it does not work for me.

Thank you for pointing this, PaulS. I believe it should be long.

But it lowered the other data frequency significantly.

The only other thing you are doing is generating and printing a random number. You do that after every character received.

You could change the while and if statement to:

while (Serial2.available() > 0 && !imu.encode(Serial2.read())
{
}

so that the code reads all available data from one packet, and then ends, rather than reading all available data for n packets.