『7x24小时有问必答』
此代码主要供系列文章:
《入门项目【自动打螺丝机】C#、PLC、触摸屏实战》学习使用。

using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CcrewMachine
{
    /// 
    /// 基恩士扫码枪串口通讯类
    /// 
    internal class KeyenceScan
    {
        // 串口状态标识
        public bool IsOpened;                  // 记录串口是否打开
        public SerialPort SerialPort;          // 串口对象
        public int SerialPortSendCount;        // 串口发送次数
        public string BufferString;            // 接收到的字符串
        public string OpenScanCommand = "LON\r\n";   // 开启扫描命令
        public string CloseScanCommand = "LOFF\r\n"// 关闭扫描命令

        /// 
        /// 构造函数
        /// 
        /// 串口数据接收事件处理器
        public KeyenceScan(SerialDataReceivedEventHandler dataReceivedHandler)
        {
            SerialPort = new SerialPort();
            SerialPort.DataReceived += dataReceivedHandler;
            IsOpened = false;
            SerialPortSendCount = 0;
            BufferString = "";
        }

        /// 
        /// 初始化串口
        /// 
        /// 串口号
        /// 波特率
        /// 校验位
        /// 数据位
        /// 停止位
        /// 初始化成功返回true,失败返回false
        public bool Initialize(string comPort, int baudRate, Parity parity, int dataBits, StopBits stopBit)
        {
            try
            {
                IsOpened = false;
                SerialPortSendCount = 0;
                SerialPort.PortName = comPort;
                SerialPort.BaudRate = baudRate;
                SerialPort.Parity = parity;
                SerialPort.DataBits = dataBits;
                SerialPort.StopBits = stopBit;
                SerialPort.ReceivedBytesThreshold = 1;
                SerialPort.ReadTimeout = 1000;
                SerialPort.Open();
                BufferString = "";
                IsOpened = true;
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        /// 
        /// 检查接收数据是否有效
        /// 
        /// 有效返回true,无效返回false
        public bool CheckData()
        {
            bool result = false;
            do
            {
                if (BufferString[0] == 0x15)
                {
                    // 写入错误
                    break;
                }

                result = true;
            } while (false);
            return result;
        }

        /// 
        /// 发送开启扫描命令
        /// 
        /// 发送成功返回true,失败返回false
        public bool OpenScan()
        {
            try
            {
                SerialPort.Write(OpenScanCommand);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        /// 
        /// 发送关闭扫描命令
        /// 
        /// 发送成功返回true,失败返回false
        public bool CloseScan()
        {
            try
            {
                SerialPort.Write(CloseScanCommand);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        /// 
        /// 读取串口接收的所有数据
        /// 
        /// 0表示接收完成,-1表示未完成或失败
        public int ReadExisting()
        {
            int returnValue = -1;
            do
            {
                if (SerialPort.IsOpen)
                {
                    BufferString += SerialPort.ReadExisting();
                    // 判断回车结束
                    if (BufferString.Length > 1)
                    {
                        // 转换字节判断末尾是否为回车
                        byte[] byteBuffer = System.Text.Encoding.Default.GetBytes(BufferString);
                        if (byteBuffer[byteBuffer.Length - 1] == 0x0D)
                        {
                            // 接收结束,移除末尾回车
                            BufferString = BufferString.Remove(BufferString.Length - 1);
                            returnValue = 0;
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    BufferString = "";
                    break;
                }
            } while (false);
            return returnValue;
        }

        /// 
        /// 关闭串口
        /// 
        public void Close()
        {
            if (SerialPort.IsOpen)
            {
                try
                {
                    IsOpened = false;
                    SerialPort.Close();
                }
                catch (Exception)
                {
                    // 忽略关闭异常
                }
            }
        }
    }
}


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

上一主题上一主题         下一主题下一主题
QQ手机版小黑屋粤ICP备17165530号

关于我们·投诉举报· 用户帮助· 联系我们 · 本站服务 · 版权声明· 隐私政策 · 投搞指南

法律保护:PLC技术网,plcjs.com,plcjs.net等字样
Copyright 2010-2030. All rights reserved. 


微信公众号二维码 抖音二维码 百家号二维码 今日头条二维码哔哩哔哩二维码