Serial read is not working as expected on arduino mega 2560.

Hello all,

I had an application that worked perfectly 6 months ago. Right now I wanted to continue the development but suddenly nothing works. After a little debug I found out that the problem is the Serial1,2,3 of the board. The Serial works perfectly but the other are sending data even that there is nothing. I reduced all code at the reading part:

  while(Serial2.available() > 0)
    {
      b2[i++] = Serial2.read();  // read all data in the buffer 
      Serial.write(b2[i-1]);    
    }

As you see I expect something on serial2 and print the result to serial monitor to see what is happening. I receive only null characters. The same behaviour is obtained if I used a bluetooth module on Serial1, the bluetooth only sends NULL even that I have only a wire conected to the RX pin of serial2.

Can someone tell me what is happening. The serial0,2,3 are set at 9600 baud rate, and the serial 1 at 115200 baund rate for bluetooth.

moiderator: double post removed

Manusharian:  while(Serial2.available() > 0)    {      b2[i++] = Serial2.read();  // read all data in the buffer      Serial.write(b2[i-1]);        }

Are you getting your indexing tangled up.

Why not keep it simple

  while(Serial2.available() > 0)
    {
      b2[i] = Serial2.read();  // read all data in the buffer 
      Serial.write(b2[i]); 
      i ++;   
    }

Also you don't seem to check if i goes out of bounds.

...R

      b2[i] = Serial2.read();  // read all data in the buffer

No, it does not. It reads one byte, if there is one, and stores that in the low order byte of the int that it returns.

Since you haven't shown us what type b2 is, I'll guess float. It is, of course, nonsense for you to be using floats.

It is also nonsense to be using Serial.write() to send binary data to the serial monitor application, which can only handle ASCII data, sent using Serial.print().

Hello and welcome,

Try to add in setup() :

pinMode( 15, INPUT_PULLUP );
pinMode( 17, INPUT_PULLUP );
pinMode( 19, INPUT_PULLUP );