PLC与计算机串口通信问题?
请教高手
怎样实现PLC与计算机的串口通信哦?? 我知道在C#中可以用SerialPort类来实现,可是我不知道怎样去用这个类
请教各路高手指点迷津。能给出具体例子或程序的最好不过了 谢谢啦!!
------解决方案--------------------假设为文本传送
初始化串口
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.Parity = Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
if (serialPort1.IsOpen) { serialPort1.Close(); }
serialPort1.Open();
发送
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Write("ABCDEFG\r\n");
}
接收
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.BytesToRead == 0)
{
return;
}
char[] buffer = new char[serialPort1.BytesToRead];
serialPort1.Read(buffer, 0, serialPort1.BytesToRead);
string b = new string(buffer);
}
------解决方案--------------------
1.添加using Sysytem.IO.Ports或者直接往界面里面放入一个serialport控件
2.public SerialPort serialPort1=new SerialPort ();实例化对象(如果是放控件的方式就不用了)
private string b;//用来显示接收到的数据
3.serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);//定义串口接收事件*/
4.private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (serialPort1.BytesToRead == 0)
{
return;
}
char[] buffer = new char[serialPort1.BytesToRead];
serialPort1.Read(buffer, 0, serialPort1.BytesToRead);
b = new string(buffer); //借用楼上
this.Invoke(SerialDelegate);//委托机制显示接收到的数据
}
5.打开串口try
{
if (serialPort1.IsOpen == false)
{
serialPort1.Open();
}
else
{
serialPort1.Close();
serialPort1.Open();
}
}
catch (Exception e)
{
//MessageBox.Show("错误:" + e.Message);
//if (e.Message == "对端口”COM1“的访问被拒绝。")
MessageBox .Show ("当前设置的串口不存在或者已经被占用,请重新设置串口并尝试连接");
}
if (serialPort1.IsOpen == true)
{
serialPort1.DiscardOutBuffer();
}
6.由于线程安全问题,如果要将接收到的数据显示出来需要使用委托的机制,故:
private delegate void MydelegateShow();//声明一个委托
private MydelegateShow SerialDelegate;//实例化一个委托对象
同时在窗口构造函数中添加SerialDelegate = new MydelegateShow(UpdateBox);
7.编写UpdateBox代码:
private void UpdateBox()
{
textBox1.Text+=b;
}
8.发送是主动的,可以按照需求发送就可以