文史赏析古今中外

C#:根据寄存器状态来执行命令

2024-12-22  本文已影响0人  大龙10

1、根据寄存器状态来执行命令

2、程序

using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using EasyModbus;

namespace ModbusTcpExample
{
    public partial class MainForm : Form
    {
        private ModbusClient _modbusClient;

        public MainForm()
        {
            InitializeComponent();
            InitializeModbusClient();
        }

        private void InitializeModbusClient()
        {
            // 初始化Modbus客户端,指定Modbus服务器的IP地址
            _modbusClient = new ModbusClient("192.168.0.100", 502);

            // 尝试连接到Modbus服务器
            try
            {
                _modbusClient.Connect();
                MessageBox.Show("Connected to Modbus server.");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to connect to Modbus server: {ex.Message}");
            }
        }

        private async void CheckRegisterAndExecuteButtonOperationAsync()
        {
            try
            {
                // 异步读取寄存器状态
                int registerValue = await Task.Run(() => _modbusClient.ReadHoldingRegisters(0, 1));

                // 根据寄存器状态执行相应的按钮操作
                if (registerValue == 1)
                {
                    // 寄存器值为1时执行按钮操作
                    ExecuteButtonOperation();
                }
                else
                {
                    // 寄存器值不为1时的处理
                    MessageBox.Show("Register value is not 1.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error reading register: {ex.Message}");
            }
        }

        private void ExecuteButtonOperation()
        {
            // 在这里执行你的按钮操作
            MessageBox.Show("Button operation executed based on register state.");
        }

        private async void myButton_Click(object sender, EventArgs e)
        {
            // 在按钮点击事件中调用异步方法
            await CheckRegisterAndExecuteButtonOperationAsync();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 关闭Modbus客户端连接
            if (_modbusClient.IsConnected)
            {
                _modbusClient.Disconnect();
            }
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读