首页 > 解决方案 > C#串口通信示例

问题描述

如果可以做(并且实施得很好)我的下一个问题,我正在徘徊:

我想通过串行通信与 PLC 交谈。每次我向 PLC 发送数据时,它都会向我发送数据,我们不知道他需要多长时间才能将我发送回来(一些毫秒,但不知道多少)。

我想用不同的方法创建一个用于串行通信(PC和PLC之间)的类:

  1. Open()--> 打开与 PLC 的串行通讯
  2. Talk2PLC()--> 向 PLC 发送数据并等待接收回数据并读取
  3. Close()-->关闭与PLC的串行通讯

它的工作方式是:当项目启动时,我们打开与 PLC 的串行通信。那么在程序执行过程中我们将只使用Talk2PLC()与PLC进行通信,我们会多次调用该方法。当接收到来自 PLC 的数据时,它将在 ProcessData() 中进行处理。完成所有工作后,我们将关闭与 PLC 的通信,我们调用 Close()。

   !!It's import methods are separated¡¡

问题:

一个

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();
        }

    }
}

感谢所有阅读并试图提供帮助的人:)

标签: c#serial-port

解决方案


推荐阅读