前言
原例程代码可以进行串口接收发送,加载与存储数据
本人在例程代码的基础上添加了共三个功能
1.加载文件数据,三通道同时显示波形
2.放大缩小
3.均值滤波
4.将接收到的数据以固定位数转换为实时波形
一、效果图与控件布局
布局
文章来源:https://www.toymoban.com/news/detail-782988.html
加载文件数据后(excel的csv格式)
滤波效果
实时波形采集当时忘了没截图,但是确实可以使用。文章来源地址https://www.toymoban.com/news/detail-782988.html
二、代码
1.进制转换代码
function sendData = ConvertStr2Dec(handles)
% 将串口发送编辑区的十六进制字符串转换为十进制数
% 输入参数handles,GUI界面的句柄
% 输出参数sendData,待发送的十进制数据
% COPYRIGHT 2018-2020 LEYUTEK. All rights reserved.
str = get(handles.edit_send, 'string'); % 获取串口发送区的十六进制字符串
n = find(str == ' '); % 查找空格的索引
n =[0 n length(str) + 1]; % 在首尾增加索引
% 将两个相邻空格之间的十六进制字符串转换为十进制数,将其转化为数值
for k = 1 : length(n) - 1
hexData = str(n(k) + 1 : n(k + 1) - 1); % 获取两个相邻空格之间的十六进制字符串
if (length(hexData) == 2)
strHex{k} = reshape(hexData, 2, [])'; % 将每个十六进制字符串转化为单元数组
else
strHex = []; % 清空
warndlg("输入错误,正确格式:01 23 4A 5F"); % 弹出警告窗口
break; % 跳出循环
end
end
sendData = hex2dec(strHex)'; % 将十六进制字符串转化为十进制数
% setappdata(handles.figure1, 'sendData', sendData); % 更新sendData
2.串口接收显示代码
function DispData(hObject, eventdata, handles)
% 在串口接收区显示接收到的数据
% 输入参数hObject, eventdata, handles
% COPYRIGHT 2018-2020 LEYUTEK. All rights reserved.
global flag_now
gotDataFlag = getappdata(handles.figure1, 'gotDataFlag'); % 获取串口接收到数据标志
strRec = getappdata(handles.figure1, 'strRec'); % 获取已经接收到的数据
% 如果串口没有接收到数据,则尝试接收串口数据
if (gotDataFlag == false)
ProcRecData(hObject, eventdata, handles);
end
% 如果串口有数据,则将这些数据显示到串口接收区
if (gotDataFlag == true)
% 在执行显示数据函数时,不允许读取串口数据,即不执行串口的回调函数(ProcRecData)
setappdata(handles.figure1, 'dispFlag', true);
% 如果要显示的字符串长度超过10000,清空显示区
if (length(strRec) > 10000)
strRec = '';
setappdata(handles.figure1, 'strRec', strRec);
end
% 在串口接收区显示接收到的数据
set(handles.edit_rec, 'string', strRec);
% 更新gotDataFlag,表示串口数据已经显示到串口接收区
setappdata(handles.figure1, 'gotDataFlag', false);
% 执行完显示数据函数后,允许读取串口数据
setappdata(handles.figure1, 'dispFlag', false);
if flag_now == 0
data = get(handles.edit_rec, 'String');
rec = length(data)/3;
set(handles.edit_receivebyte, 'String', rec)
end
end
3.串口接收处理代码
function [ ] = ProcRecData(hObject, ~, handles)
% 处理串口接收到的数据
% 输入参数hObject, handles
% 注意,既为串口可读取的字节数达到设定值后执行的回调函数,又被DispData所调用
% COPYRIGHT 2018-2020 LEYUTEK. All rights reserved.
strRec = getappdata(handles.figure1, 'strRec'); % 获取串口要显示的数据
dispFlag = getappdata(handles.figure1, 'dispFlag'); % 是否正在执行显示数据操作
% 如果正在执行数据显示操作(调用DispData函数),则暂不接收串口数据
if (dispFlag == true)
return;
end
% 获取串口可读取到的字节数
n = get(hObject, 'BytesAvailable');
global flag_now
global floatData
% 如果串口可读取的字节数不为0
if (n > 0)
% 更新gotDataFlag,说明串口有数据需要显示
setappdata(handles.figure1, 'gotDataFlag', true);
% 读取串口数据,读取出来的数据为十进制的列向量
readData = fread(hObject, n, 'uchar');
% 将数据解析为要显示的字符串
strHex1 = dec2hex(readData')';
strHex2 = [strHex1; blanks(size(readData, 1))];
strReadData = strHex2(:)';
% 更新需要显示的字符串
strRec = [strRec strReadData];
setappdata(handles.figure1, 'strRec', strRec);
% 检查是否检测到 "30 2E" 或 "31 2E"
if flag_now == 1
if contains(strRec, '30 2E') || contains(strRec, '31 2E')
% 寻找 "30 2E" 的位置
index = strfind(strRec, '30 2E');
if isempty(index)
% 寻找 "31 2E" 的位置
index = strfind(strRec, '31 2E');
end
% 找到了目标字符串
if ~isempty(index)
% 获取完整的数据(9位)
startIndex = index ; % 完整数据的开始位置
endIndex = startIndex + 9*3 - 1; % 完整数据的结束位置
% 检查是否有足够的数据可供处理
dataStr = strRec(startIndex:endIndex);
% 转换为十六进制字符串
hexData = dec2hex(dataStr);
% 将十六进制字符串转换为浮点数
floatData = typecast(uint32(hex2dec(hexData)), 'single');
% 在 axes4 上绘制数据
axesHandle = handles.axes4;
plot(axesHandle, floatData);
% 清除已处理的数据
strRec = strRec(endIndex+1:end);
setappdata(handles.figure1, 'strRec', strRec);
end
end
end
end
4.串口扫描代码
function [ ] = ProcRecData(hObject, ~, handles)
% 处理串口接收到的数据
% 输入参数hObject, handles
% 注意,既为串口可读取的字节数达到设定值后执行的回调函数,又被DispData所调用
% COPYRIGHT 2018-2020 LEYUTEK. All rights reserved.
strRec = getappdata(handles.figure1, 'strRec'); % 获取串口要显示的数据
dispFlag = getappdata(handles.figure1, 'dispFlag'); % 是否正在执行显示数据操作
% 如果正在执行数据显示操作(调用DispData函数),则暂不接收串口数据
if (dispFlag == true)
return;
end
% 获取串口可读取到的字节数
n = get(hObject, 'BytesAvailable');
global flag_now
global floatData
% 如果串口可读取的字节数不为0
if (n > 0)
% 更新gotDataFlag,说明串口有数据需要显示
setappdata(handles.figure1, 'gotDataFlag', true);
% 读取串口数据,读取出来的数据为十进制的列向量
readData = fread(hObject, n, 'uchar');
% 将数据解析为要显示的字符串
strHex1 = dec2hex(readData')';
strHex2 = [strHex1; blanks(size(readData, 1))];
strReadData = strHex2(:)';
% 更新需要显示的字符串
strRec = [strRec strReadData];
setappdata(handles.figure1, 'strRec', strRec);
% 检查是否检测到 "30 2E" 或 "31 2E"
if flag_now == 1
if contains(strRec, '30 2E') || contains(strRec, '31 2E')
% 寻找 "30 2E" 的位置
index = strfind(strRec, '30 2E');
if isempty(index)
% 寻找 "31 2E" 的位置
index = strfind(strRec, '31 2E');
end
% 找到了目标字符串
if ~isempty(index)
% 获取完整的数据(9位)
startIndex = index ; % 完整数据的开始位置
endIndex = startIndex + 9*3 - 1; % 完整数据的结束位置
% 检查是否有足够的数据可供处理
dataStr = strRec(startIndex:endIndex);
% 转换为十六进制字符串
hexData = dec2hex(dataStr);
% 将十六进制字符串转换为浮点数
floatData = typecast(uint32(hex2dec(hexData)), 'single');
% 在 axes4 上绘制数据
axesHandle = handles.axes4;
plot(axesHandle, floatData);
% 清除已处理的数据
strRec = strRec(endIndex+1:end);
setappdata(handles.figure1, 'strRec', strRec);
end
end
end
end
5.主程序代码
function varargout = SerialAssistant(varargin)
% SERIALASSISTANT MATLAB code for SerialAssistant.fig
% SERIALASSISTANT, by itself, creates a new SERIALASSISTANT or raises the existing
% singleton*.
%
% H = SERIALASSISTANT returns the handle to a new SERIALASSISTANT or the handle to
% the existing singleton*.
%
% SERIALASSISTANT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SERIALASSISTANT.M with the given input arguments.
%
% SERIALASSISTANT('Property','Value',...) creates a new SERIALASSISTANT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before SerialAssistant_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to SerialAssistant_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help SerialAssistant
% Last Modified by GUIDE v2.5 04-Jun-2023 22:07:28
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @SerialAssistant_OpeningFcn, ...
'gui_OutputFcn', @SerialAssistant_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before SerialAssistant is made visible.
function SerialAssistant_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to SerialAssistant (see VARARGIN)
global recvBytes;
global sendBytes;
recvBytes = 0;
sendBytes = 0;
% Choose default command line output for SerialAssistant
handles.output = hObject;
set(gcf,'numbertitle', 'off', 'name', '传感器上位机'); % 设置当前窗口名字
movegui('center'); % 将窗口置于屏幕中间
% 设置当前窗口各个控件的参数
set(handles.popupmenu_baud_rate, 'string', {'4800', '9600', '14400', '19200', '38400',...
'57600', '76800', '115200'}, 'value', 8); % 波特率
set(handles.popupmenu_data_bits, 'string', {'8', '9'}); % 数据位
set(handles.popupmenu_stop_bits, 'string', {'1', '1.5', '2'}); % 停止位
set(handles.popupmenu_parity, 'string', {'NONE', 'ODD', 'EVEN'}); % 校验位
global gUARTOpenFlag; % 串口开启标志,0-串口为关闭状态,1-串口为开启状态
gUARTOpenFlag = 0; % 串口默认为关闭状态
gotDataFlag = false; % 串口接收到数据标志,默认为未接收到数据
strRec = ''; % 已经接收到的字符串,默认为空
dispFlag = false; % 正在进行数据显示的标志
setappdata(hObject, 'gotDataFlag', gotDataFlag); % 更新gotDataFlag
setappdata(hObject, 'strRec', strRec); % 更新strRec
setappdata(hObject, 'dispFlag', dispFlag); % 更新dispFlag
ScanUART(handles); % 扫描串口
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes SerialAssistant wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = SerialAssistant_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function edit_rec_Callback(hObject, eventdata, handles)
% hObject handle to edit_rec (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_rec as text
% str2double(get(hObject,'String')) returns contents of edit_rec as a double
% --- Executes during object creation, after setting all properties.
function edit_rec_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_rec (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu_port_num.
function popupmenu_port_num_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_port_num (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_port_num contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_port_num
% --- Executes during object creation, after setting all properties.
function popupmenu_port_num_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_port_num (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu_baud_rate.
function popupmenu_baud_rate_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_baud_rate (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_baud_rate contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_baud_rate
% --- Executes during object creation, after setting all properties.
function popupmenu_baud_rate_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_baud_rate (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu_parity.
function popupmenu_parity_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_parity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_parity contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_parity
% --- Executes during object creation, after setting all properties.
function popupmenu_parity_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_parity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu_data_bits.
function popupmenu_data_bits_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_data_bits (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_data_bits contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_data_bits
% --- Executes during object creation, after setting all properties.
function popupmenu_data_bits_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_data_bits (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu_stop_bits.
function popupmenu_stop_bits_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu_stop_bits (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu_stop_bits contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu_stop_bits
% --- Executes during object creation, after setting all properties.
function popupmenu_stop_bits_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu_stop_bits (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton_open.
function pushbutton_open_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_open (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global gUARTOpenFlag; % 串口开启标志,0-串口为关闭状态,1-串口为开启状态
global gSerial; % 串口对象
delete(instrfindall); % 删除所有串口对象
num = get(handles.popupmenu_port_num, 'value'); % 获取所选项的序号
cellArr = get(handles.popupmenu_port_num, 'string'); % 获取所有选项组成的元胞数组
cellArrPortNum = cellArr(num); % 根据所选项的序号,获取所选串口号的字符串元胞数组
num = get(handles.popupmenu_baud_rate, 'value'); % 获取所选项的序号
cellArr = get(handles.popupmenu_baud_rate, 'string'); % 获取所有选项组成的元胞数组
cellArrBaudRate = cellArr(num); % 根据所选项的序号,获取所选波特率的字符串元胞数组
num = get(handles.popupmenu_data_bits, 'value'); % 获取所选项的序号
cellArr = get(handles.popupmenu_data_bits, 'string'); % 获取所有选项组成的元胞数组
cellArrDataBits = cellArr(num); % 根据所选项的序号,获取所选数据位的字符串元胞数组
num = get(handles.popupmenu_stop_bits, 'value'); % 获取所选项的序号
cellArr = get(handles.popupmenu_stop_bits, 'string'); % 获取所有选项组成的元胞数组
cellArrStopBits = cellArr(num); % 根据所选项的序号,获取所选停止位字符串元胞数组
num = get(handles.popupmenu_parity, 'value'); % 获取所选项的序号
cellArr = get(handles.popupmenu_parity, 'string'); % 获取所有选项组成的元胞数组
cellArrParity = cellArr(num); % 根据所选项的序号,获取所选校验位的字符串元胞数组
strPortNum = cellArrPortNum{1}; % 获取所选串口号字符串
dBaudRate = str2double(cellArrBaudRate); % 将字符串转换为双精度的波特率
dDataBits = str2double(cellArrDataBits); % 将字符串转换为双精度的数据位
dStopBits = str2double(cellArrStopBits); % 将字符串转换为双精度的停止位
strParity = cellArrParity{1}; % 获取所选校验和字符串
% 创建一个串口对象
gSerial = serial(strPortNum, 'BaudRate', dBaudRate, 'DataBits', dDataBits, ...
'StopBits', dStopBits, 'Parity', strParity, 'BytesAvailableFcnCount', 10,...
'BytesAvailableFcnMode', 'byte', 'BytesAvailableFcn', {@ProcRecData, handles},...
'TimerPeriod', 0.05, 'timerfcn', {@DispData, handles});
try
fopen(gSerial); % 打开串口
gUARTOpenFlag = 1; % 将串口打开标志置为已打开
catch
gUARTOpenFlag = 0; % 将串口打开标志置为未打开
msgbox('串口打开失败!');
end
set(handles.checkbox_regular_send, 'Enable', 'on'); % 启用定时发送复选框
set(hObject, 'Enable', 'off'); % 禁用打开串口按钮
set(handles.pushbutton_close, 'Enable', 'on'); % 启用关闭串口按钮
% --- Executes on button press in pushbutton_close.
function pushbutton_close_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_close (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global gSerial; % 串口对象
global gUARTOpenFlag; % 串口开启标志,0-串口为关闭状态,1-串口为开启状态
if (gUARTOpenFlag == 1) % 如果串口开启标志为1
gUARTOpenFlag = 0; % 将该标志置为0
fclose(gSerial); % 关闭串口
end
t = timerfind; % 查找定时器
if (~isempty(t)) % 如果查找到定时器
stop(t); % 关闭定时器
delete(t); % 删除定时器
end
set(handles.checkbox_regular_send, 'value', 0); % 定时发送复选框设置为不选中
set(hObject,'Enable','off'); % 禁用关闭串口按钮
set(handles.pushbutton_open,'Enable','on'); % 启用打开串口按钮
set(handles.checkbox_regular_send, 'Enable', 'off'); % 禁用定时发送复选框
% --- Executes on button press in checkbox_regular_send.
function checkbox_regular_send_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_regular_send (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox_regular_send
if get(hObject, 'value') % 如果定时发送复选框
t1 = 0.001 * str2double(get(handles.edit_send_period, 'string')); % 获取定时发送周期
sendTimer = timer('ExecutionMode', 'fixedrate', 'Period', t1, 'TimerFcn',...
{@pushbutton_send_Callback, handles}); % 创建定时器
set(handles.edit_send_period, 'Enable', 'off'); % 定时发送周期文本框禁止编辑
set(handles.edit_send, 'Enable', 'inactive'); % 数据发送文本框禁止编辑
start(sendTimer); % 启动定时器
else
set(handles.edit_send_period, 'Enable', 'on'); % 定时发送周期文本框允许编辑
set(handles.edit_send, 'Enable', 'on'); % 数据发送文本框允许编辑
sendTimer = timerfind; % 查找定时器
stop(sendTimer); % 关闭定时器
delete(sendTimer); % 删除定时器
end
% --- Executes on button press in pushbutton_send.
function pushbutton_send_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_send (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global gSerial; % 串口对象
global gUARTOpenFlag; % 串口开启标志,0-串口为关闭状态,1-串口为开启状态
global sendBytes
data = get(handles.edit_send, 'String'); % 获取待发送数据
record = floor((length(data)/3))+1;
sendBytes = sendBytes + record;
set(handles.edit_sendbyte, 'String',sendBytes);
sendData = ConvertStr2Dec(handles); % 将串口发送编辑区的十六进制字符串转换为十进制数
if isequal(gUARTOpenFlag, 1) % 判断串口是否已经打开
fwrite(gSerial, sendData, 'uint8', 'async'); % 通过串口发送数据
else
warndlg("串口未打开"); % 弹出警告窗
end
function edit_send_period_Callback(hObject, eventdata, handles)
% hObject handle to edit_send_period (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_send_period as text
% str2double(get(hObject,'String')) returns contents of edit_send_period as a double
% --- Executes during object creation, after setting all properties.
function edit_send_period_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_send_period (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_send_Callback(hObject, eventdata, handles)
% hObject handle to edit_send (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_send as text
% str2double(get(hObject,'String')) returns contents of edit_send as a double
% --- Executes during object creation, after setting all properties.
function edit_send_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_send (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton_clr_send.
function pushbutton_clr_send_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_clr_send (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.edit_send,'String',[]); % 清空串口发送区
% --- Executes on button press in pushbutton_clr_rec.
function pushbutton_clr_rec_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_clr_rec (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
setappdata(handles.figure1, 'strRec', ''); % 清空要显示的字符串
set(handles.edit_rec,'String',[]); % 清空串口接收区
set(handles.edit_receivebyte, 'String',0)
% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global gSerial; % 串口对象
global gUARTOpenFlag; % 串口开启标志,0-串口为关闭状态,1-串口为开启状态
if (gUARTOpenFlag == 1) % 如果串口开启标志为1
gUARTOpenFlag = 0; % 将该标志置为0
fclose(gSerial); % 关闭串口
end
t = timerfind; % 查找定时器
if (~isempty(t)) % 如果查找到定时器
stop(t); % 关闭定时器
delete(t); % 删除定时器
end
close all;
% --- Executes during object deletion, before destroying properties.
function uipanel_send_DeleteFcn(hObject, eventdata, handles)
% hObject handle to uipanel_send (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
function edit_receivebyte_Callback(hObject, eventdata, handles)
% hObject handle to edit_receivebyte (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_receivebyte as text
% str2double(get(hObject,'String')) returns contents of edit_receivebyte as a double
% --- Executes during object creation, after setting all properties.
function edit_receivebyte_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_receivebyte (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_sendbyte_Callback(hObject, eventdata, handles)
% hObject handle to edit_sendbyte (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_sendbyte as text
% str2double(get(hObject,'String')) returns contents of edit_sendbyte as a double
% --- Executes during object creation, after setting all properties.
function edit_sendbyte_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_sendbyte (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit_data_Callback(hObject, eventdata, handles)
% hObject handle to edit_data (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit_data as text
% str2double(get(hObject,'String')) returns contents of edit_data as a double
% --- Executes during object creation, after setting all properties.
function edit_data_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_data (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton_load_data.
function pushbutton_load_data_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_load_data (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global gLoadFlag; % 加载数据标志,0-未加载,1-已加载
global fileInfo
global readData
[fileName, pathName] = uigetfile('*.csv'); % 获取文件名和文件路径
fileInfo = [pathName, fileName]; % 将文件路径和文件名拼接之后赋值给fileInfo
try
readData = readmatrix(fileInfo); % 从csv文件读取数据,并赋值给readData
readData = readData(:, 1:3); % 仅保留前三列数据
set(handles.edit_data, 'String', num2str(readData')); % 列向量先转置为行向量,再转字符并显示
handles.originalData = readData; % 将readData赋值给handles结构体的成员变量
guidata(hObject, handles); % 更新handles
[~, numColumns] = size(readData);
n = 1:size(readData, 1);
axesHandles = cell(1, numColumns); % 创建一个cell数组来存储每个axes的句柄
for i = 1:numColumns
% 将绘图焦点切换到相应的axes控件
axesHandles{i} = eval(sprintf('handles.axes%d', i));
axes(axesHandles{i});
% 绘制数据
plot(n, readData(:, i), 'b');
xlim([n(1), n(end)]); % 设置x轴的显示范围
end
set(handles.pushbutton_save_data, 'Enable', 'on'); % 读取数据操作成功后,启用存储数据按钮
gLoadFlag = 1; % 将gLoadFlag设置为1,表示数据已经加载成功
catch
s = lasterror;
gLoadFlag = 0; % 将gLoadFlag设置为0,表示数据未加载成功
end
global filt_flag
filt_flag = 1;
% --- Executes on button press in buttonfilt.
function buttonfilt_Callback(hObject, eventdata, handles)
% hObject handle to buttonfilt (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global filt_flag
global readData
if filt_flag == 1
set(handles.buttonfilt, 'String', '取消滤波');
filt_flag = 0;
% 执行滤波操作,示例中使用一个简单的平均滤波器
data = readData; % 获取原始数据
filteredData = movmean(data, 5); % 使用移动平均滤波器平滑数据,窗口大小为5
handles.filteredData = filteredData; % 将滤波后的数据保存到handles结构体的成员变量
guidata(hObject, handles); % 更新handles
[~, numColumns] = size(readData);
n = 1:size(readData, 1);
axesHandles = cell(1, numColumns); % 创建一个cell数组来存储每个axes的句柄
for i = 1:numColumns
% 将绘图焦点切换到相应的axes控件
axesHandles{i} = eval(sprintf('handles.axes%d', i));
axes(axesHandles{i});
[len, ~] = size(filteredData); % 获取数据长度
n = 1:len; % 横坐标
% 绘制数据
plot(n, filteredData(n), 'b');
xlim([n(1), n(end)]); % 设置x轴的显示范围
end
else
filt_flag = 1
set(handles.buttonfilt, 'String', '开始滤波');
[~, numColumns] = size(readData);
n = 1:size(readData, 1);
for i = 1:numColumns
% 将绘图焦点切换到相应的axes控件
axesHandle = eval(sprintf('handles.axes%d', i));
axes(axesHandle);
% 绘制数据
plot(n, readData(:, i), 'b');
xlim([n(1), n(end)]); % 设置x轴的显示范围
end
end
% --- Executes on slider movement.
function buttonamplify_x_Callback(hObject, eventdata, handles)
% hObject handle to buttonamplify_x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
global floatData
global flag_ensure
if flag_ensure == 1
amplifyFactor = get(hObject, 'Value'); % 获取滑动条的当前值
amplifiedData = floatData ; % 对原始数据进行放大处理
handles.amplifiedData = amplifiedData; % 将放大后的数据保存到handles结构体的成员变量
guidata(hObject, handles); % 更新handles
% 在界面上显示放大后的数据
axes(handles.axes4); % 创建坐标轴对象
[len, ~] = size(amplifiedData); % 获取数据长度
n = 1:len*amplifyFactor; % 横坐标
plot(n, amplifiedData(n), 'b'); % 绘制放大后的波形
end
% --- Executes during object creation, after setting all properties.
function buttonamplify_x_CreateFcn(hObject, eventdata, handles)
% hObject handle to buttonamplify_x (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on slider movement.
function buttonamplify_y_Callback(hObject, eventdata, handles)
% hObject handle to buttonamplify_y (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
global floatData
global flag_ensure
if flag_ensure == 1
amplifyFactor = get(hObject, 'Value'); % 获取滑动条的当前值
originalData = floatData; % 获取原始数据
amplifiedData = originalData * amplifyFactor; % 对原始数据进行放大处理
handles.amplifiedData = amplifiedData; % 将放大后的数据保存到handles结构体的成员变量
guidata(hObject, handles); % 更新handles
% 在界面上显示放大后的数据
axes(handles.axes4); % 创建坐标轴对象
[len, ~] = size(amplifiedData); % 获取数据长度
n = 1:len; % 横坐标
plot(n, amplifiedData(n), 'b'); % 绘制放大后的波形
ylim(handles.axes1, [min(amplifiedData), max(amplifiedData)]); % 设置y轴范围
end
% --- Executes during object creation, after setting all properties.
function buttonamplify_y_CreateFcn(hObject, eventdata, handles)
% hObject handle to buttonamplify_y (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on button press in pushbutton_save_data.
function pushbutton_save_data_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_save_data (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global gLoadFlag; % 加载数据标志,0-未加载,1-已加载
[fileName, pathName] = uiputfile('*.csv'); % 获取文件名和文件路径
fileInfo = [pathName, fileName]; % 将文件路径和文件名拼接之后赋值给fileInfo
if (gLoadFlag == 1) % 如果数据已经加载
saveData = handles.originalData; % 获取handles所包含的用户定义的数据变量
try
% "w+"表示打开可读写文件,若文件存在则清空该文件,若文件不存在则创建该文件
fid = fopen(fileInfo, 'w+'); % 打开或创建文件,fid为文件句柄
fprintf(fid, '%f\n', saveData); % 向文件写入数据(小数形式)
fclose(fid); % 关闭文件
catch
s = lasterror;
disp(s.message);
end
end
global fft_flag;
fft_flag = 0;
% --- Executes on button press in fft.
function fft_Callback(hObject, eventdata, handles)
% hObject handle to fft (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global fft_flag
global fileInfo
readData = csvread(fileInfo); % 从csv文件读取数据,并赋值给readData
readData = readData(:, 1:3); % 仅保留前三列数据
if fft_flag == 0
fft_flag = 1
set(handles.fft, 'String', '取消fft'); % 读取数据操作成功后,启用存储数据按钮
fftData = fft(readData); % 执行FFT变换
Fs = 1000; % 假设采样率为1000Hz(请根据实际情况修改采样率)
% 计算频谱
L = size(readData, 1);
f = Fs*(0:(L/2))/L; % 计算频率范围
P = abs(fftData/L); % 计算频谱的幅值
% 绘制FFT图像
[~, numColumns] = size(readData);
for i = 1:numColumns
% 将绘图焦点切换到相应的axes控件
axesHandle = eval(sprintf('handles.axes%d', i));
axes(axesHandle);
% 绘制FFT图像
plot(f, P(1:L/2+1), 'b');
end
else
fft_flag = 0
set(handles.fft, 'String', '执行fft'); % 读取数据操作成功后,启用存储数据按钮
[~, numColumns] = size(readData);
n = 1:size(readData, 1);
for i = 1:numColumns
% 将绘图焦点切换到相应的axes控件
axesHandle = eval(sprintf('handles.axes%d', i));
axes(axesHandle);
% 绘制数据
plot(n, readData(:, i), '-');
xlim([n(1), n(end)]); % 设置x轴的显示范围
end
end
global flag_now
global flag_ensure
flag_now = 0;
% --- Executes on button press in capture.
function capture_Callback(hObject, eventdata, handles)
% hObject handle to capture (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global flag_now
global flag_ensure
global filt_flag
if flag_now==0
flag_now = 1;
flag_ensure = 1;
set(handles.capture, 'String', '取消采样');
fft_flag = 0;
set(handles.fft, 'String', '执行FFT');
else
flag_now = 0;
set(handles.capture, 'String', '实时采样');
end
到了这里,关于Matlab上位机——串口收发、接收转为图像实时显示、图像放大缩小等功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!