Wrong character tranmission between 2 bluetooth modules

Im doing a project which communicates between arduino boards ( Mega and Uno). Bluetooth modules are used both HC-05. I want to send analog value from potentiometer in the master to the slaver
-bluetooth master with Mega

  • the slaver is connected with UNO.
    The connection between bluetooth modules is successful. However, after I twist the potentiometer, the data displayed in the slaver (UNO) is not correct. For example, in the Master, the data that I want to send from 0-180 as degrees of servo and in the Slaver, the data displayed only 3 numbers 0, 248 and 128
    Code for Master
#include <SoftwareSerial.h>

#define BT_SERIAL_TX 10

#define BT_SERIAL_RX 11

SoftwareSerial BluetoothSerial(BT_SERIAL_TX, BT_SERIAL_RX);

int potpin = A0;

int val;

void setup()

{

Serial.begin(9600);

BluetoothSerial.begin(38400);

}

void loop()

{

val = analogRead(potpin);

val = map(val, 0, 1023, 0, 179);
//val=5;
BluetoothSerial.print(val);
Serial.println(val);
delay(100);

}

Code for Slaver

#include <SoftwareSerial.h>

#define BT_SERIAL_TX 10

#define BT_SERIAL_RX 11

SoftwareSerial BluetoothSerial(BT_SERIAL_TX, BT_SERIAL_RX);

#include <Servo.h>
//char val=' ';
int val;
Servo myservo;


void setup()

{

Serial.begin(9600);

BluetoothSerial.begin(38400);

myservo.attach(6);

}

void loop()

{

if (BluetoothSerial.available()>0)

{
val = BluetoothSerial.read();
//int gt=val-'0';
//Serial.println(gt);
//myservo.write(gt);
Serial.println(val);

myservo.write(val);

}

}

I doubt that do it put the correct baud rate for all bluetooth modules or I get some mistakes to define type of data. Please share your wisdom to solve my problem.
Sincere thanks!

if (BluetoothSerial.available()>0)

{
val = BluetoothSerial.read();

You know that there is data to read. Therefore, the read will always work. Therefore, the data will always be in the low order byte of the variable. Therefore, you don't need a multibyte type for the variable. Therefore, int is the wrong type.

If the master is sending a value of 85 for the angle, it will send '8' and '5'. You are then sending the servo to position '8' and then to position '5'. That hardly makes sense.

Send data using BluetoothSerial.println(val);. Then, read and store the serial data that arrives, in a character array, adding a NULL after each character. When the carriage return or line feed arrives, do not store them. Instead, convert the string to an int, using atoi() and send the servo to that position.

https://forum.arduino.cc/index.php?topic=288234.0