Matlab Arduino Multiple Bytes over Serial

I know this has been covered to some degree, but after several days of searching I felt it was time to make a new thread. I am trying to get Matlab to send a 16 bit (2 byte) number to Arduino, and then for Arduino to echo that number back to Matlab. The number can be anywhere between 0 and 65536. So far I have been able to get Matlab to send an 8 bit (1 byte) number to Arduino and have Arduino send it back. The code is below and was adapted from Interacting with an Arduino Using the Matlab Serial Commands - File Exchange - MATLAB Central.


clear all;

s1 = serial('COM3');    % define serial port
s1.BaudRate=9600;               % define baud rate
set(s1, 'terminator', 'LF');    % define the terminator for println

try                             % use try catch to ensure fclose
                                % signal the arduino to start collection
w=fscanf(s1,'%s');              % must define the input % d or %s, etc.
if (w=='B')
    display(['Collecting data']);
    fprintf(s1,'%s\n','B');     % establishContact just wants 
                                % something in the buffer

Answer = fscanf(s1)


catch me
    fclose(s1);                 % always, always want to close s1


int ledPin=13;
int val;

void setup() {

  // start serial port at 9600 bps:
  establishContact();  // send a byte to establish contact until receiver responds

void loop() {

  val =;



void establishContact() {
  while (Serial.available() <= 0) {
    Serial.println('B');   // send a capital B

I know that I need to read in each byte individually in Arduino and construct a 2 byte number before sending it out (something like what I have below) but I have not been able to get any variation of this to work.

in Arduino

    for (int i=0; i<2; i++) {
      b[i] =;
    val = b[0]+b[1]*256;

Also, the first time I run the Matlab code the number received from serial is usually 66 (ASCII for B), but after that I can run the Matlab code again and again and get whatever I sent as long as it is between 0 and 255. I think I can fix this with the proper use of delays, but I have not attempted this yet.

    val = b[0]+b[1]*256;

You are multiplying the wrong byte by 256.