如何通过C#将Modbus RTU设备中的数据更新为Form

问题描述 投票:0回答:1

我想更新从寄存器Modbus设备读取的值,然后每秒钟显示在Windows窗体上,这是我由C#编写的代码

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            RTU2();
        }
        catch (Exception ex)
        {

           MessageBox.Show(ex.StackTrace, "Error");
        }

    //    Console.ReadKey();
    }
    public  void RTU2()
    {

        using (SerialPort port = new SerialPort("COM7"))
        {

            ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
            {

                // configure serial port
                port.BaudRate = 19200;
                port.DataBits = 8;
                port.Parity = Parity.None;
                port.StopBits = StopBits.One;
                port.Open();
                while (true)
                {
                    {
                        // create modbus master
                        ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);

                        byte slaveId = 1;
                        int startua1 = int.Parse(txtUA1.Text.Trim(), System.Globalization.NumberStyles.HexNumber);
                        ushort startAddressua1 = (ushort)startua1;

                        // read large value in two 16 bit chunks and perform conversion
                        Thread.Sleep(100); // Delay 100ms
                        ushort[] registersua = master.ReadHoldingRegisters(slaveId, startAddressua1, 2);



                        float UAV = (float)(decimal)valueua / 100000;

                        //DISPLAY VALUE ON FORM
                        UA.Text = UAV.ToString("###,###.00");//'Cross-thread operation not valid: Control 'UA' accessed from a thread other than the thread it was created on.'


                        Thread.Sleep(2000); // Delay 20ms
                    }
                }

            }));

        }

但是,这是错误的。 enter image description here

[请帮助我,我应该如何修改该代码以使其运行良好,谢谢]

c# modbus
1个回答
0
投票
[似乎UA是一个控件,并且您试图在UA.Text中的非UI线程中修改ThreadPool

要实现这一点,请将您的值保存在m_szUAV中,并在System.Windows.Forms.Timer的Tick事件中将m_szUAV更新为UA.Text。

System.Windows.Forms.Timer timer; public Form1() { // Constructor's original code InitializeComponent(); // Initial your timer timer = new System.Windows.Forms.Timer(); timer.Interval = 50; timer.Tick += Timer_Tick; } string m_szUAV = string.Empty; public void RTU2() { // your code of modbus here // I do not post it again. float UAV = (float)(decimal)valueua / 100000; //Save value to private member. m_szUAV = UAV.ToString("###,###.00"); } private void Timer_Tick( object sender, EventArgs e ) { UA.Text = m_szUAV; }

© www.soinside.com 2019 - 2024. All rights reserved.