0

I have a very simple code in MATLAB for a laser device which I need to use. Here's the code:

% creating a serial port object
s = serial('COM3');

% opening the port
fopen(s);

% enabling the port
fprintf(s, 'e');

% sending the power to the laser
fprintf(s, 'a738.8889');

% disabling the port
fprintf(s, 'd');
fprintf(s, 'z');

fclose(s);
delete(s);

The code works perfectly fine when I write them one by one from the command window, but it's not working when I put the whole code in either a script file or a function file.

I don't get any errors or any other messages from MATLAB when I run the script or the function. Any ideas why?

Thank you.

7
  • There shouldn't be any output except for the data on COM3. Do you see that output?
    – Suever
    Mar 15, 2017 at 15:02
  • 2
    Maybe it needs some delays for the port to be ready. Executing line by line gives a lot of time between instructions for the port to get ready but executing in sequence might be too fast.
    – user2261062
    Mar 15, 2017 at 15:02
  • @Suever well the laser is visible, so if it works I should be able to see the laser (which I can't)
    – RedHood148
    Mar 15, 2017 at 15:03
  • @SembeiNorimaki so you suggest I put a pause(3) before writing to the port?
    – RedHood148
    Mar 15, 2017 at 15:04
  • 2
    There is also a possibility, that laser is turned on and immediately turned off (when you run it as a script). Do the commands fprintf(s, 'd'); and fprintf(s, 'z'); turn the laser off? I suggest you add pause(3) after every command (in case adding it before writing to the port doesn't work).
    – Rotem
    Mar 15, 2017 at 17:20

1 Answer 1

0

So I tried delaying the commands and the script works now. Apparently when the commands are being executed in the script, it is too fast for the device to read them all and that is why it wasn't working.

2
  • Actually @Rotem suggestion also makes a lot of sense. If the commands fprintf(s, 'd'); and fprintf(s, 'z'); turn off the laser, or if the laser is automatically turned off when the port is closed, then your code was maybe working but just for very short time.
    – user2261062
    Mar 16, 2017 at 11:01
  • @SembeiNorimaki yes, I actually thought of that as well but then I tried the code without the last commands and it didn't work again
    – RedHood148
    Mar 17, 2017 at 9:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.