QT串口和数据库通信

创建串口

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

client.pro

#-------------------------------------------------
#
# Project created by QtCreator 2024-07-02T14:11:20
#
#-------------------------------------------------

QT       += core gui network
QT       += core gui serialport

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = 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.0


SOURCES += main.cpp\
        widget.cpp

HEADERS  += widget.h

FORMS    += 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_OBJECT

public:
    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 sql

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = 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.0


SOURCES += main.cpp\
        widget.cpp \
    db.cpp

HEADERS  += widget.h \
    common.h \
    db.h

FORMS    += 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_OBJECT

public:
    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>

测试

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Qt串口通信库来接收传感器发送的温度数据,并将其保存到数据库中。下面是一个简单的示例代码: ``` #include <QCoreApplication> #include <QSerialPort> #include <QSqlDatabase> #include <QSqlQuery> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // 设置串口参数 QSerialPort serial; serial.setPortName("COM1"); serial.setBaudRate(QSerialPort::Baud9600); serial.setDataBits(QSerialPort::Data8); serial.setParity(QSerialPort::NoParity); serial.setStopBits(QSerialPort::OneStop); // 打开串口 if (!serial.open(QIODevice::ReadWrite)) { qDebug() << "Error: " << serial.errorString(); return -1; } // 连接数据库 QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("temp.db"); if (!db.open()) { qDebug() << "Error: " << db.lastError().text(); return -1; } // 创建表格 QSqlQuery query; query.exec("CREATE TABLE IF NOT EXISTS Temperature (id INTEGER PRIMARY KEY AUTOINCREMENT, temp REAL)"); // 循环读取串口数据并保存到数据库中 while (true) { if (serial.bytesAvailable()) { QByteArray data = serial.readAll(); QString temp = QString::fromLatin1(data).trimmed(); qDebug() << "Temperature: " << temp; // 保存到数据库 query.prepare("INSERT INTO Temperature (temp) VALUES (:temp)"); query.bindValue(":temp", temp.toDouble()); if (!query.exec()) { qDebug() << "Error: " << query.lastError().text(); } } QCoreApplication::processEvents(); } return a.exec(); } ``` 这段代码会从串口读取数据,将其转换为温度值,并将其保存到名为“temp.db”的SQLite数据库中的“Temperature”表中。您可以使用Qt的SQL模块来查询数据库并显示数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值