Matlab串口读取错误
Matlab串口读取错误)
fwrite(scom,uint8(hex2dec(Moter_Monitor(Moto_Num))));
outdec = fread(scom,17,'uchar');
outhex = dec2hex(outdec)
outstr = reshape(outhex.',1,[]);
MotoHz = hex2dec(outstr(7:10))/10; %输出频率
MotoA = hex2dec(outstr(11:14))/10; %输出电流
MotoV = hex2dec(outstr(15:18)); %输出电压
MotoRpm = hex2dec(outstr(19:22)); %电机转速
MotoDCV = hex2dec(outstr(23:26)); %内部直流电压
MotoInputV = hex2dec(outstr(27:30)); %输入电压
set(handles.text13,'string',MotoHz);
set(handles.text14,'string',MotoA);
set(handles.text15,'string',MotoV);
set(handles.text16,'string',MotoRpm);
set(handles.text17,'string',MotoInputV);
set(handles.text18,'string',MotoDCV);
在写Matlab串口程序的过程中,在Timer中设定了一组主机轮询的程序,单独运行时串口读取正常,数据切片也显示正常。但是在Guide中运行时,数据切片显示的数据一直存在问题。
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global scom Moto_Num RotSpd
RotSpd = str2num(get(handles.edit2,'string'));
fwrite(scom,uint8(hex2dec(Request_Spd(Moto_Num,RotSpd))));
经过检查发现在程序的其他地方存在一个串口的写入程序 fwrite(scom,uint8(hex2dec(Request_Spd(Moto_Num,RotSpd))));
但是此处并没有进行串口的读取,使得数据在串口缓存中累积,而Timer中串口的读取从此处累计的开始读取,所以使得Timer的数据切片不正常。
修改后
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global scom Moto_Num RotSpd
RotSpd = str2num(get(handles.edit2,'string'));
fwrite(scom,uint8(hex2dec(Request_Spd(Moto_Num,RotSpd))));
fread(scom,8,'uchar');