c# - C#串口通信示例
问题描述
如果可以做(并且实施得很好)我的下一个问题,我正在徘徊:
我想通过串行通信与 PLC 交谈。每次我向 PLC 发送数据时,它都会向我发送数据,我们不知道他需要多长时间才能将我发送回来(一些毫秒,但不知道多少)。
我想用不同的方法创建一个用于串行通信(PC和PLC之间)的类:
- Open()--> 打开与 PLC 的串行通讯
- Talk2PLC()--> 向 PLC 发送数据并等待接收回数据并读取
- Close()-->关闭与PLC的串行通讯
它的工作方式是:当项目启动时,我们打开与 PLC 的串行通信。那么在程序执行过程中我们将只使用Talk2PLC()与PLC进行通信,我们会多次调用该方法。当接收到来自 PLC 的数据时,它将在 ProcessData() 中进行处理。完成所有工作后,我们将关闭与 PLC 的通信,我们调用 Close()。
!!It's import methods are separated¡¡
问题:
即使“打开”和“关闭”分开,它会像我一样正常工作吗?
在 Talk2PLC() 中,即使答案不是即时的,我是否能够读取从 PLC 发回的数据?如果我需要等待,我是否需要某种延迟?我的事件处理程序 com_Datareceive() 能够读取它吗?我认为“ReadTimeout”和“WriteTimeout”应该可以解决问题。
- 在我第一次调用 Open() 然后调用 Talk2PLC() 之后,下次我调用 Talk2PLC() 是否可以从 PLC 发送和接收数据?
一个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
namespace Project
{
class Serial
{
// Serial port settings.
SerialPort com = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
List<byte> PlcBuffer = new List<byte>();
// Open serial communication with PLC.
public void Open()
{
com.Open();
}
/* Query PLC and get answer.
* @cmd: command to be send.
*/
public void Talk2PLC(byte[] cmd)
{
PlcBuffer.Clear();//Clear previous data before storing new one.
// Set the read/write timeouts
com.ReadTimeout = 1000;
com.WriteTimeout = 1000;
//Write. Send data to PLC
com.Write(cmd, 0, cmd.Length);
//Read. Wait for an answer from PLC.
com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);
}
// Gets all data send by the PLC.
public void com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Buffer and process binary data
while (com.BytesToRead > 0)
PlcBuffer.Add((byte)com.ReadByte());
ProcessData(PlcBuffer); //Send data to be processed
}//End com_DataReceived()
// This will process data from PLC
public void ProcessData(List<byte> buffer)
{
//Process data
}
// Close serial communication with PLC.
public void Close()
{
com.Close();
}
}
}
感谢所有阅读并试图提供帮助的人:)
解决方案
推荐阅读
- anaconda - 我无法在 anaconda 环境中将 'C:\tools\cuda\bin' 添加到我的 %PATH%
- php - 将记录插入到父数组中
- typescript - 向 TypeScript 中的函数添加动态 getter/setter 属性
- asp.net - ASP.Net web api 令牌认证是否适合保护金融 API 以阻止滥用?
- macos - Homebrew 无法安装任何东西:由 cURL 的一些 SSL 相关问题引起
- android - 为什么观察者再次调用 API 而没有在 Android 中进行任何更改?
- julia - 使用 Flux 的神经代理问题
- google-apps-script - Google Apps 脚本的 TOTAL DAILY 限制是多少?
- c# - DisplayActionSheet() 不会将销毁按钮放在 Android 的顶部
- python - 使用 StringIO 从 pyscopg2 写入 PostgresSQL - 复制会随着时间的推移而变慢