Bootstrap

QT与基恩士PLC采用上位链路通信实现

QT与基恩士PLC采用上位链路通信实现

也可以称为tcp/ip通信。只不过需要和基恩士的通讯协议相匹配。

1.pro文件中添加:

QT       += core gui serialport network

2. 头文件:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpSocket>
#include <QTimer>
#include <QString>
#include<QPushButton>
#include<QLineEdit>
#include<QLabel>
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QLineEdit>
#include <QMessageBox>
#include <QHostAddress>
#include <iostream>
#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();



public slots:


    void onSocketConnected();
    void onSocketDisconnected();
    void onSocketError(QAbstractSocket::SocketError socketError);
    void onReadyRead();

private slots:

    void on_connectButton_clicked();

    void on_readButton_clicked();

    void on_sendButton_clicked();

    void on_disconnectButton_clicked();

private:
    void connectToPLC();
    bool isConnected();
    Ui::MainWindow *ui;
    QTcpSocket *clientSocket;
    int m_nState;

    // 定义状态常量
    static const int IN_OFFLINE = 0;
    static const int IN_CONNECTING = 1;
    static const int IN_IDLE = 2;

    struct {
        unsigned char nField0;
        unsigned char nField1;
        unsigned char nField2;
        unsigned char nField3;
        unsigned short nPort;
    } ipCom;

    bool WriteWord(int address, int wordValue);
    bool ReadWord(int address, int &value);


};
#endif // MAINWINDOW_H

3.连接PLC

void MainWindow::connectToPLC()
{
    if (clientSocket->state() == QAbstractSocket::UnconnectedState) {

        clientSocket->connectToHost(QHostAddress(QString("%1.%2.%3.%4")
                                                .arg(ipCom.nField0)
                                                .arg(ipCom.nField1)
                                                .arg(ipCom.nField2)
                                                .arg(ipCom.nField3)),
                                   ipCom.nPort);

    } else {
        clientSocket->disconnectFromHost();

    }
}

void MainWindow::on_connectButton_clicked()
{
    QString ipAddress = ui->ipLineEdit->text();

           // 将输入的 IP 地址拆分成四部分
           QStringList ipParts = ipAddress.split(".");

           // 检查输入是否有效(是否正好有四个部分)
           if (ipParts.size() == 4) {
               bool ok = true;

               // 将每部分转换为 unsigned char 类型,并赋值给结构体
               ipCom.nField0 = ipParts[0].toUInt(&ok); // 转换为整数
               ipCom.nField1 = ipParts[1].toUInt(&ok);
               ipCom.nField2 = ipParts[2].toUInt(&ok);
               ipCom.nField3 = ipParts[3].toUInt(&ok);

            }
           ipCom.nPort = ui->portLineEdit->text().toInt();
    connectToPLC();
}

4.读写寄存器

…略…

5实现效果:

在这里插入图片描述
quan * bu * dai *ma *qing *si * liao

;