`
hzy3774
  • 浏览: 985484 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

C#中串口的操作

 
阅读更多


1.获取可用的串口名

static void Main(string[] args)
        {
            string[] ports = SerialPort.GetPortNames();//获取可用的串口
            foreach (string port in ports)
            {
                Console.WriteLine(port);
            }
            Console.ReadKey();
        }

 

 

串口的数据发送和接收: 

 static void Main(string[] args)
        {
            SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);//串口名:COM1,波特率:9600,无校验位,8个数据位,一个停止位
            port.Encoding = Encoding.Default;//设置编码方式为默认
            string writeMsg = null;
            string readMsg = null;
            try
            {
            	port.Open();//打开串口
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("串口不可用!");
                Console.ReadKey();
                return;
            }
            while (true)
            {
                writeMsg = Console.ReadLine();
                port.WriteLine(writeMsg);//发送一行数据
                readMsg = port.ReadLine();//接收消息
                Console.WriteLine("收到消息:" + readMsg);
            }
        }

  

 

  • 大小: 7.3 KB
  • 大小: 12.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics