三菱PLC与上位机进行通讯

c#上位机与三菱PLC(FX3U)串口通讯 项目中会经常用到上位机与PLC之间的串口通信,本文介绍一下C#如何编写上位机代码 与三菱FX3U进行通讯 1. 第一种方法是自己写代码实现,主要代码如下: //对PLC的Y7进行置1 byte[] Y007_ON = { 0x02, 0x37, 0x30, 0x37, 0x30, 0x35, 0x03, 0x30, 0x36 }; //选择串口参数 SerialPort sp = ... 阅读详情
AI摘要

本文详细介绍了三菱FX系列PLC编程口的串行通信协议,包括DEVICEREAD、DEVICEWRITE、FORCEONCMD和FORCEOFFCMD四个命令的帧格式和地址计算方法。同时,提供了C++源代码示例,展示了如何进行读写操作及数据校验。此外,还列出了PLC软元件地址对应的内存区域。

一.三菱Fx系列PLC编程口通讯协议地址算法

三菱PLC编程口通讯协议三菱PLC编程口的通讯协议只有四个命令:

命令命令码目标设备
DEVICE READ CMD“0”X,Y,M,S,T,C,D
DEVICE WRITE CMD“1”X,Y,M,S,T,C,D
FORCE ON CMD“7”X,Y,M,S,T,C
FORCE OFF CMD“8”X,Y,M,S,T,C

五个标示:

ENQ05H请求
ACK06HPLC正确响应
NAK15HPLC错误响应
STX02H报文开始
ETX03H报文结束

使用累加方式的和校验,帧格式如下:
STX CMD DATA … DATA ETX SUM(upper) SUM(lower)
和校验:
SUM= CMD+……+ETX。 如SUM=73H,SUM=“73”。

1.DEVICE READ(读出软设备状态值)

计算机向PLC发送:
始命令 首地址 位数 终和校验
STX CMD   GROUP ADDRESS   BYTES   ETX   SUM
PLC 返回
STX 1ST DATA 2ND DATA … LAST DATA ETX SUM

2.DEVICE WRITE(向PLC 软设备写入值)

计算机向PLC发送:
始命令   首地址  位数   数据   终和校验
PLC 返回
ACK (06H) 接受正确
NAK (15H) 接受错误

3.位设备强制置位/复位

FORCE ON 置位
始命令   地址   终和校验
STX   CMD   ADDRESS   ETX   SUM
02H   37H   ADDRESS   03H   SUM
FORCE OFF 复位
始  命令  地址   终 和校验
STX   CMD   ADDRESS   ETX   SUM
02H   38H   ADDRESS   03H   SUM
PLC 返回
ACK(06H) 接受正确
NAK(15H) 接受错误

4.三菱Fx系列PLC地址对应表

以上就是这些协议,但是由于没有寄存器类型信息,所以地址的计算十分关键,如D100和M100分别对应哪个地址呢?下面就是三菱Fx系列PLC地址对应表。

Public Const PLC_D_Base_AddRess = 4096 
Public Const PLC_D_Special_Base_AddRess = 3584 
Public Const PLC_Y_Group_Base_AddRess = 160 
Public Const PLC_PY_Group_Base_AddRess = 672 
Public Const PLC_T_Group_Base_AddRess = 192 
Public Const PLC_OT_Group_Base_AddRess = 704 
Public Const PLC_RT_Group_Base_AddRess = 1216 
Public Const PLC_M_SINGLE_Base_AddRess = 2048(命令为7或8时) 
Public Const PLC_M_Group_Base_AddRess = 256 
Public Const PLC_PM_Group_Base_AddRess = 768 
Public Const PLC_S_Group_Base_AddRess = 0 
Public Const PLC_X_Group_Base_AddRess = 128 
Public Const PLC_C_Group_Base_AddRess = 448 
Public Const PLC_OC_Group_Base_AddRess = 960 
Public Const PLC_RC_Group_Base_AddRess = 1472 
Public Const PLC_TV_Group_Base_AddRess = 2048 
Public Const PLC_CV16_Group_Base_AddRess = 2560 
Public Const PLC_CV32_Group_Base_AddRess = 3072 

当我们用DEVICE READ命令时,D100地址=100*2+4096;M100地址=100+256;不同的是D类型寄存器存放的是字,M寄存器存放的是位,同样是读两个字节,D100返回的就是PLC中D100地址的值,M类型寄存器返回的是M100到M116的值。所以当我们用FORCE ON 命令时,M100寄存器地址=100+2048;
但三菱公司好像不甘于如此,FORCE ON/Off命令中地址排列与DEVICE READ/WRITE不同,是低位在前高位在后。如Y20,地址是0510H,代码中4个字节地址表示为:1005。(注意:Y寄存器为八进制,如Y20地址=16+1280=0510H)

二.源代码

1.ui文件

在这里插入图片描述

2.PlcConnection.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include "ui_PlcConnection.h"

#include <QtWidgets/QMainWindow>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QtNetwork/QtNetwork>
#include <QAbstractScrollArea>


//#include <QTextCursor>

#include <iostream>

using namespace std;


#define STX 0x02    //报文开始
#define ETX 0x03    //文本结束
#define EOT 0x04    //传送结束
#define ENQ 0x05    //查询
#define ACK 0x06    //PLC肯定响应
#define NAK 0x15    //PLC否定响应

#define DEVICE_READ_CMD  '0'   //读命令,适用软元件X、Y、M、S、T、C、D
#define DEVICE_WRITE_CMD '1'   //写命令,适用软元件X、Y、M、S、T、C、D
#define FORCE_ON_CMD     '7'   //强制通命令,适用软元件X、Y、M、S、T、C
#define FORCE_OFF_CMD    '8'   //强制断命令,适用软元件X、Y、M、S、T、C

namespace Ui
{
    class PlcConnection;
}

class PlcConnection : public QMainWindow
{
    Q_OBJECT

public:
    PlcConnection(QWidget *parent = Q_NULLPTR);
    //explicit PlcConnection(QWidget* parent = nullptr);
    //~PlcConnection();
private:
    Ui::PlcConnectionClass ui;
    QSerialPort serial;//声明串口类

//public:
private:
    //QSerialPort serial;//声明串口类
    QTcpServer* server;
    QTcpSocket* client;
    QUdpSocket* sender;
    QUdpSocket* receiver;
    QTcpSocket* clientConnection[10];
    quint8 index;
    QTimer testTimer;
    quint16 port_old;
    quint16 flag;
    QHostAddress serverAddress;
    QByteArray datagram;
    QTimer* timer;

//public:
private:
    void find_seralport();
    char ConvertHexChar(char ch);
    void StringToHex(QString str, QByteArray& senddata); //字符串转换为十六进制数据0-F
    void on_time_scan_serial();
    uint8_t sum8(uint8_t data[], uint32_t len); //累加和
    int buf2value(char* b);

private slots:
    void on_openPortBtn_clicked();
    void read_Com();			//手动添加的槽函数声明,用于读出串口缓冲区的内容
    void on_sendButton_clicked();
    void on_pushButton_2_clicked();
    void testFunction();
    //void on_BaudBox_currentTextChanged(const QString &arg1);
    void onTimeOut();
    void on_sendButton_2_clicked();
    void on_sendButton_3_clicked();
    void on_sendButton_4_clicked();
    void on_sendButton_5_clicked();
};

#endif // MAINWINDOW_H

3.PlcConnection.cpp

#include "PlcConnection.h"
#include <QTimer>
#include <QMessageBox>
#include "ui_PlcConnection.h"

PlcConnection::PlcConnection(QWidget *parent):QMainWindow(parent)
{
    ui.setupUi(this);

    
    //关闭发送按钮禁能
    ui.sendButton->setEnabled(false);
    ui.sendButton_2->setEnabled(false);
    ui.sendButton_3->setEnabled(false);
    ui.sendButton_4->setEnabled(false);
    ui.sendButton_5->setEnabled(false);

    /*查找可用的串口*/
    find_seralport();

    ui.BaudBox->setCurrentText("9600");
    ui.BitNumBox->setCurrentText("7 bit");
    ui.ParityBox->setCurrentText("EVEN");

    //on_time_scan_serial();
}


/* 串口读取回调 */
void PlcConnection::read_Com()
{
    qDebug("aaa");
    /* 信号到来,读取所有的字符串 */
    QByteArray buf = serial.readAll();
    QDataStream out(&buf, QIODevice::ReadWrite);    //将字节数组读入

    while (!out.atEnd())
    {
        qint8 outChar = 0;
        out >> outChar;   //每字节填充一次,直到结束
        //十六进制的转换
        QString str = QString("%1").arg(outChar & 0xFF, 2, 16, QLatin1Char('0'));
        qDebug() << str;
        ui.recvTextBrowser->insertPlainText(str);
        ui.recvTextBrowser->insertPlainText(" ");
    }

    char* b = buf.data();
    int length = buf.length();

    if (length != 0)
        ui.recvTextBrowser->insertPlainText("\n");

    printf("receive:%d\n", length);
    for (int i = 0; i < length; i++)
    {
        printf("0x%02x ", b[i]);
    }
    printf("\n");

    qDebug() << "length:" << length;

    if (length > 1)
    {
        static char bb[500];
        static int index;

        uint8_t sum = sum8((uint8_t*)b + 1, length - 3);
        unsigned int temp = 0;

        sscanf(b + length - 2, "%02x", &temp);

        printf("temp = 0x%x\n", temp);
        printf("sum = 0x%x\n", sum);

        if (temp == sum && b[0] == 0x02)
        {
            printf("check sum OK\n");
            index = 0;

            QString display;
            for (int i = 0; i < (length - 4) / 4; i++)
            {
                int v = buf2value(b + 1 + i * 4);

                display += QString::number(v) + ",";
            }
            ui.lineEdit->setText(display);
        }
        else
        {
            printf("check sum failed\n");
            memcpy(bb + index, b, length);
            index += length;

            uint8_t sum = sum8((uint8_t*)bb + 1, index - 3);
            unsigned int temp = 0;

            printf("index = %d\n", index);
            sscanf(bb + index - 2, "%02x", &temp);

            printf("temp = 0x%x\n", temp);
            printf("sum = 0x%x\n", sum);

            for (int i = 0; i < index; i++)
            {
                printf("%02x ", bb[i]);
            }
            printf("\n");

            if (temp == sum)
            {
                printf("check sum OK\n");


                QString display;
                for (int i = 0; i < (index - 4) / 4; i++)
                {
                    int v = buf2value(bb + 1 + i * 4);

                    display += QString::number(v) + ",";
                }
                ui.lineEdit->setText(display);

                index = 0;
            }
            else
            {
                printf("check sum failed\n");
                buf.clear();
                fflush(stdout);
                return;
            }

            fflush(stdout);

        }
    }
    else if (length == 1)
    {
        if (b[0] == 0x06)
        {
            qDebug() << "写入成功";
        }
        else if (b[0] == 0x15)
        {
            qDebug() << "写入失败";
        }
    }

    buf.clear();
    fflush(stdout);
}


/**************** 读取 ***************/
void PlcConnection::on_sendButton_2_clicked()
{

    /* 首地址 */
    int addr = ui.spinBox->value();
    qDebug() << addr;

    if (addr >= 0 && addr < 1024)
    {
        uint8_t buf1[100] = { 0x02, DEVICE_READ_CMD, };  //起始、命令

        int d_addr = 0;
        if (ui.comboBox->currentText() == "S")
            d_addr = addr * 2 + 0x0000;
        else if (ui.comboBox->currentText() == "X")
            d_addr = addr * 2 + 0x0080;
        else if (ui.comboBox->currentText() == "Y")
            d_addr = addr * 2 + 0x00A0;
        else if (ui.comboBox->currentText() == "T")
            d_addr = addr * 2 + 0x00C0;
        else if (ui.comboBox->currentText() == "M")  /**/
            d_addr = addr * 2 + 0x0100;
        else if (ui.comboBox->currentText() == "C")
            d_addr = addr * 2 + 0x01C0;
        else if (ui.comboBox->currentText() == "D")  /**/
            d_addr = addr * 2 + 0x1000;


        char d_addr_str[5] = { 0 };
        snprintf(d_addr_str, 5, "%04X", d_addr);
        /* 地址不需要倒序,值需要倒序 */
        for (int i = 0; i < 4; i++)
            buf1[2 + i] = d_addr_str[i];


        /* 字节数 */
        char count_str[3] = { 0 };
        int count = ui.spinBox_2->value() * 2;
        snprintf(count_str, 3, "%02X", count);
        buf1[6] = count_str[0];
        buf1[7] = count_str[1];

        /* 结束 */
        buf1[8] = ETX;

        /* 累加和 */
        //从命令开始到结束为止的每一个字节累加和(不包括起始字节)
        uint8_t sum = sum8(buf1 + 1, 8);
        char sum_str[3] = { 0 };
        snprintf(sum_str, 3, "%02X", sum);
        buf1[9] = sum_str[0];
        buf1[10] = sum_str[1];

        /* 打印 */
        printf("send:\n");
        for (int i = 0; i < 11; i++)
            printf("%02x ", buf1[i]);
        printf("\n");

        serial.write((char*)buf1, 11);

        QString str;
        for (int i = 0; i < 11; i++)
        {
            char tmp[4] = { 0 };
            sprintf(tmp, "%02x ", buf1[i]);
            str += tmp;
        }
        qDebug() << str;

        ui.lineEdit_sand1_2->setText(str);
    }
    else if (addr >= 8000 && addr < 8512)
    {
        uint8_t buf1[100] = { 0x02, 'E', '0', '0', };  //起始、命令

        int d_addr = (addr - 8000) * 2;
        d_addr += 0x8000;
        char d_addr_str[5] = { 0 };
        snprintf(d_addr_str, 5, "%04X", d_addr);

        for (int i = 0; i < 4; i++)
            buf1[4 + i] = d_addr_str[i];

        /* 字节数 */
        char count_str[3] = { 0 };
        int count = ui.spinBox_2->value() * 2;
        snprintf(count_str, 3, "%02X", count);
        buf1[8] = count_str[0];
        buf1[9] = count_str[1];

        /* 结束 */
        buf1[10] = ETX;

        /* 累加和 */
        //从命令开始到结束为止的每一个字节累加和(不包括起始字节)
        uint8_t sum = sum8(buf1 + 1, 10);
        char sum_str[3] = { 0 };
        snprintf(sum_str, 3, "%02X", sum);
        buf1[11] = sum_str[0];
        buf1[12] = sum_str[1];

        /* 打印 */
        printf("send:\n");
        for (int i = 0; i < 13; i++)
            printf("%02x ", buf1[i]);
        printf("\n");

        serial.write((char*)buf1, 13);
    }

    fflush(stdout);
}


/********************** 写入 **********************/
void PlcConnection::on_sendButton_3_clicked()
{


    uint8_t buf1[100] = { 0x02, DEVICE_WRITE_CMD, };  //起始、命令:写

    /* 首地址 */
    int addr = ui.spinBox->value();
    if (addr >= 0 && addr < 1024)
    {
        int d_addr = 0;
        if (ui.comboBox->currentText() == "S")
            d_addr = addr * 2 + 0x0000;
        else if (ui.comboBox->currentText() == "Y")
            d_addr = addr * 2 + 0x00A0;
        else if (ui.comboBox->currentText() == "X")
            d_addr = addr * 2 + 0x0080;
        else if (ui.comboBox->currentText() == "T")
            d_addr = addr * 2 + 0x00C0;
        else if (ui.comboBox->currentText() == "M")
            d_addr = addr * 2 + 0x0100;
        else if (ui.comboBox->currentText() == "C")
            d_addr = addr * 2 + 0x01C0;
        else if (ui.comboBox->currentText() == "D")
            d_addr = addr * 2 + 0x1000;

        char d_addr_str[5] = { 0 };
        snprintf(d_addr_str, 5, "%04X", d_addr);
        for (int i = 0; i < 4; i++)
            buf1[2 + i] = d_addr_str[i];

        /* 字节数 */
        char count_str[3] = { 0 };
        int count = ui.spinBox_2->value() * 2;
        snprintf(count_str, 3, "%02X", count);
        buf1[6] = count_str[0];
        buf1[7] = count_str[1];

        count /= 2;


        QString str = ui.lineEdit->text();
        QStringList list = str.split(",", QString::SkipEmptyParts);
        qDebug() << list.length();

        if (list.length() < count)
        {
            qDebug() << "请输入足够多的数据";
            QMessageBox::critical(nullptr, "提醒", "请输入足够多的数据", QMessageBox::Ok, 0);
            return;
        }


        char v[5][5];

        for (int i = 0; i < count; i++)
        {
            qDebug() << list[i];
            QByteArray ba = list.at(i).toLatin1();
            char* c_str = ba.data();
            snprintf(v[i], 5, "%04X", atoi(c_str));
            qDebug() << v[i];

            buf1[8 + i * 4 + 2] = v[i][0];
            buf1[8 + i * 4 + 3] = v[i][1];
            buf1[8 + i * 4 + 0] = v[i][2];
            buf1[8 + i * 4 + 1] = v[i][3];
        }


        /* 结束 */
        buf1[8 + count * 4] = ETX;

        /* 累加和 */
        //从命令开始到结束为止的每一个字节累加和(不包括起始字节)
        uint8_t sum = sum8(buf1 + 1, 8 + count * 4);
        char sum_str[3] = { 0 };
        snprintf(sum_str, 3, "%02X", sum);
        buf1[9 + count * 4] = sum_str[0];
        buf1[10 + count * 4] = sum_str[1];

        /* 打印 */
        printf("send:\n");
        for (int i = 0; i < 11 + count * 4; i++)
            printf("%02x ", buf1[i]);
        printf("\n");

        serial.write((char*)buf1, 11 + count * 4);
        fflush(stdout);
    }
    else if (addr >= 8000 && addr < 8512)
    {
        uint8_t buf1[100] = { 0x02, 'E', '1', '0', };  //起始、命令:写

        int d_addr = (addr - 8000) * 2;
        d_addr += 0x8000;
        char d_addr_str[5] = { 0 };
        snprintf(d_addr_str, 5, "%04X", d_addr);
        for (int i = 0; i < 4; i++)
            buf1[4 + i] = d_addr_str[i];

        /* 字节数 */
        char count_str[3] = { 0 };
        int count = ui.spinBox_2->value() * 2;
        snprintf(count_str, 3, "%02X", count);
        buf1[8] = count_str[0];
        buf1[9] = count_str[1];

        count /= 2;


        QString str = ui.lineEdit->text();
        QStringList list = str.split(",");
        qDebug() << list.length();

        if (list.length() < count)
        {
            qDebug() << "请输入足够多的数据";
            QMessageBox::critical(0, "提醒", "请输入足够多的数据", QMessageBox::Ok, 0);
            return;
        }

        char v[5][5] = { {0} };
        for (int i = 0; i < count; i++)
        {
            qDebug() << list[i];
            QByteArray ba = list.at(i).toLatin1();
            char* c_str = ba.data();
            snprintf(v[i], 5, "%04X", atoi(c_str));
            qDebug() << v[i];

            buf1[10 + i * 4 + 2] = v[i][0];
            buf1[10 + i * 4 + 3] = v[i][1];
            buf1[10 + i * 4 + 0] = v[i][2];
            buf1[10 + i * 4 + 1] = v[i][3];
        }

        /* 结束 */
        buf1[10 + count * 4] = ETX;

        /* 累加和 */
        //从命令开始到结束为止的每一个字节累加和(不包括起始字节)
        uint8_t sum = sum8(buf1 + 1, 10 + count * 4);
        char sum_str[3] = { 0 };
        snprintf(sum_str, 3, "%02X", sum);
        buf1[11 + count * 4] = sum_str[0];
        buf1[12 + count * 4] = sum_str[1];

        /* 打印 */
        printf("send:\n");
        for (int i = 0; i < 13 + count * 4; i++)
            printf("%02x ", buf1[i]);
        printf("\n");

        serial.write((char*)buf1, 13 + count * 4);
        fflush(stdout);
    }


}



/* 累加和 */
uint8_t PlcConnection::sum8(uint8_t data[], uint32_t len)
{
    uint8_t sum = 0;
    for (uint32_t i = 0; i < len; i++)
    {
        sum += data[i];
    }

    return sum;
}

/* 打开串口 */
void PlcConnection::on_openPortBtn_clicked()
{
    if (ui.openPortBtn->text() == "打开")
    {
        ui.openPortBtn->setText("关闭");                         //按下“OpenPort”后,按键显示为“ClosePort”
        //        if(ui->openPortBtn->text() == "打开")
        //        ui->PortBox->setDisabled(true);                          //按下“OpenPort”后,禁止再修改COM口
        serial.setPortName(ui.PortBox->currentText());          //设置COM口

        QSerialPort::BaudRate baud_rate = QSerialPort::Baud115200;
        if (ui.BaudBox->currentText() == "1200")
            baud_rate = QSerialPort::Baud1200;
        else if (ui.BaudBox->currentText() == "9600")
            baud_rate = QSerialPort::Baud9600;
        else if (ui.BaudBox->currentText() == "2400")
            baud_rate = QSerialPort::Baud2400;
        else if (ui.BaudBox->currentText() == "4800")
            baud_rate = QSerialPort::Baud4800;
        else if (ui.BaudBox->currentText() == "9600")
            baud_rate = QSerialPort::Baud9600;
        else if (ui.BaudBox->currentText() == "19200")
            baud_rate = QSerialPort::Baud19200;
        else if (ui.BaudBox->currentText() == "38400")
            baud_rate = QSerialPort::Baud38400;
        else if (ui.BaudBox->currentText() == "57600")
            baud_rate = QSerialPort::Baud57600;
        else if (ui.BaudBox->currentText() == "115200")
            baud_rate = QSerialPort::Baud115200;

        serial.setBaudRate(baud_rate);   //设置波特率

        QSerialPort::DataBits data_bits = QSerialPort::Data8;
        if (ui.BitNumBox->currentText() == "8 bit")
            data_bits = QSerialPort::Data8;
        else if (ui.BitNumBox->currentText() == "7 bit")
            data_bits = QSerialPort::Data7;
        else if (ui.BitNumBox->currentText() == "6 bit")
            data_bits = QSerialPort::Data6;
        else if (ui.BitNumBox->currentText() == "5 bit")
            data_bits = QSerialPort::Data5;

        serial.setDataBits(data_bits);		//设置数据位

        serial.setFlowControl(QSerialPort::NoFlowControl);//无流控制

        QSerialPort::Parity parity = QSerialPort::NoParity;
        if (ui.ParityBox->currentText() == "NONE")
            parity = QSerialPort::NoParity;
        else if (ui.ParityBox->currentText() == "EVEN")
            parity = QSerialPort::EvenParity;
        else if (ui.ParityBox->currentText() == "ODD")
            parity = QSerialPort::OddParity;
        else if (ui.ParityBox->currentText() == "SPACE")
            parity = QSerialPort::SpaceParity;
        else if (ui.ParityBox->currentText() == "MARK")
            parity = QSerialPort::MarkParity;

        serial.setParity(parity);           //设置校验位

        QSerialPort::StopBits stop_bits = QSerialPort::OneStop;
        if (ui.StopBox->currentText() == "1 bit")
            stop_bits = QSerialPort::OneStop;
        else if (ui.StopBox->currentText() == "1.5 bit")
            stop_bits = QSerialPort::OneAndHalfStop;
        else if (ui.StopBox->currentText() == "5 bit")
            stop_bits = QSerialPort::TwoStop;

        serial.setStopBits(stop_bits);	//设置停止位

        serial.close();					//先关串口,再打开,可以保证串口不被其它函数占用。

        if (serial.open(QIODevice::ReadWrite))		//以可读写的方式打开串口
        {
            connect(&serial, SIGNAL(readyRead()), this, SLOT(read_Com()));	//把串口的readyRead()信号绑定到read_Com()这个槽函数上
        }

        ui.sendButton->setEnabled(true);
        ui.sendButton_2->setEnabled(true);
        ui.sendButton_3->setEnabled(true);
        ui.sendButton_4->setEnabled(true);
        ui.sendButton_5->setEnabled(true);

    }
    else
    {
        ui.openPortBtn->setText("打开");		//按下“ClosePort”后,按键显示为“OpenPort”
        ui.PortBox->setEnabled(true);		//按下“ClosePort”后,COM口可被修改
        serial.close();					//关串口
        //关闭发送按钮的使能
        ui.sendButton->setEnabled(false);
        ui.sendButton_2->setEnabled(false);
        ui.sendButton_3->setEnabled(false);
        ui.sendButton_4->setEnabled(false);
        ui.sendButton_5->setEnabled(false);
    }
}

/* 清除按钮 */
void PlcConnection::on_pushButton_2_clicked()
{
    ui.recvTextBrowser->clear();
}

void PlcConnection::testFunction()
{
    //    qDebug() << clientConnection[0]->read(1);
}

int PlcConnection::buf2value(char* b)
{
    char a[4] = { 0 };
    a[0] = b[2];
    a[1] = b[3];
    a[2] = b[0];
    a[3] = b[1];

    for (int i = 0; i < 4; i++)
        printf("%c ", a[i]);
    printf("\n");


    int v = 0;
    sscanf(a, "%04x", &v);
    //    printf("v = %d\n", v);
    return v;
}

void PlcConnection::on_sendButton_clicked()
{
    /* 串口发送 */
    //    serial.write(ui->textEdit_2->toPlainText().toLatin1());
    char buf1[100] = { 0x00 };
    /* 提取参数 */
    QString sand_str(ui.lineEdit_sand1_2->text());
    QString temp;
    int cnt = 0;

    for (int i = 0; ; i++)
    {
        temp = sand_str.left(2);
        if (temp == "")
            break;
        buf1[i] = temp.toInt(nullptr, 16);
        //            qDebug() << buf1[i];
        sand_str = sand_str.mid(3);
        qDebug() << temp;
        cnt++;
    }
    //    clientConnection[ui->comboBox_2->currentIndex()]->write(buf1, cnt);
    //    serial.write(ui->textEdit_2->toPlainText().toLatin1());
    serial.write(buf1, cnt);
}


/* 查找可用的串口 */
void PlcConnection::find_seralport()
{

    foreach(const QSerialPortInfo & info, QSerialPortInfo::availablePorts())
    {
        QSerialPort serial;
        serial.setPort(info);
        if (serial.open(QIODevice::ReadWrite))
        {
            ui.PortBox->addItem(serial.portName());
            serial.close();
        }
    }
}


void PlcConnection::on_time_scan_serial()
{
    timer = new QTimer;
    connect(timer, SIGNAL(timeout()), this, SLOT(onTimeOut()));
    timer->start(1000);
}

void PlcConnection::onTimeOut()
{
    find_seralport();
    qDebug() << "aaa";
}


//void MainWindow::on_BaudBox_currentTextChanged(const QString &arg1)
//{
//    qDebug() << arg1;
//    MainWindow::on_openPortBtn_clicked();
//}


/* 转换 */
void PlcConnection::StringToHex(QString str, QByteArray& senddata) //字符串转换为十六进制数据0-F
{
    int hexdata, lowhexdata;
    int hexdatalen = 0;
    int len = str.length();
    senddata.resize(len / 2);
    char lstr, hstr;

    for (int i = 0; i < len; )
    {
        //char lstr,
        hstr = str[i].toLatin1();
        if (hstr == ' ')
        {
            i++;
            continue;
        }
        i++;
        if (i >= len)
            break;
        lstr = str[i].toLatin1();
        hexdata = ConvertHexChar(hstr);
        lowhexdata = ConvertHexChar(lstr);
        if ((hexdata == 16) || (lowhexdata == 16))
            break;
        else
            hexdata = hexdata * 16 + lowhexdata;
        i++;
        senddata[hexdatalen] = (char)hexdata;
        hexdatalen++;
    }
    senddata.resize(hexdatalen);
}

char PlcConnection::ConvertHexChar(char ch)
{
    if ((ch >= '0') && (ch <= '9'))
        return ch - 0x30;
    else if ((ch >= 'A') && (ch <= 'F'))
        return ch - 'A' + 10;
    else if ((ch >= 'a') && (ch <= 'f'))
        return ch - 'a' + 10;
    else return ch - ch;//不在0-f范围内的会发送成0
}

/* 设置 */
void PlcConnection::on_sendButton_4_clicked()
{


    /* 首地址 */
    int addr = ui.spinBox_3->value();

    if (addr >= 0 && addr < 1024)
    {
        uint8_t buf1[100] = { 0x02, FORCE_ON_CMD, };  //起始、命令:写

        int d_addr = 0;
        if (ui.comboBox_2->currentText() == "S")
            d_addr = addr * 1 + 0x0000;
        else if (ui.comboBox_2->currentText() == "X")
            d_addr = addr * 2 + 0x0400;
        else if (ui.comboBox_2->currentText() == "Y")
            d_addr = addr * 1 + 0x0500;
        else if (ui.comboBox_2->currentText() == "T")
            d_addr = addr * 1 + 0x0600;
        else if (ui.comboBox_2->currentText() == "M")
            d_addr = addr * 1 + 0x0800;
        else if (ui.comboBox_2->currentText() == "C")
            d_addr = addr * 1 + 0x0E00;


        char d_addr_str[5] = { 0 };
        snprintf(d_addr_str, 5, "%04X", d_addr);


        for (int i = 0; i < 2; i++)
            buf1[2 + i + 2] = d_addr_str[i];

        for (int i = 0; i < 2; i++)
            buf1[2 + i] = d_addr_str[i + 2];


        /* 结束 */
        buf1[6] = ETX;

        /* 累加和 */
        //从命令开始到结束为止的每一个字节累加和(不包括起始字节)
        uint8_t sum = sum8(buf1 + 1, 6);
        char sum_str[3] = { 0 };
        snprintf(sum_str, 3, "%02X", sum);
        buf1[7] = sum_str[0];
        buf1[8] = sum_str[1];

        /* 打印 */
        printf("send:\n");
        for (int i = 0; i < 9; i++)
            printf("%02x ", buf1[i]);
        printf("\n");

        serial.write((char*)buf1, 9);
        fflush(stdout);          //清空缓存区
    }

    else if (addr >= 8000 && addr < 8512)
    {
        uint8_t buf1[100] = { 0x02, 'E', '7', };  //起始、命令:写

        int d_addr = 0;
        addr -= 8000;
        d_addr = addr * 1 + 0x6000;

        char d_addr_str[5] = { 0 };
        snprintf(d_addr_str, 5, "%04X", d_addr);

        for (int i = 0; i < 2; i++)
            buf1[3 + i + 2] = d_addr_str[i];

        for (int i = 0; i < 2; i++)
            buf1[3 + i] = d_addr_str[i + 2];


        /* 结束 */
        buf1[7] = ETX;

        /* 累加和 */
        //从命令开始到结束为止的每一个字节累加和(不包括起始字节)
        uint8_t sum = sum8(buf1 + 1, 7);
        char sum_str[3] = { 0 };
        snprintf(sum_str, 3, "%02X", sum);
        buf1[8] = sum_str[0];
        buf1[9] = sum_str[1];

        /* 打印 */
        printf("send:\n");
        for (int i = 0; i < 10; i++)
            printf("%02x ", buf1[i]);
        printf("\n");

        serial.write((char*)buf1, 10);
        fflush(stdout);
    }

}

/* 清除 */
void PlcConnection::on_sendButton_5_clicked()
{


    /* 首地址 */
    int addr = ui.spinBox_3->value();
    if (addr >= 0 && addr < 1024)
    {
        uint8_t buf1[100] = { 0x02, FORCE_OFF_CMD, };  //起始、命令:写

        int d_addr = 0;
        if (ui.comboBox_2->currentText() == "S")
            d_addr = addr * 1 + 0x0000;
        else if (ui.comboBox_2->currentText() == "X")
            d_addr = addr * 2 + 0x0400;
        else if (ui.comboBox_2->currentText() == "Y")
            d_addr = addr * 1 + 0x0500;
        else if (ui.comboBox_2->currentText() == "T")
            d_addr = addr * 1 + 0x0600;
        else if (ui.comboBox_2->currentText() == "M")
            d_addr = addr * 1 + 0x0800;
        else if (ui.comboBox_2->currentText() == "C")
            d_addr = addr * 1 + 0x0E00;

        char d_addr_str[5] = { 0 };
        snprintf(d_addr_str, 5, "%04X", d_addr);


        for (int i = 0; i < 2; i++)
            buf1[2 + i + 2] = d_addr_str[i];

        for (int i = 0; i < 2; i++)
            buf1[2 + i] = d_addr_str[i + 2];


        /* 结束 */
        buf1[6] = ETX;

        /* 累加和 */
        //从命令开始到结束为止的每一个字节累加和(不包括起始字节)
        uint8_t sum = sum8(buf1 + 1, 6);
        char sum_str[3] = { 0 };
        snprintf(sum_str, 3, "%02X", sum);
        buf1[7] = sum_str[0];
        buf1[8] = sum_str[1];

        /* 打印 */
        printf("send:\n");
        for (int i = 0; i < 9; i++)
            printf("%02x ", buf1[i]);
        printf("\n");

        serial.write((char*)buf1, 9);
        fflush(stdout);
    }
    else if (addr >= 8000 && addr < 8512)
    {
        uint8_t buf1[100] = { 0x02, 'E', '8', };  //起始、命令:写

        int d_addr = 0;
        addr -= 8000;
        d_addr = addr * 1 + 0x6000;

        char d_addr_str[5] = { 0 };
        snprintf(d_addr_str, 5, "%04X", d_addr);

        for (int i = 0; i < 2; i++)
            buf1[3 + i + 2] = d_addr_str[i];

        for (int i = 0; i < 2; i++)
            buf1[3 + i] = d_addr_str[i + 2];


        /* 结束 */
        buf1[7] = ETX;

        /* 累加和 */
        //从命令开始到结束为止的每一个字节累加和(不包括起始字节)
        uint8_t sum = sum8(buf1 + 1, 7);
        char sum_str[3] = { 0 };
        snprintf(sum_str, 3, "%02X", sum);
        buf1[8] = sum_str[0];
        buf1[9] = sum_str[1];

        /* 打印 */
        printf("send:\n");
        for (int i = 0; i < 10; i++)
            printf("%02x ", buf1[i]);
        printf("\n");

        serial.write((char*)buf1, 10);
        fflush(stdout);
    }
}

4.main.cpp

#pragma execution_character_set("utf-8")
#include "PlcConnection.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    PlcConnection w;
    w.setWindowTitle("三菱FX3U编程口通信助手");
    w.show();

    return a.exec();
}

运行结果:
在这里插入图片描述

参考资料:

我还下了网上两个别人的实例,若有需要参考的评论区留下邮箱,我把那两个工程文件发给你。。。
在这里插入图片描述
在这里插入图片描述

上位机开发之三菱PLC通信 三菱MC协议是开发三菱系列PLC必须掌握的一种通信协议,其目的是让外部设备,可以通过串行通信模块C24或以太网接口模块E71,实现对可编程控制器CPU的数据访问。MC协议是Melsec协议的简称。 阅读详情

相关推荐

C#上位机与三菱PLC通信实战:MC协议下的数据读写与异常处理

本文详细介绍了C#上位机与三菱PLC通过MC协议实现数据通信的实战方法,包括协议基础、环境搭建、数据读写、异常处理及性能优化。特别针对工业自动化场景,提供了温度监控系统案例和调试技巧,帮助开发者高效实现稳定可靠的PLC通信解决方案。

weixin_29175469的博客 439

C#上位机与三菱PLC的通信02--MC协议介绍

PLC是在继电器控制路线基础上发展起来的,继电器控制线路有时间继电器、中间继电器等,而PLC内部也有类似的器件,由于这些器件以软件形似存在,故称为软元件。PLC程序由指令和软元件组成,指令的功能是发出命令,软元件是指令的执行对象,比如,SET为1指令,Y000是PLC的一种软元件(输出继电器),“SET Y000”就是命令PLC的输出继电器Y000的转台变为1。由此可见,编写PLC程序必须了解PLC的指令级软元件。软元件就是存储区软元件就是存储区软元件就是存储区。

hqwest的专栏 1万+

C#与三菱PLC以太网通讯程序上位机源码 通过3E帧SLMP MC协议与三菱FX5U Q系列PLC通讯

综上所述,C#与三菱PLC以太网通讯程序上位机源码 通过3E帧SLMP MC协议与三菱FX5U Q系列PLC通讯的实现,为工业自动化生产提供了强有力的支持。同时,程序源码的可扩展性也非常强,可以为用户提供更多的自定义功能和定制需求,是一款值得推荐的PLC通讯应用程序。本文将介绍C#与三菱PLC以太网通讯程序上位机源码,其中主要涉及3E帧SLMP MC协议与三菱FX5U Q系列PLC通讯的实现。1.该程序可以与FX5U Q系列PLC以太网通讯,根据3E帧报文写了一个类库,可以读写各种类型和区域变量。

nwejpbz的博客 2635

三菱【PLC】

D128~D7999 保持 D128~D255【EEPROM】 D256~D7999【电容保持】C016~C199 保持用 C16~C31【EEPROM保持】 C32~C199【电容保持】i00~i50 【6点,输入中断指针】T246~T249 1ms 累计【电容保持】T250~T255 100ms累计【电容保持】

cfqq1989的博客 2万+

上位机与PLC 通讯源码 上位机与三菱PLC,西门子PLC通讯

上位机与PLC 通讯源码 上位机与三菱PLC,西门子PLC通讯 同时一起通讯,单独控制,三菱采用官方MX 通讯,支持三菱FX系列,A系列,Q系列,L系列,R系列,全系系列,各种串口和各种网口通讯,, 西门子采用S7.NET通讯,支持S7200,300,400,S71200,1500系列(网口), id=650606243265& 带详细注释源码,写的非常通俗易懂,PLC和上位机通讯,(编程语言采用VB.net) 需要用到上位机采集,PLC通讯数据项目的或者实际项目要用到的童靴可以学习参考程序源码实

m0_64923314的博客 2767

上位机与fx3u通讯串口_c#上位机与三菱PLC(FX3U)串口通讯

项目中会经常用到上位机与PLC之间的串口通信,本文介绍一下C#如何编写上位机代码与三菱FX3U进行通讯1. 第一种方法是自己写代码实现,主要代码如下://对PLC的Y7进行置1byte[] Y007_ON = { 0x02, 0x37, 0x30, 0x37, 0x30, 0x35, 0x03, 0x30, 0x36};//选择串口参数SerialPort sp = new SerialPort(...

weixin_32791013的博客 2854

C#上位机与三菱PLC进行通讯的程序

最近因为做一个项目,需要做一部分上位机与三菱Q系列PLC 的通讯,查阅相当一部分资料,才确定了方案,使用三菱自身的通信MX component软件,可以很方便的实现通信。一、先说逻辑站号+密码的方式,先上代码,这里用到一个通信控件:AxAcUtlType,这个很重要,这个在MX component里有提供的,自己找一下。代码很简单就是,实例化控件,然后填上站号与密码,就可以连接了,这里注意一点,这站号是要在MX component里进行设置的。更详细的操作过程,等后面有空再写吧。

jiang56789的博客 1664

三菱FX-PLC编程口通信地址表

三菱FX-PLC编程口通信地址表,通过PLC编程口快速访问PLC内部资源

【亲测免费】 三菱PLC 与 上位机SLMP通讯参考文档

三菱PLC 与 上位机SLMP通讯参考文档 【下载地址】三菱PLC与上位机SLMP通讯参考文档分享 本资源文件提供了关于三菱PLC与上位机之间使用SLMP协议进行通讯的详细参考文档。该文档旨在帮助用户理解并实现PLC与上位机之间的数据交换,适用于需要进行工业自动化控制和数据采集的工程师和技术人员 ...

gitblog_06642的博客 912

三菱PLC地址表

三菱PLC地址表

Matlab实战:3种雷达间歇采样干扰的仿真与识别(附完整代码)

本文通过Matlab实战,详细仿真了雷达有源间歇采样干扰的三种核心样式:直接转发、重复转发和循环转发干扰。文章提供了完整的代码实现,并深入探讨了基于时频分析和循环平稳分析的特征提取与识别方法,为雷达抗干扰技术的学习与实践提供了清晰的工程实现路径。

weixin_29053695的博客 365

轻松实现C与三菱PLC通讯:一款高效的上位机软件

轻松实现C#与三菱PLC通讯:一款高效的上位机软件 去发现同类优质开源项目:https://gitcode.com/ 项目介绍 在工业自动化领域,C#与三菱PLC的通讯是许多项目中不可或缺的一环。为了简化这一过程,我们推出了一款由个人开发者精心打造的C#上位机软件。该软件通过三菱的AcUtlType控件,实现了与三菱PLC的高效通讯,支持对数据寄存器和中间继电器的灵活读写操作。无论是单个还是多个寄...

gitblog_09763的博客 860

模型参考自适应控制(MRAC):让PID参数动态优化

本文深入解析模型参考自适应控制(MRAC)技术,它通过实时调整PID参数,使控制系统能自动适应系统特性变化和外部干扰。文章详细介绍了MRAC的工作原理、数学基础,并提供了用C语言实现的实战代码示例,帮助工程师解决传统PID控制在非线性、时变系统中参数整定繁琐的难题。

tequila的博客 904

c#rs232与三菱通讯_c#上位机与三菱PLC(FX3U)串口通讯

项目中会经常用到上位机与PLC之间的串口通信,本文介绍一下C#如何编写上位机代码与三菱FX3U进行通讯1. 第一种方法是自己写代码实现,主要代码如下://对PLC的Y7进行置1byte[] Y007_ON = { 0x02, 0x37, 0x30, 0x37, 0x30, 0x35, 0x03, 0x30, 0x36};//选择串口参数SerialPort sp = new SerialPort(...

weixin_39726697的博客 3221

详解Unity中的粒子系统Particle System (三)

上一篇我们详细讲解了有关主模块的全部内容,已经对粒子系统的基本运作有了足够的了解,本篇就来讲一下被粒子系统默认启用的Emission、Shape、Renderer模块又在粒子系统中扮演着怎么样的作用吧。

梦小天幼的博客 1万+

Quartz定时任务调度框架中的Misfire策略实战解析

本文深入解析了Quartz定时任务调度框架中的Misfire(失火)处理策略。针对SimpleTrigger和CronTrigger两种常用触发器,详细对比了其各自的Misfire指令(如NowWithExistingCount、FireAndProceed等)的核心行为与适用场景,并提供了基于不同业务需求(如数据补跑、时间点敏感度)的实战选型指南,帮助开发者构建更健壮可靠的任务调度系统。

weixin_29250573的博客 83

C#上位机与PLC通讯源码 C#与三菱PLC通讯MC协议

C#上位机与PLC通讯源码 C#与三菱PLC通讯MC协议

m0_59677649的博客 2460

SAP-ABAP:SAP客户端管理核心事务码SCC4深度解析

SAP客户端管理核心事务码SCC4深度解析

baidu_35680696的博客 1570

上位机与PLC 通讯源码 DEMO 上位机与三菱PLC,西门子PLC通讯 同时一起通讯,单独控制

最近在工控项目里折腾上位机和PLC联调,发现不少同行对多品牌PLC混搭通讯挺头疼的。刚好手头有个用VB.NET写的双协议通讯DEMO,实测过三菱全系和西门子S7系列,今天把关键代码拆开揉碎了说说。同时一起通讯,单独控制,三菱采用官方MX 通讯,支持三菱FX系列,A系列,Q系列,L系列,R系列,全系系列,各种串口和各种网口通讯,,西门子采用S7.NET通讯,支持S7200,300,400,S71200,1500系列(网口),带详细注释源码,写的非常通俗易懂,PLC和上位机通讯,(编程语言采用VB.NET)

2509_94268297的博客 543

26、机器学习模型的成员推断攻击与隐私保护

本文探讨了机器学习模型面临的成员推断攻击及其对隐私的潜在威胁。通过使用CIFAR-10数据集,详细介绍了如何利用影子模型和攻击模型推断特定数据点是否属于模型的训练集。实验表明,即使无法直接访问模型参数和原始数据,攻击者仍能以高于随机猜测的概率进行推断,从而构成隐私风险。此外,文章还分析了实验的关键技术点,并提出了多种隐私保护建议,包括数据脱敏、差分隐私、模型正则化等方法。

coffee的博客 131

5、癌症数据预处理技术与深度学习在癌症预测中的应用

本文详细介绍了癌症数据预处理技术和深度学习在癌症预测中的应用。针对CT扫描图像、X射线图像、超声图像、基因表达数据和文本数据等不同类型的癌症数据,分别阐述了去噪、插值、配准、归一化等预处理技术的具体方法。同时,分析了深度学习在乳腺癌、白血病和宫颈癌预测中的作用,结合相关影响因素探讨了模型的应用潜力。此外,还总结了深度学习在癌症预测中面临的挑战及未来发展方向,为癌症的早期诊断与精准预测提供了理论支持和技术参考。

alice7model的博客 123

三菱MC协议通讯代码:实现高效PLC与上位机数据交互

三菱MC协议通讯代码:实现高效PLC与上位机数据交互 去发现同类优质开源项目:https://gitcode.com/ 项目介绍 在工业自动化领域,PLC(可编程逻辑控制器)与上位机之间的通讯是实现高效数据交互的关键环节。本项目提供了一个用于三菱Q系列和L系列PLC与VC#上位机进行MC协议通讯的代码资源。该代码经过多个实际项目的应用检验,确保其有效性和可靠性,为开发者提供了一个稳定、高效的通讯解...

gitblog_09776的博客 669

uniapp支付宝/钉钉小程序ref为undefined的解决方案 `uniapp 支付宝小程序 ref undefined` `uniapp 钉钉小程序 组件ref获取失败` `uniapp 支付宝

如果你在uniapp 开发支付宝小程序或钉钉小程序时,遇到ref始终为undefined的问题,十有八九就是没开启 component2。所以记住一句话:👉支付宝/钉钉小程序要想用 ref,必须在里加。

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 1229

上位机与PLC 通讯源码 上位机与三菱PLC,西门子PLC通讯 同时一起通讯,单独控制,三菱采...

同时一起通讯,单独控制,三菱采用官方MX 通讯,支持三菱FX系列,A系列,Q系列,L系列,R系列,全系系列,各种串口和各种网口通讯,,同时一起通讯,单独控制,三菱采用官方MX 通讯,支持三菱FX系列,A系列,Q系列,L系列,R系列,全系系列,各种串口和各种网口通讯,,西门子采用S7.NET通讯,支持S7200,300,400,S71200,1500系列(网口),西门子采用S7.NET通讯,支持S7200,300,400,S71200,1500系列(网口),上位机与三菱PLC,西门子PLC通讯。

2508_94198527的博客 1063

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

【亲测免费】 三菱PLC与上位机SLMP通讯参考文档:工业自动化的新利器

三菱PLC与上位机SLMP通讯参考文档:工业自动化的新利器 【下载地址】三菱PLC与上位机SLMP通讯参考文档分享 本资源文件提供了关于三菱PLC与上位机之间使用SLMP协议进行通讯的详细参考文档。该文档旨在帮助用户理解并实现PLC与上位机之间的数据交换,适用于需要进行工业自动化控制和数据采集的工程师和技术人员 ...

gitblog_06681的博客 888

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

【无标题】C#上位机与三菱PLC FX2NC通讯方法

C# 上位机与三菱PLC FX2NC通讯方法

weixin_52151600的博客 1927

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

上一篇: 【VS2019+QT5报错】:LNK2019无法解析的外部符号“_declspec(dllimport)public:bool_cdecl QSerialPort“
下一篇: 线性表note
小桉桉冲吖
小桉桉冲吖 领域专家: 人工智能技术领域 领域专家: 人工智能技术领域
博客等级 码龄7年 5万+粉丝 339原创
评论 154
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

打赏作者

小桉桉冲吖

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值
⌂ 换网址