首页 新闻 会员 周边 捐助

c#串口数据接收问题

0
悬赏园豆:5 [已解决问题] 解决于 2018-10-24 13:52
    public partial class _default : System.Web.UI.Page
    {
        public string temp = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            //字符转成16进制字符
            //string str = "YHY632A-1203";
            //char[] chars = str.ToCharArray();
            //List<string> thirty = new List<string>();
            //for (int i = 0; i < chars.Length;i++ )
            //{
            //    thirty.Add(((int)chars[i]).ToString("X"));
            //}
            //temp =string.Join(" ", thirty.ToArray());

            //逐字节异或值
            //int a =Convert.ToInt32("00",16);
            //int b =Convert.ToInt32( "00",16);
            //int c =Convert.ToInt32( "07",16);
            //int d = Convert.ToInt32("01",16);
            //int f =Convert.ToInt32( "03",16);
            //int t = a ^ b ^ c ^ d ^ f;
            //temp = t.ToString();

            SerialPort com3 = new SerialPort();
            byte[] data=new byte[9];
            data[0] = 0xAA;
            data[1] = 0xBB;
            data[2] = 0x05;
            data[3] = 0x00;
            data[4] = 0x00;
            data[5] = 0x00;
            data[6] = 0x04;
            data[7] = 0x01;
            //data[8] = 0x02;
            data[8] =(byte)Convert.ToInt32((data[4] ^ data[5] ^ data[6] ^ data[7] ^ data[8]).ToString(),16);
            try
            {
                com3.PortName = "COM3";
                com3.BaudRate = 115200;
                com3.DataBits = 8;
                com3.StopBits = StopBits.One;
                com3.ReceivedBytesThreshold = 1;
                com3.ReadTimeout = 3000;
                com3.Handshake = Handshake.None;
                com3.DataReceived +=new SerialDataReceivedEventHandler(com3_DataReceived);

                com3.DiscardInBuffer();
                com3.DiscardOutBuffer();
                com3.Open();
                com3.Write(data, 0, data.Length);


            }
            catch (Exception ue)
            {
               
            }
            finally
            {
                com3.Close();
            }
        }

        void com3_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort com3 = (SerialPort)sender;
            string indata = com3.ReadExisting();
        }
    }

如上代码,我用串口给一个rfid读卡器设备发送指令,但是无法触发datareceived事件,哪里出问题了?

哈哈啊的主页 哈哈啊 | 初学一级 | 园豆:5
提问于:2016-01-22 16:54
< >
分享
最佳答案
1

你把上面的代码,用winform程序试试。

你的确给读卡发数据了,但是你发完就直接close了,

就算你不close,你也不能确定读卡器返回数据了

收获园豆:5
Firen | 大侠五级 |园豆:5385 | 2016-01-22 17:04

意思是close只能在程序里手动去控制,数据接收完了再close?读卡器是有数据的,我直接在write后面read是可以读到数据,只是有时候能读到,有时候读不到

哈哈啊 | 园豆:5 (初学一级) | 2016-01-23 13:46
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册