1
votes

I have been reading several threads but I am still not sure how to accomplish this. I am reading some values in Arduino with analogRead(), so I am getting values between 0-1023 and I am sending them to Matlab via Serial Communiaction. I am currently using Serial.print(), but I have read that it is a much more efficient way to use Serial.write(): by packing first the value into bits and only sending the MSB and the LSB. This way I will use less bits to send one value than in the case of using Serial.print.

The thing is that I don't know how I can pack the values (0-1023) in Arduino to send the MSB and LSB and then unpacking them in MATLAB to define the integer value again.

Coud you please give me a hand?

Thanks in advance

1

1 Answers

0
votes

First in C/C++ on the Arduino, you can get the most significant bit (MSB) or least significant bit (LSB) via the bitwise operations of bit shifting and bit masking:

const word Value = 1000;   // Could also be an int or an unsigned int, [0-1023]
byte MSB = Value >> 8;     // Right shift
byte LSB = Value & 0x00FF; // Mask

However, Arduino, being Arduino, has functions for these: highByte and lowByte return the MSB and LSB of a value, respectively.

I can't really say if using Serial.Write will be faster for you. If you're sending lots of data to Matlab, it's best to limit the number of calls to either Serial.Write or Serial.Print. You can do this by creating a buffer (a byte array), sticking all of the data in it, and then passing the upper to Serial.Write (see the documentation for the overloaded version of this function).

On the Matlab side there are equivalent bitwise functions, just don't expect them to be as efficient as their C counterparts. They are useful for testing an prototyping though. For example, you can reproduce the above C code in Matlab with:

Value = uint16(1000);
MSB = bitshift(Value,-8); % Right shift
LSB = bitand(Value,255);  % Mask

You "reassemble" your two-byte value by reversing the bit-wise operations:

Value = bitor(bitshift(MSB,8),LSB)

In C this is just (MSB<<8)|LSB and you can implement the above more efficiently in Matlab with:

Value = MSB*256+LSB