Làm thế nào để kết nối C# với PLC S7-1200?
Bài viết này hướng dẫn các bạn kết nối C# với PLC S7-1200 sử dụng thư viện S7.Net ở chế độ "Read and Write Struct".
Các bạn có thể tham khảo thêm chế độ:
- Read from PLC using S7.net
- Write to PLC using S7.net
- Write Bit to PLC using S7.net
- Read and Write Bytes to PLC using S7.net
- Read and Write Class to PLC using S7.net
Giao diện:
Source Code:
////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using S7.Net;namespace READ_AND_WRITE_STRUCT{public partial class Form1 : Form{Timer timer = new Timer();Plc plc_s7_1200;CpuType CPU_Type = CpuType.S71200;string Ip = "192.168.1.197";short Rack = 0;short Slot = 1;int Time_Update = 100;public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){plc_s7_1200 = new Plc(CPU_Type, Ip, Rack, Slot);plc_s7_1200.Open();timer.Interval = Time_Update;timer.Start();timer.Tick += Timer_Tick;if (plc_s7_1200.IsConnected){}}private void Timer_Tick(object sender, EventArgs e){if (plc_s7_1200.IsConnected)progressBar1.Value = 100;elseprogressBar1.Value = 0;if (plc_s7_1200.IsConnected){DB1 db1 = (DB1)plc_s7_1200.ReadStruct(typeof(DB1), 1);TB_Read_a.Text = db1.a.ToString();TB_Read_b.Text = db1.b.ToString();TB_Read_c.Text = db1.c.ToString();TB_Read_d.Text = Convert.ToSingle(db1.d).ToString() ;}}public struct DB1{public bool a;public short b;public int c;public double d;}private void Btn_a_Click(object sender, EventArgs e){DB1 db1 = new DB1();db1.a = Convert.ToBoolean(TB_Write_a.Text);db1.b = Convert.ToInt16(TB_Write_b.Text);db1.c = Convert.ToInt32(TB_Write_c.Text);db1.d = Convert.ToSingle(TB_Write_d.Text);if (plc_s7_1200.IsConnected){plc_s7_1200.WriteStruct(db1, 1);}}}}////////////////////////////////////////////////////////////////////////////////////////////////////////
Link tải Source Code: Download
No comments:
Post a Comment