Matlab上位机——串口收发、接收转为图像实时显示、图像放大缩小等功能

前言

原例程代码可以进行串口接收发送,加载与存储数据

本人在例程代码的基础上添加了共三个功能
1.加载文件数据,三通道同时显示波形
2.放大缩小
3.均值滤波
4.将接收到的数据以固定位数转换为实时波形

一、效果图与控件布局

布局
在这里插入图片描述

在这里插入图片描述
加载文件数据后(excel的csv格式)在这里插入图片描述
滤波效果
在这里插入图片描述
实时波形采集当时忘了没截图,但是确实可以使用。

二、代码

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

  • 14
    点赞
  • 136
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
分享自己的串口接收GUI可实时观察数据图像-ADC DMA USART.rar 做这个软件的想法是这样的 先是阅读了飞哥的串口收发助手程序 其中 在第二版书中的P512页末端提出了一个串口接收数据的要求 即 假设计算机与某硬件设备用串口相连 设备每隔固定时间(我这里是5mS 速度非常快)通过串口给计算机发送数据 这帧数据中包含有 帧头 两字节 0x55 0xAA 数据字节数20 一共每帧22个数据 飞哥提出的是仅用串口的定时器定时读取的方法 并且他说 “经实践证明是可以的” 费劲九牛二虎之力我把它实现了 还是挺艰辛的 程序刚刚完成基本调试 代码也不是特别整齐 我用单片机上位机发送串口数据 按一帧20个数据并 2个帧起始位  帧发送间歇时间是定时的5mS 为什么要做这个东西呢?因为 这个做法是很有意义的  实时地观察采样数据 我参加的智能车比赛中就意识到 上位机调试 看数据曲线十分重要  否则 不知道参数的变化情况 怎么调试? 大概描述一下这个程序 STM32底层A/D转换采样 通过DMA连接片上USART  定时地发送数据到上位机 其中我对一个通道进行采样 采样十次 即同一个传感器  一共20个数据(STM32是12位的片上AD 参考电压3.3V) 数据传入Matlab串口中 用矩阵相乘的方法求出平均值 后plot到axes图上   由于是定时器触发的读取数据函数 那么每次读取到的数据有以下几种情况: ||Data, Data,StartByte1,StartByte2,Data,...,StartByte1,StartByte2|| ||Data, Data,StartByte1,StartByte2,Data,...,StartByte1|| ||Data, Data,StartByte1,StartByte2,Data,...,Data||  %这一次定时器定时接收的到的数据末尾的最后一帧的Data不满20个 不够一帧 ||StartByte1,StartByte2,Data,...,Data,Data,StartByte1,StartByte2|| %这次读到的数据末尾只有帧头的2位标志数据 连原始数据全部都得在下一次定时读取中才能读得到 情况比较多 即一帧的数据可能会被中间间断成2次读取!每一次定时读取的时候 就意味着至多会有2帧数据是不完整的! 大家一般的想法大概就是丢失被中断的帧 这样做程序简洁 方便读 但不可避免地会丢失掉一些数据 我在这里耽误了很久 写了很多段程序代码来完整地恢复了这些被打断的数据 (吹毛求疵吧 但我觉得如果在非常严格的数据观察里是有意义的) 程序有时还是有些不知道为什么的BUG 工科人 表达能力不行 分享一个小作品 可能程序写得比较乱 大家看不明白 或运行不了 有需要就问吧    使用方法 我把STM32 工程里的USER文件放进来了 整个工程太大放不下   连接STM32 ADC1 通道15到外设 把USART1接到电脑上 Matlab 打开GUI 'serial_communication2'  ‘打开串口’ OK 看看数据吧 (有时可能会Matlab报错 关闭再重新执行一次GUI 这BUG一直不知道错在哪)
MATLAB中,可以使用图像处理工具箱和GUI工具箱来编写程序,以实现图像显示上位机。 首先,需要使用图像处理工具箱中的函数加载图像数据。可以使用`imread`函数来读取图像,并保存为一个二维矩阵。这个矩阵的每个元素表示图像中对应位置的像素值。 接下来,使用MATLAB的GUI工具箱来创建一个图形界面。可以使用`figure`函数创建一个新窗口,并使用`axes`函数创建一个用于显示图像的轴。然后,可以将图像数据传递给`imshow`函数,将图像显示在轴上。 为了增强用户的交互体验,可以为图形界面添加一些控件,例如按钮、滑动条等。通过在回调函数中编写代码,可以实现对图像进行调整、处理等功能。 例如,可以添加一个按钮,当用户点击按钮时,可以调用图像处理工具箱中的函数对图像进行滤波操作,如平滑滤波、锐化等。处理后的图像可以通过`imshow`函数显示在轴上。 除了显示图像,还可以使用MATLAB的GUI工具箱创建其他控件,例如文本框,用于显示图像的统计信息,如最大值、最小值等。还可以添加菜单栏、工具栏等,提供更多功能选项。 最后,可以使用MATLAB的部署工具箱将编写的程序导出为可执行文件,以便在没有MATLAB安装的计算机上运行。导出后的可执行文件可以作为一个独立的上位机程序,用于图像显示、处理等功能。 总而言之,使用MATLAB图像处理工具箱和GUI工具箱,可以实现图像显示上位机的编写。通过加载、处理和显示图像,以及添加交互控件和功能,可以为用户提供灵活、可视化的图像处理工具。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不知何人

万分感谢诸位观看

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值