串口是计算机上一种非常通用的设备通信协议。
大多数计算机包含两个基于RS-232的串口。 PLC采用的是三菱公司的FX1N©系列产品,支持的串口通信协议是422,不支持232协议, 所以要调用第三方提供的动态库实现PC与PLC之间串口通信。
- 首先到三菱官网
下载软件,测试PC与PLC的通信。
注:点击图中的查看并下载,软件安装过程中需要序列号,可以在官网通过注册账号获得。 - 安装完成后,打开PLC Monitor测试软件
按照图中标识的1,2,3操作顺序,先点击btton.
在下面对话框选择COM口,然后点击Next。
在对话框中填入红色标记的部分。
点击Next,在之后的选项都保持默认值,直到点击Finish完成。
点击Start monitor 按钮开始监控。如果想监控D100 地址的数据,可直接Device中输入这个地址
- 下面分析如何使用c#实现读写PLC数据
首先可在安装目录下找到Manual文件夹,查看调用打开串口及读写串口的参数,如图可以看到ActCpu Type参数值。并可以找到samples 代码,其中包含读写PLC常用方法。
- 主要代码示例
int iReturnCode; //Return code
//Displayed output data is cleared.
ClearDisplay();
//
//Processing of Open method
//
try
{
//获取端口号
var item = this.comboBoxPort.GetItemText(this.comboBoxPort.SelectedItem);
int COMPort = 0;
if (!GetIntValue(item, out COMPort))
{
return;
}
else
{
// Specify the module type connected to the physical port
lpcom_ReferencesProgType.ActUnitType = 0x0f;
//设置为FX1N(C)
lpcom_ReferencesProgType.ActCpuType = 0x207;
//set PROTOCOL_SERIAL
lpcom_ReferencesProgType.ActProtocolType = 0x04;
// Specify the baud rate for serial communication.
lpcom_ReferencesProgType.ActBaudRate = 9600;
//设置端口号 Specify the connection port number of personal computer.
lpcom_ReferencesProgType.ActPortNumber = COMPort;
// Specify the number of bits of the byte data sent and received for serial communication
// 设置数据为8bit
lpcom_ReferencesProgType.ActDataBits = 8;
// Specify the parity system used for serial communication
//无校验位
lpcom_ReferencesProgType.ActParity = 0;
//停止位 1 个bit zhx
lpcom_ReferencesProgType.ActStopBits = 0;
//设置超时时间
lpcom_ReferencesProgType.ActTimeOut = 100;
//The Open method is executed.
//先关闭再打开
lpcom_ReferencesProgType.Close();
iReturnCode = lpcom_ReferencesProgType.Open();
//When the Open method is succeeded, disable the open button
switch (iReturnCode)
{
case 0:
this.isOpen = true;
this.isStop = false;
this.label1.Visible = false;
this.label1.Refresh();
this.pictureBox1.BackColor = Color.LawnGreen;
this.timer1.Enabled = true;
this.timer1.Start();
break;
case 0x01802007:
case 0x0180840B:
this.isOpen = false;
this.isStop = true;
this.label1.Visible = true;
this.label1.Refresh();
this.txt_Data.Text = "";
this.txt_Data.Text = "串口打开失败";
break;
case 0x01808009:
this.isOpen = false;
this.label1.Visible = false;
this.label1.Refresh();
this.txt_Data.Text = "";
this.txt_Data.Text = "此串口不存在";
break;
default:
break;
}
}
//The return code of the method is displayed by the hexadecimal.
txt_ReturnCode.Text = String.Format("0x{0:x8} [HEX]", iReturnCode);
}
//Exception processing
catch (Exception exception)
{
MessageBox.Show(exception.Message,
Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
完整代码示例下载PLCdemo
注: 上面代码示例:由于项目的需求,只需要读取PLC某个地址的数据,只用到Read的方法
下面这个示例代码是经过对PLC读写方法封装后的库,包含:打开/关闭PLC,读PLC,写PLC,可以用于测试PLC约定的通信协议。
下载地址: 点击下载
重要
上面两个示例代码都是在已安装了MXComponent包后,方可使用,否则会提示引用组件有问题。