SCADA with C# (Winform) connect to PLC S7 sử dụng thư viên S7.Net
1. Thiết bị
- 1 Máy tính: được lập trình Winform C# giao tiếp S7-1200 qua Visual Studio 2019 sử dụng thư viện S7.Net
2. Chương trình
2.1 PLC
a. Cấu hình PLC mô phỏng
b. Chương trình PLC
2.2 Chương trình C#
a. Giao diện
b. Chương trình C# giao tiếp với PLC S7-1200
Khởi tạo kết nối với PLC
– thông qua sự kiện click button connect
private void bt_connect_Click(object sender, EventArgs e)
{
try
{
//Kiem
tra Textbox IP Adrress != null chua? = null => Exception
if string.IsNullOrEmpty(IpAddress.Text)) throw new Exception("This invalid IP Address,
please input valid IP Address");
//Tien
hanh khoi tao CPU S71200
S71200 = new Plc(CpuType.S71200, IpAddress.Text,
0, 1);
//Kiem
tra cap da ket noi voi PLC
if(!S71200.IsAvailable)
throw new Exception("No PLC was established,
please check PLC connection");
//Tien
hanh mo ket noi
S71200.Open();
//Kiem
Tra da ket noi thanh cong voi PLC chua?
if (S71200.IsConnected)
{
Isconnected = true;
throw new Exception("Successfully Connected");
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Notification",
MessageBoxButtons.OK);
}
}
Ngắt kết nối với PLC - thông qua sự kiện click button disconnect
private void bt_Read_Click(object sender, EventArgs e)
{
try
{
if (Isconnected)
{
string variable = txt_address.Text;
object value = S71200.Read(variable);
txt_getv.Text =
value.ToString();
}
}
catch
{
;
}
}
Ghi giá trị thông qua nút
nhấn Wirte (Variable là địa chỉ ta muốn ghi xuống)
private void bt_Wirte_Click(object sender, EventArgs e)
{
try
{
if (Isconnected)
{
string variable = txt_address.Text;
string value = txt_setv.Text;
ushort value_set = ushort.Parse(value);
S71200.Write(variable,
value_set);
}
}
catch
{
;
}
}
Nhận xét
Đăng nhận xét