Incoming serial halts 2560 code

Hi Guys found this old discussion:-

where much like myself my 2560 locks up whenever I start sending serial data...

Like the other thread I to am trying to run the neopix library,.. but even when this is commented out serial data stops/hangs the 2560 dead in in its tracks.

did anyone find a solution fix to this issue

I am running the following basic program with adaptation to talk to a 20x 4 LCD display for debugging purposes:-

String str;

void setup()

void loop ()
   while (Serial.available() > 0){
       char c =;
       if (Serial.available() == 0)
           str = "";

One thing that I wonder is when I do a,.. which port is assumed,.. as I see references to serial1,2,3.... do I have to specify serial1 if trying to listen to the USB serial port,... BTW the Rx onboard LED flashes away 10 to the dozen,.. ( indicating serial data IS being received.. I assume ).

Yours Baffled

I believe Serial is for the USB, which also uses pins TX0/RX0.

And on the mega, Serial1, Serial2, Serial3 correspond to pins TX1/RX1, TX2/RX2, TX3/RX3.

Btw you don't need that break; in your code, it will exit the loop on its own the way you have it coded.

I'd be wary of how long the string coming from serial is when printing to the lcd. I'd also maybe recommend listenign for a delimiter, such as carriage return, then concatenating your string, checking its size and printing to lcd.

Welcome to the Forum. First, you should read the two posts at the top of this Forum by Nick Gammon on how to post to the Forum, especially for posting code using the code tags (</>). Second, you’re going to find that, while the String class makes it easier to work with string data, that class is a real resource hog. You will save a noticeable amount of memory if you use char arrays instead.

diyhouse: where much like myself my 2560 locks up whenever I start sending serial data...

I can't relate that comment to the code you have posted. In what sense does it "lock up" ?

You are using a very strange way to receive the data. Have a look at the examples in serial input basics.

What happens if you change your WHILE to IF ?


Thanks for the responses and clarifications guys,… ( original post corrected ). My goal,… is to drive a NeoPix LED string, by taking screen shot data from the display and sending serial data to the 2560 to determine how to drive the LEDS.

My code as presented here was the lowest common denominator of what does not appear to work,… basically the code never sees valid serial data even though the Rx LED flashes 10 to dozen.

I have also noticed that when I stop and start the serial stream,… the Arduino goes through a full reset… indicating the code has really lost the plot…

The formal code I am trying to get running is as follows.

//Ambi: AmbientNeoPixel Arduino Sketch
//Created By: Cory Malantonio

#include <Adafruit_NeoPixel.h>
#define PIN 2
#define N_LEDS 30
Adafruit_NeoPixel strip = Adafruit_NeoPixel(N_LEDS, PIN, NEO_GRB + NEO_KHZ800);

int r[11]; // array for each color value
int g[11];
int b[11];

void setup() {
  strip.begin(); // prep the neopixel;

void loop() {

  if (Serial.available()>=31) {
    if ( == 0xff){
            for (int x = 1; x < 11; x++){
        r[x] =; // read in the values from processing
        g[x] =; // in the same order we sent them
        b[x] =;

        r[x] = constrain(r[x], 0, 255); // just incase any values slip away
        g[x] = constrain(g[x], 0, 255);
        b[x] = constrain(b[x], 0, 255);


int Xval = 1;             // count to 30
int Yval = 2;             // while loading rgb values
int Zval = 3;             // into 3 led's at a time

for (int z = 1; z < 11; z++){

strip.setPixelColor(Xval, r[z], g[z], b[z]);
strip.setPixelColor(Yval, r[z], g[z], b[z]);
strip.setPixelColor(Zval, r[z], g[z], b[z]);

Xval = Xval + 3;
Yval = Yval + 3;
Zval = Zval + 3;
};       //output to the neopixel
  delay(20);          //for safety

During the debugging phase I added the LCD libraries to log what was going on,… ( because the serial port is taken by the screen neoPix data stream ) which is where I eventually found that the Arduino never sees there being serial data,. let alone 0xFF,… because it just crashes the code when the serial stream is turned on,… and I am now completely baffled.

So fundamentally Rx flashes away,… but no data appears to be available to be read… beats me where the data IS going…

Just looked at the board component silk screen,.. and the comms ports show

TX0/RX0, TX3/RX3, TX2/RX2, TX1/RX1..

Does Serial.available() check the USB serial input lines,... ( yes,.. clutching at straws... )


Serial.available() checks RX0 for incoming data. If USB cable is connected and PC is transmitting, it will read that data and make it available for assignment to a variable with

diyhouse: ... ( original post corrected ).

That is just confusing.

What did you change - can you show it in colour? Or preferrably reinstate the original text and post the changes in a new post.


Sorry,.. when I say corrected,.. all I did was put the code into "code" quotes,.. the actual text and source I did not change.

My original problem is still the same,... sending serial data stop/hangs my arduino 2560,.. and when I stop the serial data,.. the Arduino resets....

I include two libraries with my test code,.. the serial NeoPix,.. and the LCD library,.. ( the LCD library is purely for debug purposes as when I set the system up the USB serial port is re-assigned to another process.., and hence not accessible from the Arduino 2560.

Hi diyhouse

One of the comments says that the data is being sent to the Arduino from Processing. If so, can you please post the Processing program.

Your code is expecting a byte of 0xFF as the start flag for the data packet. As a test, can you change this to 0x7F (on the PC and in the Arduino program) and see if that makes a difference.



If you have start and end markers surrounding your data the 3rd example in serial input basics should meet your requirement reliably.


This is the processing script that I run,… to send the RGB data about the screen colour intensity etc…

the complete project can be found here:-

As far as I can tell,… “processing” is sending the required data,… I just don’t know what is going down the serial wires,… for that I would ideally need a logic analyser or alike

/*  Ambi2: AmbientNeoPixel Processing Sketch
**  Created by: Cory Malantonio
**  ambiArray is based on a design by Rajarshi Roy

import cc.arduino.*;
import java.awt.Robot;
import java.awt.AWTException;
import java.awt.event.InputEvent;
import java.awt.image.BufferedImage;
import java.awt.Rectangle;
import java.awt.Dimension;
import processing.serial.*;

//-------Set Resolution Here-----//
int resX = 1920;
int resY = 1080;

int sectW = resX / 10;  //Section Width for the 10 sections
int SectRx = sectW / 4; //Section resolution for x
int SectRy = resY / 4;  //Section resolution for y

Serial port;
Robot GrabRGBval;

void setup()
  port = new Serial(this, Serial.list()[2], 9600);
  //Serial.list()[#], # = usb device number
    GrabRGBval = new Robot();
  catch (AWTException e)
    println("Robot class not supported by your system!");
  size(200, 200);

void draw()
  int pixel;

  float[] rA = new float[11];
  float[] gA = new float[11];
  float[] bA = new float[11];
  int[] reso = new int[11];
  for (int Ar = 1; Ar < 11; Ar++){  //load the resolutions into the array
  reso[Ar] = sectW * Ar;              //192 is 1/10th of the 1920 resolution
  float r=0;
  float g=0;
  float b=0;
 BufferedImage screenshot = GrabRGBval.createScreenCapture(new Rectangle(new Dimension(resX, resY)));
for (int LED = 1; LED < 11; LED++){
  int x=0;
  int y=0;
  //reso array increments in 10ths of the 1920 resolution, starting at 0
  for ( x = reso[LED-1] ; x < reso[LED]; x = x + 4) {  //"x + 4" is skipping pixels
    for (y = 0; y < resY; y = y + 4) {                 // to help it run faster
      pixel = screenshot.getRGB(x, y);
      r = r+(int)(255&(pixel>>16));
      g = g+(int)(255&(pixel>>8));
      b = b+(int)(255&(pixel));

  r=r/(SectRx*SectRy); //48 is 1/4th each 10th of the screen. Above we are skipping pixels
  g=g/(SectRx*SectRy); //we are left with 1/4th the pixels.
  b=b/(SectRx*SectRy); //270 is 1/4th of the 1080 resolution
rA[LED] = r;
gA[LED] = g;
bA[LED] = b;


   port.write(0xff); //write marker, arduino is looking for this
   for (int Br = 1; Br < 11; Br++){
  delay(10); //delay for safety

    for (int cOne = 1; cOne < 11; cOne++){  
  stroke(rA[cOne], gA[cOne], bA[cOne]);
  rect((cOne - 1)*20, 0, cOne*20, 200);
  fill(rA[cOne], gA[cOne], bA[cOne]);
  rect((cOne - 1)*20, 0, cOne*20, 200);

Do you have a USB to serial converter? If so, you could connect it to one of the other serial ports on the Mega and use a simple program to check what data the Mega is receiving from Processing.

diyhouse: As far as I can tell,.. "processing" is sending the required data,... I just don't know what is going down the serial wires,..

Have you tried the code in serial input basics?

You could easily modify it to print each character (or its ASCII value) as it is received.

If your Processing code does not add an end-marker I suggest that you modify it so it does so - it will make life much easier for the Arduino.


Now there's a thought,... Yes I do have a USB to serial converter,...

My only off the cuff thought is,.. the serial data I am sending,.. is over the USB port,... so not RS232,.. and my converter takes RS232 and converts it to USB compatible levels.. so struggling to see how this would help me,.. am I missing the bloomin' obvious,....

With regards Robins comments about stop and start characters,.. yes I take your point,.. this app is a little basic,.. and prone to errors as no overall packet checks,.... My plan is once system is running,.. ( and I am receiving some sort of serial data I can process ) I was going to look into some design improvements,.. as searching for 0xFF is hardly unique in the characters that can be received.

And Yes,.. I think back to serial basics and see what is being transmitted,.. and see if I can actually receive 'anything',...


The Serial port on the Mega is the one connected to USB and via that your PC.

But the Mega has three more ports, Serial1 to Serial3, that come out on marked pins.

If your converter is a TTL-level converter (rather than true RS232 levels) you can connect it to one of those ports. You would need a terminal program like PuTTY running on the PC to see what was received. And a short program to read each byte from Serial and write it straight out on Serial1, say.

Actually, since you are dealing with binary RGB values, your test program should probably print the received data to Serial1 as hex.

Ok,… here is my latest attempt at getting something to read on the serial port:-

A couple of test lines to show thing started,… with a counter top left to show things a ticking along…

This works as before as with above examples, so no change:-

I must be doing something wrong,…

Arduino loaded with code sketch as below,… programmed from PC over USB port connection…
Display text updates on top two line ( of 4 line ) display,…

Start sending serial data,… Rx LED starts flashing…counter immediately stops!!

Stop serial data,… slight pause 2 -3 seconds Display resets,… and counter resumes from ZERO,… so full reset.

Any thoughts anyone

/*-----( Import needed libraries )-----*/
#include <Wire.h>  // Comes with Arduino IDE
// Get the LCD I2C Library here: 
// Move any other LCD libraries to another folder or delete them
// See Library "Docs" folder for possible commands etc.
#include <LiquidCrystal_I2C.h>

int LCDadd = 0x27;
/*-----( Declare objects )-----*/
// set the LCD address to 0x20 for a 20 chars 4 line display
// Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(LCDadd, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

char receivedChar;
boolean newData = false;

int counter = 0;

void setup() {
  // put your setup code here, to run once:
  lcd.begin(20,4);           // initialize the lcd for 20 chars 4 lines and turn on backlight

// NOTE: Cursor Position: CHAR, LINE) start at 0  
  lcd.setCursor(3,0); //Start at character 3 on line 0
  lcd.print("Hello, steve!");
  lcd.print("<Arduino is ready>");

void loop() {

void recvOneChar() {
 if (Serial.available() > 0) {
 receivedChar =;
 newData = true;

void showNewData() {
 if (newData == true) {
 lcd.print("This just in ... ");
 newData = false;

In response to HS comment and serial ports,...

My serial data,... (from PC to transmit the RGB data) data is being transmitted over a USB port and being received into the Arduino USB serial port,.. RX LED flashes,... my PC does not have a true external RS232 port.... hence using USB,... and it seems to be squirting something as Rx LED flashes,.. unless this is a "red herring".

Am I missing the obvious or making an incorrect assumption.

Don't know if this makes any difference,.. but my Arduino 2560 board is a MEGA ADK for Andriod,.. so has an extra USB port on PCB to enable it to connect to a Android compatable device.

Looks like there may be incompatibility between Processing and Mega specifically.