質問

I am trying to build a serial port device in Matlab. I have 2 devices 'COM1' and 'COM2'. 'COM1' ASYNCHROUNOUSLY writes data into the serial port 'COM2'. I have alternative names for 'COM1' and 'COM2', as follows:

global serialcom
serialcom=serial('COM1'); %Serial Communication portal COM 1
global testdummy
testdummy=serial('COM2'); %Serial Communication portal COM 2

The number of Bytes in the input buffer of testdummy which triggers the testdummyfunction is 2, and this is specified using the testdummy.BytesAvailableFcnCount field (below).

testdummy.BytesAvailableFcnMode = 'Byte';
testdummy.BytesAvailableFcnCount = 2;
testdummy.BytesAvailableFcn = @testdummycomfunction;

I have a function "testdummyfunction" on the testdummy side which is triggered using the BytesAvailable callback property in Matlab.The structure of this function is as follows:

function testdummyfunction(testdummy,BytesAvailable)
% TESTDUMMYFUNCTION(testdummy,...BytesAvailable)
% INPUTS:
% TESTDUMMY:refers to the serial port testdummy
% BYTESAVAILABLE:Refers to the callback function 'BytesAvailablefunction'

    global serialcom;
    data_string=fscanf(serialcom,'%c',2); %Reads the data sent form serialcom

end

Now, suppose the string which i print into testdummy is greater than 2 bytes, say 10 bytes. Since i write the data into testdummy asynchronously, the first time the bytes available function is triggered, 2 bytes are read from it.(these 2 bytes act like a syncbyte for me, if they are correct, it means that i can read the rest).

Now, i want to change the testdummy.BytesAvailableFcnCount property to 8; so that i can read the reamaining 8 bytes. However, Matlab says that i must first close the serial port to change the testdummy.BytesAvailableFcnCount property. If i do this, then everything in my input buffer is lost! How do i still ensure that i change the property and not lose the data in the input buffer?

役に立ちましたか?

解決

You could just set your BytesAvailableFcnCount to 1. Then use a variable like global serialmode = 1; to switch between different modes:

function testdummyfunction(testdummy,BytesAvailable)
    global serialcom;
    if (serialmode==1 && get(serialcom,'BytesAvailable')>=2)
        data_string=fscanf(serialcom,'%c',2); %Reads the data sent from serialcom
    elseif (serialmode==2 && get(serialcom,'BytesAvailable')>=8)
        data_string2=fscanf(serialcom,'%c',8); %Reads the data sent from serialcom
end

Alternatively, a quicker solution if you always send 10 bytes is simply to set BytesAvailableFcnCount to 10, then read 2 then 8 bytes.

Another quick solution would be to set your remote device to send 8 bytes instead of 2 (you just send 6 zeros after the initial 2 sync bytes), and just use BytesAvailableFcnCount = 8 for everything.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top