Matlab串口读取错误

本文探讨了在Matlab中使用串口进行数据读取时遇到的问题,特别是在Guide环境中运行时出现的数据切片异常现象。通过分析发现,问题源于串口缓存中的数据未被及时清除,导致后续读取操作受到影响。文章提供了修改后的代码示例,通过增加fread函数清空串口缓存,解决了数据切片显示不准确的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值