4
votes

The following guide shows how to open and read fomr a serial port using matlab:

Serial fOpen

And it is done like this:

s = serial('COM1');
fopen(s)
fprintf(s,'*IDN?')
idn = fscanf(s);
fclose(s)

I have a program that continually gets the serial output and plots it:

figure
s = serial('COM11');
fopen(s)

while(true)

    if (strcmp(comsStatus, 'open') == 1)

        tline(i) = str2num(fgetl(s));
        i = i+1
        plot(tline(1:i-1))
        drawnow
    end
end

fclose(s)

What i am looking to do is automatically break out of the while loop. But there does not seem to be an easy indication of when the serial has stopped coming through. the fgetl(s) part will wait until something actually comes through. Is there a way to time this out? Is there a better way to do this?

1
Couldn't you query s.BytesAvailable and only call fgetl when s.BytesAvailable is larger than 0?H.Muster
@H.Muster I haven't tried that yet. You should add this as an answer, I would up vote it.Fantastic Mr Fox
I haven't tried this either, hence, so far it's only an idea and not a working answer. Therefore only a comment yet. Do you need an code example or can you try it on your own?H.Muster
Sorry to swoop in on this. I had done this in a prior project and was hoping to capitalize on my experience. Gotta pick up those points to catch up with you guys!Sekkou527

1 Answers

1
votes

You can modify the while loop as follows:

figure
s = serial('COM11');
fopen(s)

while(s.BytesAvailable > 0)
        if (strcmp(comsStatus, 'open') == 1)

            tline(i) = str2num(fgetl(s));
            i = i+1
            plot(tline(1:i-1))
            drawnow
        end
    end

fclose(s)

Reference: http://home.iitb.ac.in/~rahul./ITSP/serial_comm_matlab.pdf

Also from personal experience.