[MATLAB App Designer] 用MATLAB写一个上位机--基于串

搜索串口:
COM_x = serialportlist("available");%搜索可用串口
if isempty(COM_x)
warndlg('No available COM port', 'Warning');
else
app.COMListBox.Items = COM_x;
end
创建串口:
value = app.Switch.Value;
switch value
case 1
%创建串口 选择COM口 波特率 默认校验 N 8 1
app.setupCOM = serialport(app.COMListBox.Value, str2double(app.DropDown.Value));
app.setupCOM.Timeout = 1;%接收超时 时间
app.Lamp.Color = [0 1 0];
case 0
app.Lamp.Color = [1 0 0];
delete(app.setupCOM);%删除串口
end
读取并显示:
y = zeros(2000, 1);%随便定义一个存储空间
while 1
if app.ReadDataButton.Value == 0
app.ReadDataButton.BackgroundColor = [0.98 0.91 0.91];
return;%跳出循环
else
app.ReadDataButton.BackgroundColor = [0.91 0.98 0.96];
data = read(app.setupCOM, 1, 'int8');%读取一个字节 的数据
y = circshift(y, 1);%存储空间移位
y(1) = data;
plot(app.UIAxes, 1:500, y(1:500, 1));%实时显示存储的最近500个点
app.DisplayEditField.Value = data;
flush(app.setupCOM);
pause(0.01);%暂停0.01s
end
end