梦雨天涯
微信hui530527   &
级别: 网络英雄
精华主题: 0
发帖数量: 4646 个
工控威望: 8045 点
下载积分: 17186 分
在线时间: 3225(小时)
注册时间: 2016-10-31
最后登录: 2025-04-23
查看梦雨天涯的 主题 / 回贴
楼主  发表于: 昨天
问题是我是一个PLC工程师,想用写一个上位机程序和三菱FX3U通讯,PLC的IP地址为192.168.0.250,端口号为5551.要求显示X0到X7,输出显示Y0到Y7,还有M0到M9切换按钮,输出格式为直接打开的exe文件
以下是使用C#开发的三菱FX3U上位机通信程序实现方案,包含可直接运行的EXE文件生成方法:
一、开发环境配置
‌开发工具‌:
Visual Studio 2022 (社区版)
.NET Framework 4.8
通信参数‌
NuGet包:Mx.Component.Melsec(三菱协议库)
var config = new MelsecConfiguration {
    ProtocolType = ProtocolType.TCP,
    Host = "192.168.0.250",
    Port = 5551,
    CpuType = CpuType.FX3U,
    ConnectTimeout = 3000
};
二、界面设计(Windows Forms)
<!-- MainForm.Designer.cs -->
this.Controls.AddRange(new Control[] {
    // X0-X7状态指示灯
    new StatusLight { Name="x0", Location=new Point(20,20) },
    // ...重复创建x1-x7
    
    // Y0-Y7状态显示
    new StatusLight { Name="y0", Location=new Point(120,20) },
    // ...重复创建y1-y7
    
    // M0-M9切换按钮
    new ToggleButton { Name="m0", Text="M0", Location=new Point(220,20) },
    // ...创建m1-m9
    
    // 状态栏
    new StatusStrip {
        Items = {
            new ToolStripStatusLabel { Name="lblStatus" }
        }
    }
});
三、核心通信代码
public partial class MainForm : Form {
    private MelsecFxPLC plc;
    
    // 初始化PLC连接
    private void ConnectPLC() {
        plc = new MelsecFxPLC(config);
        var result = plc.Connect();
        
        if (result.IsSuccess) {
            timer1.Interval = 500;  // 500ms轮询周期
            timer1.Start();
        }
    }

    // 定时读取状态
    private void timer1_Tick(object sender, EventArgs e) {
        // 批量读取X/Y状态
        var xStatus = plc.ReadBytes("X0", 1);
        var yStatus = plc.ReadBytes("Y0", 1);
        
        // 更新指示灯
        UpdateLights(xStatus, "x");
        UpdateLights(yStatus, "y");
    }

    // M按钮点击事件
    private void mButton_Click(object sender, EventArgs e) {
        var btn = sender as ToggleButton;
        plc.WriteBit($"M{btn.Tag}", btn.Checked);
    }
}
四、可视化组件类
// 状态指示灯控件
public class StatusLight : PictureBox {
    public StatusLight() {
        Size = new Size(30, 30);
        BackColor = Color.Silver;
    }

    public bool Active {
        set => BackColor = value ? Color.Lime : Color.Red;
    }
}

// 切换按钮控件
public class ToggleButton : CheckBox {
    public ToggleButton() {
        Appearance = Appearance.Button;
        TextAlign = ContentAlignment.MiddleCenter;
        Size = new Size(50, 30);
    }
}
五、项目打包部署
‌发布设置‌:

项目属性 → 发布 → 选择"从CD/USB安装"
包含.NET Framework 4.8运行库
生成单文件EXE
‌依赖文件‌
├── MelsecFx.dll
├── Newtonsoft.Json.dll
└── Mx.Component.Core.dll
六、协议处理流程图
sequenceDiagram
    participant UI as 上位机
    participant PLC as FX3U PLC
    
    UI->>PLC: TCP Connect(192.168.0.250:5551)
    PLC-->>UI: 连接成功响应
    
    loop 500ms轮询
        UI->>PLC: 读取X0-X7(0x00B0命令)
        PLC-->>UI: X状态数据
        UI->>PLC: 读取Y0-Y7(0x00B0命令)
        PLC-->>UI: Y状态数据
    end
    
    UI->>PLC: 写入M位(0x1401命令)
    PLC-->>UI: 写入确认
七、测试验证步骤
‌PLC准备‌:
; 测试程序
LD M8000
MOV K85 K1Y0  // Y0-Y7循环显示
‌上位机操作检查表‌:
微信hui530527      b站账号,非标自动化谭工
请不要随意加我,不会随便通过。QQ群942493953
zq123666
级别: 工控侠客
精华主题: 0
发帖数量: 539 个
工控威望: 2203 点
下载积分: 26448 分
在线时间: 1185(小时)
注册时间: 2021-03-24
最后登录: 2025-04-23
查看zq123666的 主题 / 回贴
1楼  发表于: 昨天
估计它也在等软件工程师写完程序并在网上开源吧!
工控tucao
级别: 略有小成
精华主题: 0
发帖数量: 192 个
工控威望: 374 点
下载积分: 875 分
在线时间: 170(小时)
注册时间: 2013-01-30
最后登录: 2025-04-23
查看工控tucao的 主题 / 回贴
2楼  发表于: 昨天
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace MELSEC_FX3U_Comm
{
    public partial class MainForm : Form
    {
        private TcpClient plcClient;
        private NetworkStream stream;
        private Timer refreshTimer;
        private byte station = 0x00;

        // PLC寄存器状态存储
        private bool[] xStatus = new bool[8];
        private bool[] yStatus = new bool[8];
        private bool[] mStatus = new bool[10];

        public MainForm()
        {
            InitializeComponent();
            InitializePLCConnection();
            SetupUI();
            StartRefreshTimer();
        }

        private void InitializePLCConnection()
        {
            try
            {
                plcClient = new TcpClient();
                plcClient.Connect(IPAddress.Parse("192.168.0.250"), 5551);
                stream = plcClient.GetStream();
                StatusLabel.Text = "已连接到PLC";
            }
            catch (Exception ex)
            {
                StatusLabel.Text = $"连接失败: {ex.Message}";
            }
        }

        private void SetupUI()
        {
            // 初始化输入显示区域
            for (int i = 0; i < 8; i++)
            {
                var cb = new CheckBox
                {
                    Text = $"X{i}",
                    Location = new Point(20 + (i % 4) * 80, 20 + (i / 4) * 30),
                    AutoSize = true
                };
                xCheckBoxes.Add(cb);
                this.Controls.Add(cb);
            }

            // 初始化输出显示区域
            for (int i = 0; i < 8; i++)
            {
                var cb = new CheckBox
                {
                    Text = $"Y{i}",
                    Location = new Point(200 + (i % 4) * 80, 20 + (i / 4) * 30),
                    AutoSize = true
                };
                yCheckBoxes.Add(cb);
                this.Controls.Add(cb);
            }

            // 初始化M寄存器按钮
            for (int i = 0; i < 10; i++)
            {
                var btn = new Button
                {
                    Text = $"M{i}",
                    Location = new Point(380 + (i % 5) * 80, 20 + (i / 5) * 30),
                    Width = 70
                };
                btn.Click += (s, e) => ToggleMRegister(i);
                mButtons.Add(btn);
                this.Controls.Add(btn);
            }
        }

        private void StartRefreshTimer()
        {
            refreshTimer = new Timer { Interval = 500 };
            refreshTimer.Tick += async (s, e) => await ReadPLCData();
            refreshTimer.Start();
        }

        private async Task ReadPLCData()
        {
            try
            {
                // 读取X寄存器
                byte[] xData = ReadRegisters(0x0000, 8);
                for (int i = 0; i < 8; i++)
                    xStatus = (xData[i / 8] & (1 << (7 - (i % 8)))) != 0;

                // 读取Y寄存器
                byte[] yData = ReadRegisters(0x0010, 8);
                for (int i = 0; i < 8; i++)
                    yStatus = (yData[i / 8] & (1 << (7 - (i % 8)))) != 0;

                UpdateUI();
            }
            catch (Exception ex)
            {
                StatusLabel.Text = $"读取错误: {ex.Message}";
            }
        }

        private byte[] ReadRegisters(ushort start, ushort length)
        {
            // 构建读取请求报文
            List<byte> query = new List<byte>
            {
                0x80, 0x00, 0x00, 0x00,           // 起始符
                0x00, 0x02,                         // 控制代码
                (byte)(station), 0x00, 0x00,      // 站号、保留
                (byte)(start >> 8), (byte)start,  // 起始地址
                (byte)(length >> 8), (byte)length,// 寄存器数量
                0x00, 0x00                          // 结束符
            };

            SendCommand(query.ToArray());
            return ReadResponse();
        }

        private void ToggleMRegister(int index)
        {
            mStatus[index] = !mStatus[index];
            WriteRegister(0x2000 + index, mStatus[index] ? 1 : 0);
            mButtons[index].BackColor = mStatus[index] ? Color.LightGreen : SystemColors.Control;
        }

        private void WriteRegister(ushort address, ushort value)
        {
            // 构建写请求报文
            List<byte> query = new List<byte>
            {
                0x80, 0x00, 0x00, 0x00,           // 起始符
                0x00, 0x12,                         // 控制代码
                (byte)(station), 0x00, 0x00,      // 站号、保留
                (byte)(address >> 8), (byte)address,// 地址
                (byte)(value >> 8), (byte)value,  // 值
                0x00, 0x00                          // 结束符
            };

            SendCommand(query.ToArray());
        }

        private void SendCommand(byte[] command)
        {
            stream.Write(command, 0, command.Length);
        }

        private byte[] ReadResponse()
        {
            byte[] buffer = new byte[1024];
            int bytesRead = stream.Read(buffer, 0, buffer.Length);
            Array.Resize(ref buffer, bytesRead);
            return buffer;
        }

        private void UpdateUI()
        {
            // 更新X寄存器显示
            for (int i = 0; i < 8; i++)
                xCheckBoxes.Checked = xStatus;

            // 更新Y寄存器显示
            for (int i = 0; i < 8; i++)
                yCheckBoxes.Checked = yStatus;

            // 更新M寄存器显示
            for (int i = 0; i < 10; i++)
                mButtons.BackColor = mStatus ? Color.LightGreen : SystemColors.Control;
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            plcClient?.Close();
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}