bluetooth doubt

int ledPin = 13;  // use the built in LED on pin 13 of the MEGA
int state=0 ;
int flag = 0;        // make sure that you return the state only once

void setup() {
    // sets the pins as outputs:
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, LOW);

   Serial.begin(9600);
      Serial2.begin(9600);// Default connection rate for my BT module
     
     Serial2.println("Bluetooth On please wait...."); 
}
void serialEvent2(){
Serial.print(Serial2.read());//for debugging
}

void loop() {
    
    //if some data is sent, read it and save it in the state variable
    if(Serial2.available() > 0){
      state = Serial2.read();
      flag=0;
    }
    // if the state is 0 the led will turn off
    if (state == 0) {
        digitalWrite(ledPin, LOW);
        if(flag == 0){
          Serial2.print("LED: off");
          flag = 1;
        }
    }
    // if the state is 1 the led will turn on
    else if (state == 1) {
        digitalWrite(ledPin, HIGH);
        if(flag == 0){
          Serial2.print("LED: on");
          flag = 1;
        }
    }
}

Hey guys,Im interfacing a HC 05 bluetooth module to my arduino mega 2560 connected at serial port 2 the bluetooth module is paired .I use blueterm app as a terminal here I receive the message ( Bluetooth On please wait....) then i press 1 or 0 nothing happens

I suggest you get rid of serialEvent2() and just add debugging code into the code in loop() - Serial.println(state);

serialEvent() is just a nonsense that is basically equivalent to if (Serial.available() > 0) {

…R

Hey robin thanks for the reply,i have done the needful,I receive "Bluetooth On please wait...." on the bluetooth terminal but on the receiving side i receive garbage value suppose if i press 0 i get 64 and again if i press it gives me 255 very random in nature.Is it a issue of baudrate?.Please do help struggling since past 3 days to get it right .Also my module blinks slowly like twice one cycle is it okay or should it be steady.Im using this module from jy- mcu

Eimathew:
Is it a issue of baudrate?.

If it is sending data perfectly it should be able to receive it.

Post your latest code and explain in detail what data is being sent to the HC05 for reception in the Arduino and what software and hardware is doing the sending. Saying "if i press 0 i get 64 etc." is not sufficiently informative.

...R