当前位置:编程学习 > C#/ASP.NET >>

SerialPort操作串口用ReadByte()读缓存数据时“操作已超时”

下面是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;

namespace SerialPortTest
{
    public class DriverTest
    {
        SerialPort sp = new SerialPort();

        public string strStatus;

        //打开串口 得到数据 关闭串口

        #region
        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="Portname">串口名称</param>
        /// <param name="baudRate">串口波特率</param>
        /// <returns>打开是否成功</returns>
        public bool Open(string Portname, int baudRate)
        {
            if (!sp.IsOpen)
            {
                //名称 com1
                sp.PortName = Portname;
                //波特率 9600或115200
                sp.BaudRate = baudRate;
                //数据位 8
                sp.DataBits = 8;
                //奇偶校验 none
                sp.Parity = Parity.None;
                //停止位 1
                sp.StopBits = StopBits.One;

                sp.ReadTimeout = 500;
                sp.WriteTimeout = 500;

                try
                {
                    //打开串口
                    sp.Open();

                }
                catch (Exception ex)
                {

                    strStatus = "Open error: " + ex.Message;

                    return false;
                }

                strStatus = "Open successfully";

                return true;

            }

            else
            {

                strStatus = "Open error:  Had Opened.";

                return false;
            }

        }
        /// <summary>
        /// 关闭串口
        /// </summary>
        /// <returns>关闭是否成功</returns>
        public bool Close()
        {
            if (sp.IsOpen)
            {
                //关闭串口
                try
                {
                    sp.Close();
                }
                catch (Exception ex)
                {

                    strStatus = "Close Error: " + ex.Message;

                    return false;
                }

                strStatus = "Close Sucessfully.";

                return true;
            }

            else
            {

                strStatus = "Error: port not open.";

                return false;
            }
        }
        #endregion

        //建立命令
        /// <summary>
        /// 建立命令
        /// </summary>
        /// <param name="address">设备地址</param>
        /// <param name="command">要建立的命令</param>
        private void BuildCommadN1012(byte address, ref byte[] command)
        {
            //校验位
            byte[] CRC = new byte[2];
            //设备地址
            command[0] = address;
            //操作类型 读
            command[1] = 0x03;
            //DI寄存器地址 0x02 0x00
            command[2] = 0x02;
            command[3] = 0x00;
            //DI数量 0x00 0x10
            command[4] = 0x00;
            command[5] = 0x10;

            GetCRC(command, ref CRC);
            command[command.Length - 2] = CRC[0];
            command[command.Length - 1] = CRC[1];

        }

        //建立CRC校验
        /// <summary>
        /// 建立CRC校验
        /// </summary>
        /// <param name="command">命令</param>
        /// <param name="CRC">校验值</param>
        private void GetCRC(byte[] command, ref byte[] CRC)
        {
            //初始化
            ushort CRCFULL = 0xFFFF;
            byte CRCH = 0xFF;
            byte CRCL = 0xFF;
            char CRCLSB;

            for (int i = 0; i < command.Length - 2; i++)
            {
                CRCFULL = (ushort)(CRCFULL ^ command[i]);

                for (int j = 0; j < 8; j++)
                {
                    CRCLSB = (char)(CRCFULL & 0x0001);
                    CRCFULL = (ushort)((CRCFULL >> 1) & 0x7FFF);

                    if (CRCLSB == 1)
                    {
                        CRCFULL = (ushort)(CRCFULL ^ 0xA001);
                    }
                }
            }

            CRC[1] = CRCH = (byte)((CRCFULL >> 8) & 0xFF);
            CRC[0] = CRCL = (byte)(CRCFULL & 0xFF);
        }
        //得到返回数据
        /// <summary>
        /// 获取发回数据 
        /// </summary>
        /// <param name="response">返回数据</param>
        private void GetResponse(ref byte[] response)
        {
            if (sp.IsOpen)
            {
                for (int i = 0; i < response.Length; i++)
                {

                    response[i] = (byte)sp.ReadByte();

                }



            }

            else
            {
                strStatus = "port not open";
            }
        }
        //检查返回数据
        /// <summary>
        /// 检查返回数据
        /// </summary>
        /// <param name="response">返回字节</param>
        /// <returns>是否成功</returns>
        private bool CheckResponse(byte[] response)
        {

            byte[] CRC = new byte[2];
            //获取CRC校验
            GetCRC(response, ref CRC);

            if (CRC[0] == response[response.Length - 2] && CRC[1] == response[response.Length - 1])

                return true;

            else

                return false;

        }


        #region 发送并接收数据 M16

        private bool SendGetDataN1012(byte address, ref byte[] response)
        {
            //检查串口是否打开

            if (sp.IsOpen)
            {
                //清空缓存区
                sp.DiscardInBuffer();

                sp.DiscardOutBuffer();
                //命令字节组 
                byte[] command = new byte[8];

                BuildCommadN1012(address, ref command);

                try
                {

                    sp.Write(command, 0, command.Length);
                    GetResponse(ref response);

                    if (!CheckResponse(response))
                    {
                        return false;
                    }
                }

                catch (Exception ex)
                {

                    strStatus = "N1012 Write Error: " + ex.Message;

                    return false;
                }

                return true;
            }
            else
            {
                strStatus = "port not open";

                return false;
            }
        }

        #endregion

        private byte[] Convert2ByteTo1Byte(byte[] source)
        {
            byte[] buffer = new byte[16];
            for (int i = 0; i < (source.Length / 2); i++)
            {
                buffer[i] = source[2 * i];
                buffer[i] <<= 8;
                buffer[i] += source[2 * i + 1];
            }

            return buffer;

        }

        private byte[] ConverN1012SourceData(byte[] source)
        {
            if (source[1] == 0x03)
            {

                byte[] buffer = new byte[32];

                Array.Copy(source, 3, buffer, 0, 32);

                return Convert2ByteTo1Byte(buffer);
            }

            else
            {
                return new byte[] { 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15 };
            }

        }

        public byte[,] GetStatusByAddressN1012(int[] iaddress)
        {

            byte[] response = new byte[37];

            byte[] values = new byte[16];

            byte[,] buffer = new byte[iaddress.Length, 16];

            for (int i = 0; i < iaddress.Length; i++)
            {

                SendGetDataN1012((byte)iaddress[i], ref response);

                values = ConverN1012SourceData(response);

                for (int j = 0; j < 16; j++)
                {
                    buffer[i, j] = values[j];
                }

                Thread.Sleep(20);

            }

            return buffer;
        }

        
    }
}
红色部分是报“操作已超时”异常的部分 --------------------编程问答-------------------- 超时,没有数据发送,等待时间过长 --------------------编程问答-------------------- 是说设备那端没有返回的数据么?等待时间过长貌似不是,我发出一指令后设备的数据灯就立马闪一下,应该网络连接良好,那没返回数据一般是什么原因导致的呢? --------------------编程问答--------------------

    public string ZZID
    {
        get { return getstring(Request.QueryString["zzid"]); }
    }

--------------------编程问答-------------------- tangolivesky发的是什么东东?打酱油? --------------------编程问答-------------------- 没人踩么?跪求大神解答啊,很急 --------------------编程问答-------------------- 不知道楼主问题有没有解决,我现在也遇到了这样的问题,不知是什么原因
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,