The bluetooth code doesn't works on MEGA2560 need help please

Hi,
the serial monitor attached.
Thanks
Adam

#include "SoftwareSerial.h" // remove the inverted commas after you copy the code to the IDE
SoftwareSerial BT(16, 17);   ////// WAS :10 , 11
// creates a "virtual" serial port/UART
// connect BT module TX to D10
// connect BT module RX to D11
// connect BT Vcc to 5V, GND to GND
int LED = 14;
void setup()
{
  Serial.begin(9600);
  Serial2.begin(38400);
  Serial.println("setup");
  // set digital pin to control as an output
  pinMode(LED, OUTPUT);
  // set the data rate for the SoftwareSerial port
  BT.begin(38400);
  delay(100);
  // Send test message to other device
  BT.println("Hello from Arduino");
}
char a; // stores incoming character from other device
void loop()
{

  while (!BT.available())
  {
    Serial.println("NO BT!");
  }
  if (BT.available())
    // if text arrived in from BT serial...
  {
    a = (BT.read());

    Serial.print("a=(BT.read())");
    Serial.print(a);

    if (a == '1')
    {
      digitalWrite(LED, HIGH);
      BT.println("LED on");
    }
    if (a == '2')
    {
      digitalWrite(LED, LOW);
      BT.println("LED off");
    }
    if (a == '?')
    {
      BT.println("Send '1' to turn LED on");
      BT.println("Send '2' to turn LED on");
    }
    // you can add more "if" statements with other characters to add more commands
  }
}

pp4

Why are you using software serial on a Mega?

What are you using Serial2 for?

Comments should match code, or they're utterly worthless

1 Like

Thanks.
Its because I used Serial2 no work.

Why about Serial3?

1 Like

this code used to test the Serial2 and 3, all no work.

char Incoming_value=0;
int LED = 16;
void setup() {
Serial.begin(9600);
Serial.print("SETUP!");
Serial3.begin(38400);
pinMode(LED,OUTPUT);

}

void loop() {
  if(Serial3.available()>0)
  {Incoming_value=Serial3.read();
  Serial.print(Incoming_value);
  Serial.print("\n");

  if(Incoming_value=='1')
    digitalWrite(LED,HIGH);
   else if(Incoming_value=='0')
   digitalWrite(LED,LOW); 
    
    }
}

Please get used to the concept that phrases like "it doesn't work" or "it no work" without some explanation are utterly useless here, and that you will get ignored if you continue to post them.

The default communication baud rate (as opposed to AT mode baud rate) is 9600. Did you use AT mode to change the baud rate?

It is silly to use software serial on a Mega. Anyway there are only certain pins that would work and 16 and 17 are not among them. Look at the SoftwareSerial reference.

Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

1 Like

Thanks.
the result posted in #1.
The code in #5 just printed one 'setup'.

Great!
It is the baud rate matter.
Thank you!