QT串口和数据库通信

创建串口

串口连接客户端并向服务器发送消息

client.pro

#-------------------------------------------------
#
# Project created by QtCreator 2024-07-02T14:11:20
#
#-------------------------------------------------QT       += core gui network
QT       += core gui serialportgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = client
TEMPLATE = app# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0SOURCES += main.cpp\widget.cppHEADERS  += widget.hFORMS    += widget.ui

widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTcpSocket>
#include <QSerialPort>namespace Ui {
class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();void InitClient();void InitWidget();private slots:void on_connect_bt_clicked();void OnReadData();void OnReadyData1();void on_open_bt_clicked();private:Ui::Widget *ui;QTcpSocket *m_pSocket;QSerialPort *m_pSerial;
};#endif // WIDGET_H

main.cpp

#include "widget.h"
#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.InitClient();w.InitWidget();w.show();return a.exec();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QHostAddress>
#include <QSerialPort>
#include <QSerialPortInfo>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);m_pSocket = NULL;m_pSerial = NULL;
}Widget::~Widget()
{delete ui;
}void Widget::InitClient()
{qDebug() << "Widget::InitClient() enter";if (NULL == m_pSocket){m_pSocket = new QTcpSocket(this);connect(m_pSocket, SIGNAL(readyRead()), this, SLOT(OnReadData()));}qDebug() << "Widget::InitClient() exit";
}void Widget::on_connect_bt_clicked()
{qDebug() << "Widget::on_connect_bt_clicked() enter";QString strIP = ui->ip_edit->text();QString strPort = ui->port_edit->text();qDebug() << strIP << " " << strPort;if (strIP.length() == 0 || strPort.length() == 0){qDebug() << "input error";return;}if (NULL == m_pSocket){qDebug() << "socket error";return;}m_pSocket->connectToHost(QHostAddress("127.0.0.1"), strPort.toShort());if (m_pSocket->waitForConnected(3000)){qDebug() << "connect ok";}else{qDebug() << "connect error";}qDebug() << "Widget::on_connect_bt_clicked() exit";
}void Widget::OnReadData()
{QByteArray arr = m_pSocket->readAll();qDebug() << arr;
}void Widget::InitWidget()
{qDebug()  << "Widget::InitWidget() enter";if (NULL  == m_pSerial){m_pSerial  = new QSerialPort(this);connect(m_pSerial, SIGNAL(readyRead()), this, SLOT(OnReadyData1()));}qDebug()  << "Widget::InitWidget() exit";
}void Widget::OnReadyData1() //串口数据就绪槽函数,当串口有数据可读时,该函数会被调用
{qDebug()  << "Widget::OnReadyData1() enter";QByteArray strData = m_pSerial->readAll(); // 读取所有数据,处理接收到的数据m_pSocket->write(strData.toStdString().data());qDebug()  << "Widget::OnReadyData1() exit";
}void Widget::on_open_bt_clicked()
{qDebug()  << "Widget::on_open_bt_clicked() enter";if (NULL == m_pSerial){qDebug()  << "serial obj error";return;}QString strBt = ui->open_bt->text();if (strBt == "open"){QString strCom = ui->uart_com->currentText();if (strCom.length() == 0){qDebug() << "com port error";return;}m_pSerial->setPortName(strCom);m_pSerial->setBaudRate(QSerialPort::Baud9600);m_pSerial->setDataBits(QSerialPort::Data8);m_pSerial->setStopBits(QSerialPort::OneStop);m_pSerial->setParity(QSerialPort::NoParity);m_pSerial->setFlowControl(QSerialPort::NoFlowControl);if (!m_pSerial->isOpen()){if (m_pSerial->open(QIODevice::ReadWrite)){qDebug()  <<  "open ok";ui->open_bt->setText("close");ui->uart_com->setEnabled(false);}else{qDebug()  << "open error";}}}else{m_pSerial->close();ui->open_bt->setText("open");//ui->send_bt->setEnabled(false);ui->uart_com->setEnabled(true);}
qDebug()  << "Widget::on_open_bt_clicked() exit";}

widget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0"><class>Widget</class><widget class="QWidget" name="Widget"><property name="geometry"><rect><x>0</x><y>0</y><width>692</width><height>468</height></rect></property><property name="windowTitle"><string>Widget</string></property><widget class="QLabel" name="label"><property name="geometry"><rect><x>30</x><y>140</y><width>72</width><height>15</height></rect></property><property name="text"><string>ip</string></property></widget><widget class="QLineEdit" name="ip_edit"><property name="geometry"><rect><x>110</x><y>140</y><width>181</width><height>21</height></rect></property></widget><widget class="QLabel" name="label_2"><property name="geometry"><rect><x>30</x><y>180</y><width>72</width><height>15</height></rect></property><property name="text"><string>port</string></property></widget><widget class="QLineEdit" name="port_edit"><property name="geometry"><rect><x>110</x><y>180</y><width>181</width><height>21</height></rect></property></widget><widget class="QPushButton" name="connect_bt"><property name="geometry"><rect><x>340</x><y>150</y><width>93</width><height>28</height></rect></property><property name="text"><string>connect</string></property></widget><widget class="QComboBox" name="uart_com"><property name="geometry"><rect><x>30</x><y>50</y><width>87</width><height>22</height></rect></property><item><property name="text"><string>com9</string></property></item></widget><widget class="QPushButton" name="open_bt"><property name="geometry"><rect><x>200</x><y>50</y><width>93</width><height>28</height></rect></property><property name="text"><string>open</string></property></widget></widget><layoutdefault spacing="6" margin="11"/><resources/><connections/>
</ui>

服务器接收数据并存储在数据库内 

server.pro

#-------------------------------------------------
#
# Project created by QtCreator 2024-07-02T09:20:48
#
#-------------------------------------------------QT       += core gui network
QT       += core gui sqlgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = server
TEMPLATE = app# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0SOURCES += main.cpp\widget.cpp \db.cppHEADERS  += widget.h \common.h \db.hFORMS    += widget.ui

common.h

#ifndef _COMMON_H_
#define _COMMON_H_#include <QDebug>
#include <QTime>#define _TIME_ qPrintable(QTime::currentTime().toString("hh:mm:ss:zzz"))#define FUNCTION_ENTER qDebug("%s %s %d %s start!",__FILE__,__FUNCTION__,__LINE__,_TIME_);
#define FUNCTION_EXIT qDebug("%s %s %d %s end!",__FILE__,__FUNCTION__,__LINE__,_TIME_);#endif //_COMMON_H_

db.h

#ifndef _DB_H_
#define _DB_H_#include <QSqlDatabase>
#include <QSqlQuery>class DBManager
{
public:enum DBMANAGER_TYPE{DBMANAGER_OK = 0,DBMANAGER_ERR,};public:static DBManager * GetInstance();static void DestroyInstance();int ExecSql(QString strSql);int ExecSql(QString strSql, QSqlQuery &query);private:DBManager();~DBManager();void InitDb();private:static DBManager *m_pManager;QSqlDatabase m_db;
};#endif //_DB_H_

widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QTcpServer>namespace Ui {
class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();void InitServer();void InitWidget();private slots:void OnNewConnection();void on_listen_bt_clicked();void Insert();void on_pushButton_2_clicked();private:Ui::Widget *ui;QTcpServer *m_pServer;
};#endif // WIDGET_H

db.cpp

#include "common.h"
#include "db.h"
#include <QSqlError>DBManager *DBManager::m_pManager = NULL;int DBManager::ExecSql(QString strSql, QSqlQuery &query)
{FUNCTION_ENTER;if (strSql.length() == 0){return DBMANAGER_ERR;}query = m_db.exec(strSql);if (m_db.lastError().isValid()){qDebug() << m_db.lastError().text();return DBMANAGER_ERR;}FUNCTION_EXIT;return DBMANAGER_OK;
}int DBManager::ExecSql(QString strSql)
{FUNCTION_ENTER;if (strSql.length() == 0){return DBMANAGER_ERR;}m_db.exec(strSql);if (m_db.lastError().isValid()){qDebug() << m_db.lastError().text();return DBMANAGER_ERR;}FUNCTION_EXIT;return DBMANAGER_OK;
}DBManager::DBManager()
{FUNCTION_ENTER;FUNCTION_EXIT;
}DBManager::~DBManager()
{FUNCTION_ENTER;FUNCTION_EXIT;
}DBManager *DBManager::GetInstance()
{FUNCTION_ENTER;if (NULL == m_pManager){m_pManager = new DBManager();m_pManager->InitDb();}FUNCTION_EXIT;return m_pManager;
}void DBManager::DestroyInstance()
{FUNCTION_ENTER;if (NULL != m_pManager){delete m_pManager;m_pManager = NULL;}FUNCTION_EXIT;
}void DBManager::InitDb()
{FUNCTION_ENTER;m_db = QSqlDatabase::addDatabase("QMYSQL");m_db.setHostName("localhost");m_db.setDatabaseName("text");m_db.setUserName("root");m_db.setPassword("123456");if (m_db.open()){qDebug() << "open ok";}FUNCTION_EXIT;
}

main.cpp

#include "widget.h"
#include <QApplication>
#include <QSqlDatabase> //sql驱动基础
#include <QSqlQuery>//sql查询相关
#include <QSqlError>//sql输出错误int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.InitServer();w.InitWidget();w.show();return a.exec();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QHostAddress>
#include <QTcpSocket>
#include "common.h"
#include "db.h"
#include <QTableWidgetItem>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);m_pServer = NULL;
}Widget::~Widget()
{delete ui;
}void Widget::InitServer()
{qDebug() << "Widget::InitServer() enter";if (NULL == m_pServer){m_pServer = new QTcpServer(this);connect(m_pServer, SIGNAL(newConnection()), this, SLOT(OnNewConnection()));}qDebug() << "Widget::InitServer() exit";
}void Widget::InitWidget()
{FUNCTION_ENTER;ui->tableWidget->setColumnCount(2);ui->tableWidget->setRowCount(5);QStringList strList;strList << "id"<<"name"  ;ui->tableWidget->setHorizontalHeaderLabels(strList);ui->tableWidget->setAutoScroll(true);ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);ui->tableWidget->setSelectionBehavior( QAbstractItemView::SelectRows);FUNCTION_EXIT;
}void Widget::OnNewConnection()
{qDebug() << "new connection";QTcpSocket *pTmp = m_pServer->nextPendingConnection();if (NULL != pTmp){connect(pTmp, SIGNAL(readyRead()), this, SLOT(Insert()));}
}void Widget::on_listen_bt_clicked()
{qDebug() << "Widget::on_listen_bt_clicked() enter";if (NULL == m_pServer){return;}QString strIP = ui->ip_edit->text();QString strPort = ui->port_edit->text();if (strIP.length() == 0 || strPort.length() == 0){qDebug() << "input error";return;}bool bRet = m_pServer->listen(QHostAddress(strIP), strPort.toShort());if (bRet == true){qDebug() << "server listen ok";}qDebug() << "Widget::on_listen_bt_clicked() enter";
}void Widget::Insert()
{FUNCTION_ENTER;DBManager *pTmp = DBManager::GetInstance();if (NULL == pTmp){qDebug() << "db error";}QTcpSocket *pTmps = (QTcpSocket *)sender();if (NULL == pTmps){qDebug() << "socket error";return;}QByteArray arr = pTmps->readAll();//qDebug() << arr;QString str(arr);QStringList list = str.split(" ");QString strSql = QString("insert into text2 (id,name) values ('%1', '%2')").arg(list.at(0)).arg(list.at(1));int iRet = pTmp->ExecSql(strSql);if (iRet != DBManager::DBMANAGER_OK){qDebug() << "insert data error";return;}FUNCTION_EXIT;
}void Widget::on_pushButton_2_clicked()
{FUNCTION_ENTER;DBManager *pTmp = DBManager::GetInstance();if (NULL == pTmp){qDebug() << "db error";}QString strSql = "select * from text2";QSqlQuery query;int iRet = pTmp->ExecSql(strSql, query);if (iRet != DBManager::DBMANAGER_OK){qDebug() << "select data error";return;}int i = 0;while(query.next()){int j = 0;for (j = 0; j < 2; j++){//qDebug() << query.value(j).toString();QTableWidgetItem *pItem = new QTableWidgetItem(query.value(j).toString());ui->tableWidget->setItem(i, j, pItem);}i++;}FUNCTION_EXIT;
}

widget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0"><class>Widget</class><widget class="QWidget" name="Widget"><property name="geometry"><rect><x>0</x><y>0</y><width>893</width><height>629</height></rect></property><property name="windowTitle"><string>Widget</string></property><widget class="QLabel" name="label"><property name="geometry"><rect><x>80</x><y>60</y><width>72</width><height>15</height></rect></property><property name="text"><string>ip</string></property></widget><widget class="QLineEdit" name="ip_edit"><property name="geometry"><rect><x>140</x><y>60</y><width>221</width><height>21</height></rect></property></widget><widget class="QLineEdit" name="port_edit"><property name="geometry"><rect><x>140</x><y>100</y><width>221</width><height>21</height></rect></property></widget><widget class="QLabel" name="label_2"><property name="geometry"><rect><x>70</x><y>100</y><width>71</width><height>21</height></rect></property><property name="text"><string>port</string></property></widget><widget class="QPushButton" name="listen_bt"><property name="geometry"><rect><x>400</x><y>100</y><width>93</width><height>28</height></rect></property><property name="text"><string>listen</string></property></widget><widget class="QTableWidget" name="tableWidget"><property name="geometry"><rect><x>60</x><y>170</y><width>531</width><height>301</height></rect></property></widget><widget class="QPushButton" name="pushButton_2"><property name="geometry"><rect><x>670</x><y>180</y><width>101</width><height>31</height></rect></property><property name="text"><string>select</string></property></widget></widget><layoutdefault spacing="6" margin="11"/><resources/><connections/>
</ui>

测试

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/48734.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【React】箭头函数:现代 JavaScript 的高效编程方式

文章目录 一、箭头函数的基本语法二、箭头函数的特性三、在 React 中的常见用法四、最佳实践 在现代 JavaScript 中&#xff0c;箭头函数&#xff08;Arrow Functions&#xff09;是一种简洁的函数表达方式&#xff0c;并且在 React 开发中非常常见。箭头函数不仅简化了函数的语…

RockyLinux 9 PXE Server bios+uefi 自动化部署 RockLinux 8 9

pxe server 前言 PXE&#xff08;Preboot eXecution Environment&#xff0c;预启动执行环境&#xff09;是一种网络启动协议&#xff0c;允许计算机通过网络启动而不是使用本地硬盘。PXE服务器是实现这一功能的服务器&#xff0c;它提供了启动镜像和引导加载程序&#xff0c;…

前端开发知识(三)-javascript

javascript是一门跨平台、面向对象的脚本语言。 一、引入方式 1.内部脚本&#xff1a;使用<script> &#xff0c;可以放在任意位置&#xff0c;也可以有多个&#xff0c;一般是放在<body></body>的下方。 2.外部脚本&#xff1a;单独编写.js文件&#xff…

HarmonyOS实现跨语言交互(Node-API)

Node-API简介 通过Native接口&#xff0c;实现两种代码的交互。 是在Node.js提供的Node-API基础上扩展而来&#xff0c;但与Node.js中的Node-API不完全兼容。本质就是提供了对C/C代码的使用接口&#xff0c;使得两种代码共同工作。规范I/O、CPU密集型、OS底层等能力。 应用场景…

景区AR导航营销系统:技术解决方案与实施效益分析

随着旅游市场的竞争日益激烈&#xff0c;景区需要不断创新以吸引游客。景区 AR 导航将虚拟画面与现实场景相结合&#xff0c;为游客提供了更加直观、生动的导航服务。对于景区而言&#xff0c;这一创新技术无疑是吸引游客目光、提升景区知名度的有力武器。通过独特的 AR 导航体…

CentOS怎么关闭自动锁屏?

禁止自动锁屏 有时候几分钟不用Centos&#xff0c;系统就自动锁屏了&#xff0c;这是一种安全措施&#xff0c;防止别人趁你不在时使用你的系统。但对于大部分人而言&#xff0c;这是没有必要的&#xff0c;尤其是Centos虚拟机&#xff0c;里面没啥重要的东西&#xff0c;每次…

STM32-寄存器ADC配置指南

目录 输入方式&#xff1a; 模拟看门狗功能&#xff1a; ADC中断 配置一个Demo 设置时钟 自校准 通道选择 采样时间选择 转换模式选择 断续模式 启动转换 软件触发 外部触发 转换结束 关于DMA 模拟看门狗 ​编辑ADC数据位置​编辑 在STM32F中&#xff0c;ADC可…

手写数字识别(机器学习)

一&#xff1a;一对多分类方法(one-vs-all) 这里先上的代码&#xff0c;想看原理可以到代码下面。 在数据集中&#xff0c;y的取值为1~10&#xff0c;y10表示当前数字为0 首先读取数据,并对数据进行切分。 import pandas as pd import numpy as np import matplotlibmatplo…

【BUG】已解决:IndexError: positional indexers are out-of-bounds

IndexError: positional indexers are out-of-bounds 目录 IndexError: positional indexers are out-of-bounds 【常见模块错误】 【解决方案】 原因分析 解决方法 示例代码 欢迎来到英杰社区https://bbs.csdn.net/topics/617804998 欢迎来到我的主页&#xff0c;我是博…

JavaScript:数组排序(冒泡排序)

目录 一、数组排序 二、sort()方法 1、基本语法 2、默认排序 3、自定义排序 三、冒泡排序 1、基本概念 2、实现步骤 3、过程解析 4、代码示例 5、时间复杂度 一、数组排序 对一个给定数组进行处理&#xff0c;使其从无序变为有序&#xff0c;这个过程就是数组排序&…

二叉树基础及实现(二,加经典OJ)

目录&#xff1a; 一 .接引二叉树(一) 二 .二叉树相关oj题&#xff1a; 1. 检查两颗树是否相同 2. 另一颗树的子树 3. 翻转二叉树 4. 判断一颗二叉树是否是平衡二叉树 5. 对称二叉树 6. 二叉树的构建及遍历 7. 二叉树的分层遍历 8. 给定一个二叉树, 找到该树中两个指定节点的最…

Fine-BI学习笔记

官方学习文档&#xff1a;快速入门指南- FineBI帮助文档 FineBI帮助文档 (fanruan.com) 1.零基础入门 1.1 功能简介 完成四个流程&#xff1a;新建分析主题、添加数据、分析数据、分享协作。 示例数据获取&#xff1a;5分钟上手FineBI - FineBI帮助文档 (fanruan.com) 1.2 …

R语言优雅的进行广义可加模型泊松回归分析

泊松回归&#xff08;Poisson regression&#xff09;是以结局变量为计数结果时的一种回归分析。泊松回归在我们的生活中应用非常广泛&#xff0c;例如&#xff1a;1分钟内过马路人数&#xff0c;1天内火车站的旅客流动数&#xff0c;1天内的银行取钱人数&#xff0c;一周内的销…

【已解决】如何使用母版视图统一PPT格式?

母版视图在PPT中是一个强大的工具&#xff0c;可以帮助我们统一幻灯片的格式、布局和设计风格。今天来看看如何利用母版视图统一PPT格式&#xff0c;让每张幻灯片看起来一致和专业。 第一步&#xff1a;打开母版视图 打开PPT后&#xff0c;在顶部菜单栏中&#xff0c;选择【视…

Docker容器限制内存与CPU使用

文章目录 Docker 容器限制内存与 CPU 使用内存限额内存限制命令举例使用 `nginx` 镜像学习内存分配只指定 `-m` 参数的情况CPU 限制命令举例验证资源使用Docker 容器限制内存与 CPU 使用 在生产环境中,为了保证服务器不因某一个软件导致服务器资源耗尽,我们会限制软件的资源…

windows服务器启动apache失败,提示请通过cmd命令行启动:net start apache

Windows Server 2012 R2服务器突然停止运行apche&#xff0c;启动apache失败&#xff0c;提示请通过cmd命令行启动:net start apache 1.报错截图&#xff1a; 进入服务里输入命令启动也不行&#xff0c;提示由于登录失败而无法启动服务。 2.问题原因&#xff1a; 服务器www用…

Node.js知识点总结

Node.js知识点总结 Node.js其本质和浏览器一样是一个JavaScript运行环境。浏览器的运行环境为V8引擎浏览器内置API&#xff08;BOM、DOM、Canvas);而node.js的运行环境是V8引擎node提供的API(fs、path、http)。它使JavaScript可以编写后端。 基本知识 fs文件系统模块 它提供一…

springboot宠物相亲平台-计算机毕业设计源码16285

目 录 摘要 1 绪论 1.1 选题背景与意义 1.2国内外研究现状 1.3论文结构与章节安排 2 开发环境及相关技术介绍 2.1 MySQL数据库的介绍 2.2 B/S架构的介绍 2.3 Java语言 2.4 SpringBoot框架 3 宠物相亲平台系统分析 3.1 可行性分析 3.1.1 技术可行性分析 3.1.2 经济…

基于FPGA + Qt + OpenCv的人脸考勤系统

一:界面设计 客户端界面设计: 服务端界面设计: 简介:首先服务端在注册界面先注册人脸,然后客户端界面进行人脸识别,将人脸识别的图像发送给服务端以后,服务端在图像数据库里寻找人脸比对,若有数据就将查询到的个人信息发送给客户端,并在客户端显示,查询界面是用来查…

Ribbon负载均衡与内核原理

什么是Ribbon? 目前主流的负载方案分为两种&#xff1a; 集中式负载均衡&#xff0c;在消费者和服务提供方中间使用独立的代理方式进行负载&#xff0c;有硬件的&#xff08;比如F5&#xff09;&#xff0c;也有软件的&#xff08;Nginx&#xff09;客户端根据自己的请求做负…