我有這樣的MATLAB代碼:Modbus TCP和MATLAB
function [s] = serialstart(opt)
% Function for initializing a serial interface in matlab for interfacing
% Functions using the serial port must be passed the serial port object
% s in order for the serial port to be accessible.
port = 502;
s = tcpip('192.168.2.177',port);
%?????
set(s, 'InputBufferSize', 3000000);
% Initialize serial port on specified com port
date_addr = 40001;
date_num=1;
date_addr_high = floor(date_addr/100);
date_addr_low = mod(date_addr,100);
date_num_high = floor(date_num/100);
date_num_low = mod(date_num,100);
%Open serial connection
fopen(s);
% Specify Terminator
s.terminator='CR/LF';
fwrite(s,0,'char') %Transactio identifier 0x00
fwrite(s,0,'char') % Transactio identifier 0x00
fwrite(s,0,'char') % Protokol identifier 0x00
fwrite(s,0,'char') % Protokol identifier 0x00
fwrite(s,0,'char') % Data Bytes 0x00
fwrite(s,1,'char') % Data Bytes 0x06
fwrite(s,255,'char') % unit identifier 0xff
fwrite(s,3,'uint8') % Function 0x03
fwrite(s,date_addr_high,'uint8') %Register High Byte
fwrite(s,date_addr_low,'uint8') %Register Low Byte
fwrite(s,date_num_high,'uint8') %How many Register Low Byte
fwrite(s,date_num_low,'uint8') %How many Register High Byte
out = fread(s,1,'char');
fclose(s);
,但我得到如下回應:
警告:讀取失敗:指定的數據量不是 超時時間內返回期。
下面是對TCPIP對象的設置:
TCPIP Object : TCPIP-192.168.2.177
Communication Settings
RemotePort: 502
RemoteHost: 192.168.2.177
Terminator: 'CR/LF'
NetworkRole: client
Communication State
Status: closed
RecordStatus: off
Read/Write State
TransferStatus: idle
BytesAvailable: 0
ValuesReceived: 0
ValuesSent: 12
連接成功,但我沒有收到任何數據。我不知道如何收到任何日期。
編輯:
我加入這個底:
while ~s.BytesAvailable
end
s.BytesAvailable
res=fread(s,s.BytesAvailable)
fclose(s);
現在我得到任何答覆。
感謝您的回覆。我做了一個s.BytesAvailable while循環來讀取數據。我收到52個值,現在我必須找出哪個值是寄存器。 – knuppel
我建議使用['BytesAvailableFcn'](http://www.mathworks.com/help/instrument/bytesavailablefcn.html)回調函數,而不是使用'while'循環來檢查數據是否可用 - 這樣您不必一直主動檢查新數據。 –
添加此底:同時〜s.BytesAvailable 端 s.BytesAvailable 解析度=的fread(S,s.BytesAvailable) FCLOSE(一個或多個);我沒有迴應 – knuppel