1.用Modbus工具模擬PLC
2.建立一個實體類
點選檢視程式碼
internal class Data : INotifyPropertyChanged
{
ushort[] ushorts = new ushort[10];
public ushort D0 { get => ushorts[0]; set { ushorts[0] = value; OnPropertyChanged(nameof(D0)); } }
public ushort D1 { get => ushorts[1]; set { ushorts[1] = value; } }
public ushort D2 { get => ushorts[2]; set { ushorts[2] = value; } }
public ushort D3 { get => ushorts[3]; set { ushorts[3] = value; } }
public ushort D4 { get => ushorts[4]; set { ushorts[4] = value; } }
public ushort D5 { get => ushorts[5]; set { ushorts[5] = value; } }
public ushort D6 { get => ushorts[6]; set { ushorts[6] = value; } }
public ushort D7 { get => ushorts[7]; set { ushorts[7] = value; } }
public ushort D8 { get => ushorts[8]; set { ushorts[8] = value; } }
public ushort D9 { get => ushorts[9]; set { ushorts[9] = value; } }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
4.把資料繫結控制元件,利用定時器事件讀取和寫入PLC資料。
點選檢視程式碼
Data DB = new Data();
ModbusTcp ModbusTcp = new ModbusTcp();
private void Form1_Load(object sender, EventArgs e)
{
try
{
textBox1.DataBindings.Add("Text", DB, "D0");
textBox2.DataBindings.Add("Text", DB, "D1");
textBox3.DataBindings.Add("Text", DB, "D2");
textBox4.DataBindings.Add("Text", DB, "D3");
textBox5.DataBindings.Add("Text", DB, "D4");
textBox6.DataBindings.Add("Text", DB, "D5");
textBox7.DataBindings.Add("Text", DB, "D6");
textBox8.DataBindings.Add("Text", DB, "D7");
textBox9.DataBindings.Add("Text", DB, "D8");
textBox10.DataBindings.Add("Text", DB, "D9");
ModbusTcp.ModbusTcpConnect("127.0.0.1", 502);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void timer1_Tick(object sender, EventArgs e)
{
ushort[] ushorts = {DB.D0,DB.D1,DB.D2,DB.D3,DB.D4,DB.D5,DB.D6,DB.D7,DB.D8,DB.D9};
ModbusTcp.WriteMultipleRegisters(1, 0, ushorts);
ushorts = ModbusTcp.ReadHoldingRegisters(1, 0, 10);
}