Touch Screen Serial Issues

I am using a serial touchscreen with an arduino mega and am having some problems reading touch coordinates from the screen. The screen works fine with serial commands sent from the computer, but when the commands come from arduino, about 50% of the bytes are 0xFF (-1, aka no data) or incorrect.

The screen sends 2 integers (x coordinate, y coordinate) over serial with the most significant bytes first. The first bytes tend to mess up more often. When the touch coordinates are small, it works better. Here is the relevant part of code:

void getTouch(int *x0_touch, int *y0_touch){
 
 Serial1.flush();
 Serial1.write(0x6F); //Tell screen to send touch coordinates
 Serial1.write(0x01); //Tell screen to send touch coordinates
 while(Serial1.available() < 1) {}
 delay(30);
 
 char a = Serial1.read(); //x coordinate, high byte
 char b = Serial1.read(); //x coordinate, low byte
 char c = Serial1.read(); //y coordinate, high byte
 char d = Serial1.read(); //y coordinate, low byte

 *x0_touch = a;                           //Put bytes back into integer form-- this part works because if I put my own values
 *x0_touch = (*x0_touch << 8) | b; // in instead of reading them, it comes out right
 *y0_touch = c;
 *y0_touch = (*y0_touch << 8) | d;

I’ve messed around with Serial1.available() but with no luck. Delays between Serial1.read()'s didn’t work either.

Any suggestions?

Any suggestions?

Yes.

 Serial1.flush();

Quit doing this, unless you have very good reason to. If you have such a reason, there should be a comment explaining WHY you need to throw away perfectly good data unused.

 while(Serial1.available() < 1) {}
 delay(30);

Wait until there is at least one byte to be read, then wait some more. Why?

 char a = Serial1.read(); //x coordinate, high byte
 char b = Serial1.read(); //x coordinate, low byte
 char c = Serial1.read(); //y coordinate, high byte
 char d = Serial1.read(); //y coordinate, low byte

Once there is a byte to be read, read all 4 of them. Do you see a problem with that?

Try this:

 while(Serial1.available() < 4)
 {
   // Do nothing
 }

 char a = Serial1.read(); //x coordinate, high byte
 char b = Serial1.read(); //x coordinate, low byte
 char c = Serial1.read(); //y coordinate, high byte
 char d = Serial1.read(); //y coordinate, low byte

I got it working now.

Thank you so much for the help!