C#-编写上位机与PLC通信的心跳信号

[复制链接]
查看33921 | 回复0 | 2024-12-24 17:54:29 | 显示全部楼层 |阅读模式
见视频



video: https://mp.weixin.qq.com/mp/readtemplate?t=pages/video_player_tmpl&action=mpvideo&auto=0&vid=wxv_1647261779061735428
实现方法如下

1-PLC中定时实现每1s,DB100.DBW0的值加1,当到达设定值9时,DB100.DBW0的值变为1,然后继续循环。(设定值可以任意设置,只要不超上限即可)。这里我没有和PLC连接,模拟实现了数值的变化。

2-上位机每1s(可任意设定,但要小于PLC中DB100.DBW0的设定值)从PLC的DB100.DBW0中获取值。并和上一次获取的值进行比较。比较结果不同表示通信正常。

3-定义一个变量,比较结果不同的时候,变量+1;然后定义一个定时器,每1s判断一下这个变量是偶数还是奇数。偶数时显示picturebox可见,picturebox中我们放置了一个心的图片。然后通过图片的可见不可见确认了通信正常。

其它说明:

1-实际中,这些数值的获取,判断,我们都会定义到变量中,并且这些数值不会显示在界面中。这里只是为了想直观的显示整个过程,把这些数值都放到界面中了。也算是抛砖引玉吧。

代码如下:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;
namespaceheartSignal{publicpartialclassForm1 : Form    {publicForm1()        {            InitializeComponent();        }
publicint a,c;publicstring b;privatevoidForm1_Load(object sender, EventArgs e)        {            Thread caiji = new Thread(new ThreadStart(Caiji));            caiji.Start();
            Thread jishu = new Thread(new ThreadStart(Jishu));            jishu.Start();
            timer1.Start();        }
privatevoidJishu()        {while (true)            {             if (a <= 8)                {                    a += 1;                }else                {                    a = 0;                }
if (textBox1.InvokeRequired)                {this.textBox1.Invoke(new Action<string>                           (s => { this.textBox1.Text = s; }), a.ToString());                }                Thread.Sleep(1000);            }        }privatevoidCaiji()        {while (true)            {if (textBox3.InvokeRequired)                {this.textBox3.Invoke(new Action<string>                           (s => { this.textBox3.Text = s; }), b);                }
if (textBox2.InvokeRequired)                {this.textBox2.Invoke(new Action<string>                           (s => { this.textBox2.Text = s; }), textBox1.Text);                    b = textBox2.Text;                }
if (textBox2.Text != textBox3.Text)                {                    c += 1;                }
                Thread.Sleep(1000);            }        }privatevoidtimer1_Tick(object sender, EventArgs e)        {            timer1.Interval = 1000;if (c % 2 == 0)            {                pictureBox1.Visible = true;            }else            {                pictureBox1.Visible = false;            }        }    }}



本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册哦

x
您需要登录后才可以回帖 登录 | 注册哦

本版积分规则