[solved] split two bytes


I am trying to control two servos with arduino, who recive two bytes an (uint16) form simulink. The objective is to split in two 1 byte and write the value to the servos.

This is what i tried:

void loop() {

if( Serial.available() >= 0)

short LSB = Serial.read();

uint8_t valx = LSB & 0xff;
uint8_t valy = (LSB >> 8);




The result is one servo shaking... Can you please help me?

Thank you!

Serial read only reads one byte at a time, so if you are receiving a 16 bit value then just two serial reads will do it one for each byte.

Your code got corrupted when you posted it. Did you notice the smiley?

Please edit your post above, delete out the code, click Tools–>Auto Format in the IDE, then re-copy the code into your post with code tags around it using the </> icon so it looks like


Thank you for your time, are you saing like this?

void loop() {

if( Serial.available() ) 
       int x = Serial.read();
       int y = Serial.read();

Think about it. That code is saying if one or more bytes are available then read two bytes. That is not what you want to do is it?

You want

if( Serial.available()>1 )
1 Like

Thank yoy for your help!

actually to work you have to put "2"

if( Serial.available()>= 2)
** {**
** int x = Serial.read();**
** int y = Serial.read();**

** servo1.write(x);**

** servo2.write(y);**

** }**

What the grumpy one wrote works just as well. Notice the difference between > and >=