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

这篇具有很好参考价值的文章主要介绍了Matlab上位机——串口收发、接收转为图像实时显示、图像放大缩小等功能。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

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

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

一、效果图与控件布局

布局
matlab串口波显示,MatlabPTB,matlab,开发语言,单片机

matlab串口波显示,MatlabPTB,matlab,开发语言,单片机
加载文件数据后(excel的csv格式)matlab串口波显示,MatlabPTB,matlab,开发语言,单片机
滤波效果
matlab串口波显示,MatlabPTB,matlab,开发语言,单片机
实时波形采集当时忘了没截图,但是确实可以使用。文章来源地址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模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • QT三驾马车(一)——实现上位机(串口数据发送和接收)

    以后同学们做项目一定会用到QT的三驾马车,QT的三驾马车即QT的串口编程,QT的网络编程和QT的GPIO,今天我们通过一个项目来介绍第一部分,QT的串口编程。 之前看过很多相关的文章,但是按照顺序来编译总是会出错,可是我自己还找不到原因,对于我这种新手小白来说极其

    2024年02月15日
    浏览(46)
  • C#上位机与三菱FX3UPLC实现异步伪实时串口通信机制(串口类通信可参考)

    串口是串行接口(serial port)的简称,也称为 串行通信接口 或 COM接口。 串口通信(serial communication)是指采用串行通信协议在一条信号线上将数据一个比特一个比特地逐位进行传输的通信模式。 串口按电气标准及协议来划分,包括RS-232-C、RS-422、RS485等。 在串行通信中,数

    2023年04月21日
    浏览(53)
  • MATLAB :【11】一文带你读懂serialport串口收发原理与实现

    碎碎念: 这周的主要工作还是集中于FOC中,因为羡慕稚晖君做出的漂亮Qt面板,因此在利用MATLAB复刻过程中,学习了一下serialport的使用。FOC的GUI部分就在加班加点写作中啦,同时最近打算开一个新坑,大家可以期待一下哈哈哈。 欢迎大佬们点赞+收藏+关注~ o(* ̄▽ ̄*)ブ 目录

    2023年04月18日
    浏览(50)
  • 【PHP】PHP实现与硬件串口交互,接收硬件发送的实时数据

    目的:借助虚拟串口软件(VSPD)模拟硬件串口发送数据,使用PHP语言实现接收硬件发送的数据。 我这里的需求是连接天平,把天平的称量数据实时的传送到PHP使用。 使用工具:vspd+串口调试工具 使用语言:PHP 使用到的工具有VSPD和串口调试工具,其中VSPD是模拟硬件串口,串

    2024年02月02日
    浏览(35)
  • QT串口接收数据并进行波形显示(含源码)

    ** 使用QT在串口调试助手基础上实现波形显示(含源码) 评论比较多留言需要源码的,逐个发邮箱比较麻烦也不能及时回复,现将源码上传至链接(无需积分下载)https://download.csdn.net/download/m0_51294753/87743394,下载不下来可以私信我留邮箱。 一、前言 背景:使用ADS1255对模拟信

    2024年02月01日
    浏览(41)
  • FPGA接收串口数据并通过LCD1602显示

    一、前言 在学习《FPGA设计与Verilog HDL实现》第九章内容Verilog驱动常用I/O外设时,书中有一个驱动LCD1602的例程,但其是通过状态机显示固定的几个字符。本着动手实践的原则,决定利用手头的硬件实现FPGA接收串口数据并在LCD1602上显示,下面记录项目开始的过程。因为刚接触

    2024年02月06日
    浏览(47)
  • FPGA_数码管显示UART串口接收的数据

          实验目标 :通过电脑调试助手向FPGA的UART串口接收模块发送数据,然后数据可以稳定显示 在数码管上。       实验目的 : 练习UART串口模块和数码管的使用。之前已经有文章详细讲解了串口和数码管的开发,故这里直接提供设计思路供大家参考。 (串口文章链接)ht

    2024年02月13日
    浏览(48)
  • FPGA实现AD9708和AD9280波形收发输出HDMI模拟示波器,串口协议帧控制显示,提供工程源码和技术支持

    AD9708 很简单,8 位分辨率,125MSPS 采样率,输入参考电压3~5V,内置 1.2V 参考电压,8bit数字信号输入,差分电流输出;芯片操作不需要软件配置,给个时钟信号就工作,简单得很,根据官方手册,内部结构如下: SLEEP引脚提供芯片休眠功能,当不需要使用该芯片时可拉高SLEEP以

    2024年02月02日
    浏览(58)
  • STM32+ov7725+ESP8266实现无线图传-完成上位机图像显示

    stm32f407探索者开发板和STM32F103ZET6战舰开发板。接正点原子ov5640、OV7725、OV2640摄像头,通过esp8266Wi-Fi模块(透传模式)将摄像头采集到的rgb565格式图片通过tcp/ip协议上传到上位机显示。 【1】使用QT开发上位机,建立TCP服务器,接收ESP8266发送过来的图像数据显示。 【2】编写S

    2024年02月08日
    浏览(88)
  • 【个人笔记】51单片机串口通信的字符串接收和发送,串口通信调节数码管显示时钟(串口通信,定时器,数码管)

           目的:利用PROTUES仿真软件、串口调试助手、虚拟串口,搭建单片机与PC通信仿真平台,熟悉单片机串口的配置及与PC机的通信方法;尝试制定通信协议,单片机根据通信协议解析接收到的内容,并根据接收的指令执行相应的操作。 基本功能: 1.时分秒的动态显示。

    2024年02月11日
    浏览(63)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包