When you open the serial connection, the Arduino resets itself and the bootloader waits for potential sketch upload. This adds some delay before the sketch actually runs.
Add a pause after you open the serial connection.
fopen(s);
pause(3);
There are other options:
-
Make the Arduino to announce when it’s booted up, by sending something to the PC. For example you wait until the Arduino sends an
S
. -
I am not sure if this is possible with MATLAB, but if you disable the serial’s DTR pin, the Arduino won’t auto reset.
-
Burn the code directly with the programmer, so the there is no bootloader which waits at boot. But this also prevents you from uploading the sketch via the USB.
-
A hardware solution to prevent auto reset. But this prevents the necessary reboot during the sketch uploading, so you have to time the reset manually.