Send data from MATLAB to Arduino Uno via serial communication

Hi all, my arduino can receive the data from MATLAB. However, the arduino cannot conserve the received data. Below is my MATLAB and arduino code:

arduinoCom = serial('COM6','BaudRate',9600);
sendData = 5;
fprintf(arduinoCom,'%i',sendData); %this will send 5 to the arduino

Arduino code:
int val;
void setup() {
void loop()
if (Serial.available() > 0)
val =;

In this case, I send a value "5" from MATLAB to arduino via serial communication. If there is no serial data from MATLAB, the value of "val" variable turn to zero. How I can conserve the "val" variable value until the next input from MATLAB. Thank you

If no serial is available no is performed and val ought to stay untouched.

What do I miss?


Your question may be quite wide. You´ll need to be more specific.

One thing is to store "5", another thing is to store a small group of numbers (and do something with them) and a third thing is to store a large amount of data.

I suggest you taking a look at this topic that may help you on the first steps:

Serial Input Basics - updated

+1 for Robin2's serial input basics.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.