C# 串口操作

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

 

 

最基本串口操作:

 

 private void sendCmd(string  i_cmd, bool i_isSendText)
        {
            byte[] send, receive;
            char[] cSend, cReceive;
            int i;

            if (i_isSendText)
            {
                i_cmd += "/x01a";
            }

            cSend = new char[i_cmd.Trim().Length];
            cSend = i_cmd.Trim().ToCharArray();
            if (i_cmd.Trim().Length == 0)
            {
                return;
            }

            send = new byte[i_cmd.Trim().Length + 2];
            for (i = 0; i < i_cmd.Trim().Length; i++)
            {
                send[i] = (byte)cSend[i];
            }    
            send[i++] = (byte)'/r';
            send[i++] = (byte)'/n';

 

            
                        m_receive_text.Text += new string(cReceive);

            // serial.Close();
        }

 

       public SerialPort port;
        public byte[]  receive;
        public char[]  cReceive;

 

         port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
            port.ReadTimeout = 10000;
            port.Open();          

 

          // 最基本串口操作         
            int readLen = 0;
           port.Write(send, 0, send.Length);

            System.Threading.Thread.Sleep(500);

            receive = new byte[1024];
            cReceive = new char[1024];
            readLen = port.Read(receive, 0, receive.Length);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值