下面为简单的PLC数据读写
地址:如D100;位数:读取或写入的个数;写入数据:写入地址的数据;读数据:显示读出的数据
废话不多说,先上代码:
class cplcom
{
public System.IO.Ports.SerialPort serialPort1=new System.IO.Ports.SerialPort();//實例化串口號
public string enq = "05 ";
public string head = "F90000FF00";
public string order = "1401";//命令----批量写:1401;批量读:0401
public string childorder = "0000";//子命令
public string A_dress = "";//软元件代码
public string start = ""; //起始软元件
public string count = "";//软元件点数
public void ss()//先設置端口
{
serialPort1.PortName="COM1";
serialPort1.BaudRate =9600;// int.Parse(cobBaudrate.SelectedValue.ToString());
//serialPort1.Parity = int.Parse(cobCheckDigit.SelectedValue.ToString());
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.DataBits = 8;// int.Parse(cobDataBit.SelectedValue.ToString());
serialPort1.StopBits = System.IO.Ports.StopBits.One ;//
}
public void connect()
{
if (serialPort1.IsOpen == false)
{
serialPort1.Close();
serialPort1.ReceivedBytesThreshold = 1;
serialPort1.RtsEnable = true;
serialPort1.DtrEnable = true;
serialPort1.Open();
}
}
public void noconnect()
{
serialPort1.ReceivedBytesThreshold = 1;
serialPort1.RtsEnable = false;
serialPort1.DtrEnable = false;
serialPort1.Close();
}
public void writePlcData(string szDevice, int dwSize, short[] write)//写入數據(多个)
{
order = "1401";//批量写
szDevice = szDevice.ToUpper();//將寄存器改成大寫
string adress = szDevice.Substring(0, 1);
string AD1 = "";
switch (adress)
{
case "D": AD1 = "D"; break;
case "R": AD1 = "R"; break;
case "M": AD1 = "M"; break;
default: break;
}
A_dress = AD1 + "*";
start = (szDevice.Substring(1, szDevice.Length - 1)).ToString().PadLeft(6, '0');
count = Convert.ToString(dwSize, 16).PadLeft(4, '0');
string concent="";//寫入的內容
for (int i = 0; i < write.Length; i++)
{
concent += write[i].ToString("X4");//写入的值
}
//string sendMsg = "05 46 39 30 30 30 30 46 46 30 30 31 34 30 31 30 30 30 30 44 2A 30 30 30 " + ASC(szDevice) + ASC(Convert.ToString(dwSize, 16).PadLeft(4, '0')) + WriteNum;//.padleft(2,"0");將數據改成連接的字符串形式,後期需要在進行書寫
string sendMsg = enq + ASC(head + order + childorder + A_dress + start + count + concent);//.padleft(2,"0");將數據改成連接的字符串形式,後期需要在進行書寫
//項將字符串請求命令延時寄存器讀取位數連接起來
string ckSum = CheckSum(sendMsg);
sendMsg = sendMsg + " 0D 0A";//和校驗之後加上結束符
//sendMsg = sendMsg + " 0D 0A";//和校驗之後加上結束符
SendString(sendMsg);//发送数据
}
public string[] readPlcData(string szDevice, int dwSize)//讀取數據 (读取多个)
{
order = "0401";