0
votes

I am writing a script to talk to an arduino. The arduino listens for communication on the serial port and acts according to the command received.

If I work in the Matlab command prompt, everything works as expected: I send the commands:

s = serial('COM4','BaudRate',9600, 'Terminator', 'LF/CR');
fopen(s);
fprintf(s, '%s','start');
pause(10;
fprintf(s, '%s','stop');
fclose(s);

and the arduino reacts by enabling a pump for 10 seconds before switching it off.

If I use the same exact code from a script, nothing happens. The problem seems to reside in the fprintf because if I open the serial communication from the script (and leave it open), I can send the start/stop commands from the prompt and it works.

I have tried adding a line terminator to the script

fprintf(s, '%s \n','start');

but this again does nothing (although it works fine from command prompt).

Has anyone experience the same issue?

1

1 Answers

1
votes

It turns out the source of the problem is the very long time taken by the fopen function to work. I had previously tried to add a 1 second pause after it, but seeing no improvement I had removed it. Now I just tried adding even more time (currently 3 seconds) and the script executes correctly.

To summarize: if you are having the same issue, add a

pause(3)

between the fopen and any other serial port command, and the script should work fine.