上一篇聊到了C#与三菱PLC设备任何通信,这篇详细介绍结合本人项目中的使用。包括32位数据寄存器的读取写入。
1.数据寄存器(如D100),数据寄存器直接使用32位即可
private void btn_ReadDeviceBlock_Click(object sender, EventArgs e)
{
int iReturnCode;
short[] arrDeviceValue = new short[2]; // 表示 2个 寄存器软元件
byte[] byarrBufferByte = new byte[4]; // 表示 4个 字节的数据
byte[] byarr;
try
{
String objText = ((Button)sender).Text;
String[] sText = objText.Split('-');
String szDevice = sText[0];
Control col = this.groupBox1.Controls.Find(szDevice + "text", true)[0];
TextBox textBox = (TextBox)col;
iReturnCode = axActUtlType1.ReadDeviceBlock2(szDevice, 2, out arrDeviceValue[0]);
for (int i = 0; i < 2; i++)
{
byarr = BitConverter.GetBytes(arrDeviceValue[i]);
byarrBufferByte[i * 2] = byarr[0];
byarrBufferByte[i * 2 + 1] = byarr[1];
}
textBox.Text = BitConverter.ToInt32(byarrBufferByte, 0).ToString();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, Name,
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//The return code of the method is displayed by the hexadecimal.
txt_ReturnCode.Text = String.Format("0x{0:x8}", iReturnCode);
}
private void btn_WriteDeviceBlock_Click(object sender, EventArgs e)
{
int iReturnCode;
int iNumberOfData = 0;
byte[] byarrBufferByte;
short[] arrDeviceValue;
try
{
String objText = ((Button)sender).Text;
String[] sText = objText.Split('-');
String szDevice = sText[0];
Control col = this.groupBox1.Controls.Find(szDevice + "text", true)[0];
TextBox textBox = (TextBox)col;
if (!GetIntValue(textBox, out iNumberOfData))
{
//If failed, this process is end.
return;
}
arrDeviceValue = new short[2];
byarrBufferByte = BitConverter.GetBytes(iNumberOfData);
arrDeviceValue[0] = BitConverter.ToInt16(byarrBufferByte, 0);
arrDeviceValue[1] = BitConverter.ToInt16(byarrBufferByte, 2);
iReturnCode = axActUtlType1.WriteDeviceBlock2(szDevice, 2, ref arrDeviceValue[0]);
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, Name,
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//The return code of the method is displayed by the hexadecimal.
txt_ReturnCode.Text = String.Format("0x{0:x8}", iReturnCode);
}
2.内部继电器如(M10),内部继电器相当于一个开关0,1
#region "软元件1点的开启关闭设置" 如:M80
private void btn_SetDeviceType_Click(object sender, EventArgs e)
{
int iReturnCode; //Return code
try
{
String objText = ((Button)sender).Text;
String[] sText = objText.Split('-');
String szDevice = sText[0];
String clickType = sText[1];
if (clickType.Equals("ON"))
{
iReturnCode = axActUtlType1.SetDevice(szDevice, 1);
}
else
{
iReturnCode = axActUtlType1.SetDevice(szDevice, 0);
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, Name,
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//The return code of the method is displayed by the hexadecimal.
txt_ReturnCode.Text = String.Format("0x{0:x8}", iReturnCode);
}
#endregion
3.监听继电器如(X0),监听要注意如果批量监听2个,就是2点方法的软元件点数要传2。
这个官方有Demo就不贴代码了。