I am doing some computations on Matlab and I need to send those values to an Arduino Leonardo through USB serial connection. I need to send 2 variables which can vary from -400 to +400. I'm saying their values because I was able to do this with small positive values (unsigned byte), but not larger and negative numbers. Please help! Thank you
You cannot send larger values because byte only covers the range from 0-255.
To send larger values, you can break your int variable into 2 byte variables. Here's an example:
// On Arduino int myVar = -123; byte myVar_HighByte = myVar>>8; // get the high byte byte myVar_LowByte = myVar; // get the low byte // x86 compatible machines are little-endian so we send the low byte first Serial.write(myVar_LowByte); Serial.write(myVar_HighByte); % On MATLAB s = serial('COM10') fopen(s) myVar = fread(s,1,'int16')
Disclaimer: Syntax might not be entirely correct, since I have no MATLAB or Arduino near me when I typed this. But you should get the idea. ;-)
Edit: On second thought, it might be easier to use a pointer.
// On Arduino float myFloat = 3.14159265359; byte* ptr = (byte*) (&myFloat); Serial.write(*ptr++); Serial.write(*ptr++); Serial.write(*ptr++); Serial.write(*ptr); % On MATLAB s = serial('COM10') fopen(s) myVar = fread(s,1,'float')
Having said that, you will still have to take care of the endianness, if you use a different microcontroller.
If you want to send your data directly from Matlab to the Arduino, you can try using the "Matlab Arduino Support package". It lets you read/write pins on the arduino directly from Matlab command line or script just like you would with a VERY LOW END Data Acquisition card.
This has the advantage of removing the burden of managing the serial communication. I don't know how it handles large numbers though.