arduino mega 2560 not working properly

You're overflowing the Serial1 software receive buffer. Don't write more than you read (for this sample code).