一、编程环境

    VS2022软件,选择windows窗体应用(.NET FrameWork)

添加NuGet程序包;S7netplus

二、引用S7.net

三、建立PLC链接

S7-200smart和S7-1200的通讯协议一样的。

四、建立读数据

五、关于组合框选择驱动

六、关于自动读数据

当链接成功后,我们选择连续读取数据,就可实现连续读。

这里我们用到了radioButton控件。

先从工具箱中拉出两个radioButton控件,分别在radioButton.text属性设置“单次读”和“连续读”,然后配置radioButton控件的选中。

private void radioButton1_CheckedChanged(object sender, EventArgs e)
  {textBox1.Text = "0"; }

private void radioButton2_CheckedChanged(object sender, EventArgs e)

  {  textBox1.Text = "1";}

//在定时器中设置读取的时间间隔
private void timer1_Tick(object sender, EventArgs e)
{
    autoread = Convert.ToBoolean(int.Parse(textBox1.Text));
    txtPLCType.Text = comboBox1.Text;
    if (autoread)
    {
        timer1_autoread.Enabled = true;
    }
    else
    { timer1_autoread.Enabled = false; }
}

//连续读
private void timer1_autoread_Tick(object sender, EventArgs e)
{
    if (plc.IsConnected == false)
    {
        MessageBox.Show("未连接PLC!", "连接提示", MessageBoxButtons.OK);//检查PLC是否连接;      }
    else
    {
        try
        {
            string[] arr = (txtAddress2.Text.ToUpper()).Split('.');
            string valuetype = arr[1].Substring(0, 3);   
            if (valuetype == "DBX")
            {
                bool test1 = (bool)plc.Read(txtAddress2.Text.ToUpper());
                txtReadData.Text = txtAddress2.Text + ":" + test1.ToString();
            }
            else if (valuetype == "DBW")
            {
                short test3 = ((ushort)plc.Read(txtAddress2.Text.ToUpper())).ConvertToShort();

                txtReadData.Text = txtAddress2.Text + ":" + test3.ToString();
            }
            else if (valuetype == "DBD")

            {
  double test5 = ((uint)plc.Read(txtAddress2.Text.ToUpper())).ConvertToFloat();

                txtReadData.Text = test5.ToString("F3");
            }
            else
            {
                MessageBox.Show("请检查地址是否输入错误!", "输入提示", MessageBoxButtons.OK);
            }
        }
        catch (Exception Ex)
        {
            MessageBox.Show("请检查地址是否输入错误!" + Ex, "输入提示", MessageBoxButtons.OK);
        }
    }
}

七:测试效果:

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐