在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → RS232通讯(入门级)示例源码

RS232通讯(入门级)示例源码

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.06M
  • 下载次数:21
  • 浏览次数:248
  • 发布时间:2020-03-20
  • 实例类别:C#语言基础
  • 发 布 人:1404051159
  • 文件格式:.zip
  • 所需积分:6
 相关标签: RS232 S2 23 通讯

实例介绍

【实例简介】RS232通讯

【实例截图】Sample program to connect SR series readers with RS-232C cable.

from clipboard

【核心代码】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Text.RegularExpressions;
/// <summary>
/// Sample program to connect SR series readers with RS-232C cable.
/// </summary>
namespace SrRs232cSample
{
    public partial class Form1 : Form
    {
        //private const Byte STX = 0x02;
        //private const Byte ETX = 0x03;
        //private const Byte CR = 0x0d;
        //private const int SERIAL_PORT_COUNT = 1;    // Number of COM ports used
        //private const int RECV_DATA_MAX = 10240;
        //private const bool binaryDataMode = false;  // Whether using binary data mode
        //private SerialPort[] serialPortInstance;    // Array to store instances of COM ports used
        /// <summary>
        /// Constructor
        /// </summary>
        public Form1()
        {
            InitializeComponent();
            //
            // Set RS-232C parameters.
            //
            this.serialPort1.BaudRate = 115200;         // 9600, 19200, 38400, 57600 or 115200
            this.serialPort1.DataBits = 8;              // 7 or 8
            this.serialPort1.Parity = Parity.None;    // Even or Odd
            this.serialPort1.StopBits = StopBits.One;   // One or Two
            this.serialPort1.PortName = "COM10";
            //this.serialPort2.BaudRate = 115200;         // 9600, 19200, 38400, 57600 or 115200
            //this.serialPort2.DataBits = 8;              // 7 or 8
            //this.serialPort2.Parity = Parity.Even;    // Even or Odd
            //this.serialPort2.StopBits = StopBits.One;   // One or Two
            //this.serialPort2.PortName = "COM2";
            //
            // Store COM ports instances in the array.
            //
            serialPortInstance = new SerialPort[SERIAL_PORT_COUNT] { this.serialPort1 };//, this.serialPort2 };
        }
        /// <summary>
        /// handler for "Connect" button is clicked
        /// </summary>
        private void connect_Click(object sender, EventArgs e)
        {
            Scanconnect();
        }
        /// <summary>
        /// handler for "Disonnect" button is clicked
        /// </summary>
        private void disconnect_Click(object sender, EventArgs e)
        {
            Scandisconnect();
        }
        /// <summary>
        /// handler for "Timing ON" button is clicked
        /// </summary>
        private void lon_Click(object sender, EventArgs e)
        {
            LON();
        }
        /// <summary>
        /// handler for "Timing OFF" button is clicked
        /// </summary>
        private void loff_Click(object sender, EventArgs e)
        {
            LOFF();
        }
        /// <summary>
        ///  handler for "Receive Data" button is clicked
        /// </summary>
        private void receive_Click(object sender, EventArgs e)
        {
            //Input = Regex.Split(ScanReceive(), "\r", RegexOptions.IgnoreCase);
            //MessageBox.Show(serialPortInstance[0].PortName "\r\n" Input[0]);

            //四合一测试------------------------------------------------------------------------
            LOFF();
            string[] Input = Regex.Split(ScanReceive(), "\r", RegexOptions.IgnoreCase);
            //清除缓存
            while (true )
            {
                 Input = Regex.Split(ScanReceive(), "\r", RegexOptions.IgnoreCase);
                if (Input[0]=="")
                {
                    break;
                }
            }
            textSN.Text = "";
            LON();
            Input = Regex.Split(ScanReceive(), "\r", RegexOptions.IgnoreCase);
            //MessageBox.Show(serialPortInstance[0].PortName "\r\n" Input[0]);
            if (Input[0]== "OK,LON")
            {
                Input = Regex.Split(ScanReceive(), "\r", RegexOptions.IgnoreCase);
                if (Input[0] != "")
                {
                    //1次有码--禁止打码,NG抛料
                    //output
                    //2次有码--比对二维码
                    textSN.Text = Input[0];
                    //out
                }
                else
                {
                    //1次无码--启动打码
                    LOFF();


                    //2次有码--扫码失败


                }
            }
        }
        /// <summary>
        /// check data size
        /// </summary>
        private bool checkDataSize(Byte[] recvBytes, int recvSize)
        {
            const int dataSizeLen = 4;
            if (binaryDataMode == false)
            {
                return true;
            }
            if (recvSize < dataSizeLen)
            {
                return false;
            }
            int dataSize = 0;
            int mul = 1;
            for (int i = 0; i < dataSizeLen; i )
            {
                dataSize = (recvBytes[dataSizeLen - 1 - i] - '0') * mul;
                mul *= 10;
            }
            return (dataSize 1 == recvSize);
        }

        #region 扫码枪控制
        private const Byte STX = 0x02;
        private const Byte ETX = 0x03;
        private const Byte CR = 0x0d;
        private const int SERIAL_PORT_COUNT = 1;    // Number of COM ports used
        private const int RECV_DATA_MAX = 10240;
        private const bool binaryDataMode = false;  // Whether using binary data mode
        private SerialPort[] serialPortInstance;    // Array to store instances of COM ports used
        //private System.IO.Ports.SerialPort serialPort1;
        private void ScanInitialize()
        {
            //
            // Set RS-232C parameters.
            //
            this.serialPort1.BaudRate = 115200;         // 9600, 19200, 38400, 57600 or 115200
            this.serialPort1.DataBits = 8;              // 7 or 8
            this.serialPort1.Parity = Parity.None;    // Even or Odd
            this.serialPort1.StopBits = StopBits.One;   // One or Two
            this.serialPort1.PortName = "COM10";
            //
            // Store COM ports instances in the array.
            //
            serialPortInstance = new SerialPort[SERIAL_PORT_COUNT] { this.serialPort1 };//, this.serialPort2 };
        }

        /// <summary>
        /// handler for "Connect" button is clicked
        /// </summary>
        private void Scanconnect()
        {
            for (int i = 0; i < serialPortInstance.Length; i )
            {
                try
                {
                    //
                    // Close the COM port if opened.
                    //
                    if (serialPortInstance[i].IsOpen)
                    {
                        this.serialPortInstance[i].Close();
                    }
                    //
                    // Open the COM port.
                    //
                    this.serialPortInstance[i].Open();
                    //PublicValue.ComScan = true;
                    //
                    // Set 100 milliseconds to receive timeout.
                    //
                    this.serialPortInstance[i].ReadTimeout = 100;
                }
                catch //(Exception ex)
                {
                    //PublicValue.ComScan = false;
                    // MessageBox.Show(serialPortInstance[i].PortName "\r\n" ex.Message);  // non-existent or disappeared
                }
            }
        }
        /// <summary>
        /// handler for "Disonnect" button is clicked
        /// </summary>
        private void Scandisconnect()
        {
            for (int i = 0; i < serialPortInstance.Length; i )
            {
                try
                {
                    this.serialPortInstance[i].Close();
                    //PublicValue.ComScan = false;
                }
                catch (IOException ex)
                {
                    MessageBox.Show(serialPortInstance[i].PortName "\r\n" ex.Message);    // disappeared
                }
            }
        }
        /// <summary>
        /// handler for "Timing ON" button is clicked
        /// </summary>
        private void LON()
        {
            //
            // Send "LON" command.
            // Set STX to command header and ETX to the terminator to distinguish between command respons
            // and read data when receives data from readers.
            //
            string lon = "LON\r";     // "%01#RDD0011000010154\r\n"; //"\x02LON\x03";   // <STX>LON<ETX>
            Byte[] sendBytes = ASCIIEncoding.ASCII.GetBytes(lon);
            for (int i = 0; i < serialPortInstance.Length; i )
            {
                if (this.serialPortInstance[i].IsOpen)
                {
                    try
                    {
                        this.serialPortInstance[i].Write(sendBytes, 0, sendBytes.Length);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show(serialPortInstance[i].PortName "\r\n" ex.Message);    // disappeared
                    }
                }
                else
                {
                    MessageBox.Show(serialPortInstance[i].PortName " is disconnected.");
                }
            }
        }
        /// <summary>
        /// handler for "Timing OFF" button is clicked
        /// </summary>
        private void LOFF()
        {
            //
            // Send "LOFF" command.
            // Set STX to command header and ETX to the terminator to distinguish between command respons
            // and read data when receives data from readers.
            //
            string loff = "\x02LOFF\x03";   // <STX>LOFF<ETX>
            Byte[] sendBytes = ASCIIEncoding.ASCII.GetBytes(loff);
            for (int i = 0; i < serialPortInstance.Length; i )
            {
                if (this.serialPortInstance[i].IsOpen)
                {
                    try
                    {
                        this.serialPortInstance[i].Write(sendBytes, 0, sendBytes.Length);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show(serialPortInstance[i].PortName "\r\n" ex.Message);    // disappeared
                    }
                }
                else
                {
                    MessageBox.Show(serialPortInstance[i].PortName " is disconnected.");
                }
            }
        }
        /// <summary>
        /// 清楚发送缓存
        /// </summary>
        private void BCLR()
        {
            //
            // Send "LON" command.
            // Set STX to command header and ETX to the terminator to distinguish between command respons
            // and read data when receives data from readers.
            //
            string lon = "RESET\r";     // "%01#RDD0011000010154\r\n"; //"\x02LON\x03";   // <STX>LON<ETX>
            Byte[] sendBytes = ASCIIEncoding.ASCII.GetBytes(lon);
            for (int i = 0; i < serialPortInstance.Length; i )
            {
                if (this.serialPortInstance[i].IsOpen)
                {
                    try
                    {
                        this.serialPortInstance[i].Write(sendBytes, 0, sendBytes.Length);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show(serialPortInstance[i].PortName "\r\n" ex.Message);    // disappeared
                    }
                }
                else
                {
                    MessageBox.Show(serialPortInstance[i].PortName " is disconnected.");
                }
            }
        }
        /// <summary>
        ///  handler for "Receive Data" button is clicked
        /// </summary>
        private string ScanReceive()
        {
            string QQ = "";
            Byte[] recvBytes = new Byte[RECV_DATA_MAX];
            int recvSize;
            for (int i = 0; i < this.serialPortInstance.Length; i )
            {
                if (this.serialPortInstance[i].IsOpen == false)
                {
                    //MessageBox.Show(serialPortInstance[i].PortName " is disconnected.");
                    QQ = "";
                    continue;
                }
                for (;;)
                {
                    try
                    {
                        recvSize = ReadDataSub(recvBytes, this.serialPortInstance[i]);
                    }
                    catch (IOException ex)
                    {
                        //MessageBox.Show(serialPortInstance[i].PortName "\r\n" ex.Message);    // disappeared
                        QQ = "";
                        break;
                    }
                    if (recvSize == 0)
                    {
                        //MessageBox.Show(serialPortInstance[i].PortName " has no data.");
                        QQ = "";
                        break;
                    }
                    if (recvBytes[0] == STX)
                    {
                        //
                        // Skip if command response.
                        //
                        continue;
                    }
                    else
                    {
                        //
                        // Show the receive data after converting the receive data to Shift-JIS.
                        // Terminating null to handle as string.
                        //
                        recvBytes[recvSize] = 0;
                        QQ = Encoding.GetEncoding("Shift_JIS").GetString(recvBytes);
                        //MessageBox.Show(serialPortInstance[i].PortName "\r\n" QQ);
                        break;
                    }
                }
            }
            return QQ;
        }
        /// <summary>
        /// Sub function to receive data
        /// </summary>
        private int ReadDataSub(Byte[] recvBytes, SerialPort serialPortInstance)
        {
            int recvSize = 0;
            bool isCommandRes = false;
            Byte d;
            //
            // Distinguish between command response and read data.
            //
            try
            {
                d = (Byte)serialPortInstance.ReadByte();
                recvBytes[recvSize ] = d;
                if (d == STX)
                {
                    isCommandRes = true;    // Distinguish between command response and read data.
                }
            }
            catch (TimeoutException)
            {
                return 0;   //  No data received.
            }
            //
            // Receive data until the terminator character.
            //
            for (;;)
            {
                try
                {
                    d = (Byte)serialPortInstance.ReadByte();
                    recvBytes[recvSize ] = d;
                    if (isCommandRes && (d == ETX))
                    {
                        break;  // Command response is received completely.
                    }
                    else if (d == CR)
                    {
                        if (CheckDataSize(recvBytes, recvSize))
                        {
                            break;  // Read data is received completely.
                        }
                    }
                }
                catch (TimeoutException ex)
                {
                    //
                    // No terminator is received.
                    //
                    MessageBox.Show(ex.Message);
                    return 0;
                }
            }
            return recvSize;
        }
        /// <summary>
        /// check data size
        /// </summary>
        private bool CheckDataSize(Byte[] recvBytes, int recvSize)
        {
            const int dataSizeLen = 4;
            if (binaryDataMode == false)
            {
                return true;
            }
            if (recvSize < dataSizeLen)
            {
                return false;
            }
            int dataSize = 0;
            int mul = 1;
            for (int i = 0; i < dataSizeLen; i )
            {
                dataSize = (recvBytes[dataSizeLen - 1 - i] - '0') * mul;
                mul *= 10;
            }
            return (dataSize 1 == recvSize);
        }

        #endregion

    }
}

标签: RS232 S2 23 通讯

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警