C#編寫一個控制臺程序的實(shí)現(xiàn)串口通信示例
1.用C#編寫一個控制臺程序,列出計(jì)算機(jī)上可用的串口,并能夠選擇要用的串口,波特率配置成9600,8,N,1,能夠進(jìn)行接受和發(fā)送字符串。
2.添加依賴項(xiàng)
3.程序
using System; using System.IO.Ports; using System.Text; using System.Threading; namespace SerialPortTerminal { class Program { private static SerialPort _serialPort; private static bool _continue = true; static void Main(string[] args) { Console.Title = "串口通信終端"; Console.OutputEncoding = Encoding.UTF8; Console.InputEncoding = Encoding.UTF8; try { // 列出可用串口 Console.WriteLine("可用的串口列表:"); string[] ports = SerialPort.GetPortNames(); if (ports.Length == 0) { Console.WriteLine("未找到可用串口。按任意鍵退出..."); Console.ReadKey(); return; } for (int i = 0; i < ports.Length; i++) { Console.WriteLine($"{i + 1}. {ports[i]}"); } // 選擇串口 int selectedIndex = -1; while (selectedIndex < 0 || selectedIndex >= ports.Length) { Console.Write($"\n請選擇串口 (1-{ports.Length}): "); if (int.TryParse(Console.ReadLine(), out int input) && input > 0 && input <= ports.Length) { selectedIndex = input - 1; } else { Console.WriteLine("無效的選擇,請重新輸入。"); } } string selectedPort = ports[selectedIndex]; Console.WriteLine($"已選擇: {selectedPort}"); // 創(chuàng)建并配置串口 _serialPort = new SerialPort(selectedPort) { BaudRate = 9600, Parity = Parity.None, DataBits = 8, StopBits = StopBits.One, Handshake = Handshake.None, ReadTimeout = 500, WriteTimeout = 500, Encoding = Encoding.UTF8 }; // 設(shè)置數(shù)據(jù)接收事件處理 _serialPort.DataReceived += SerialPortDataReceived; // 打開串口 _serialPort.Open(); Console.WriteLine("串口已打開,配置: 9600,8,N,1"); Console.WriteLine("輸入要發(fā)送的文本 (輸入 'exit' 退出):"); Console.WriteLine("---------------------------------"); // 啟動發(fā)送線程 Thread writeThread = new Thread(Write); writeThread.IsBackground = true; writeThread.Start(); // 等待退出 while (_continue) { Thread.Sleep(100); } // 關(guān)閉串口 if (_serialPort.IsOpen) { _serialPort.Close(); } Console.WriteLine("串口已關(guān)閉。"); } catch (Exception ex) { Console.WriteLine($"錯誤: {ex.Message}"); Console.WriteLine("按任意鍵退出..."); Console.ReadKey(); } } private static void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e) { try { SerialPort sp = (SerialPort)sender; string data = sp.ReadExisting(); if (!string.IsNullOrEmpty(data)) { Console.Write($"[接收] {data}"); } } catch (Exception ex) { Console.WriteLine($"接收錯誤: {ex.Message}"); } } private static void Write() { while (_continue) { try { string message = Console.ReadLine(); if (message?.ToLower() == "exit") { _continue = false; return; } if (_serialPort != null && _serialPort.IsOpen) { _serialPort.WriteLine(message); Console.WriteLine($"[發(fā)送] {message}"); } } catch (Exception ex) { Console.WriteLine($"發(fā)送錯誤: {ex.Message}"); } } } } }
4.結(jié)果
到此這篇關(guān)于C#編寫一個控制臺程序的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)C#編寫控制臺程序內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# textBox如何實(shí)時(shí)更新到最新行
這篇文章主要介紹了C# textBox如何實(shí)時(shí)更新到最新行問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04C#使用Jquery zTree實(shí)現(xiàn)樹狀結(jié)構(gòu)顯示 異步數(shù)據(jù)加載
這篇文章主要為大家詳細(xì)介紹了C#使用Jquery zTree實(shí)現(xiàn)樹狀結(jié)構(gòu)顯示和異步數(shù)據(jù)加載,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12C#使用NPOI實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出功能
這篇文章主要為大家詳細(xì)介紹了C#使用NPOI實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02C#短時(shí)間內(nèi)產(chǎn)生大量不重復(fù)的隨機(jī)數(shù)
在C#編程中,經(jīng)常會碰到產(chǎn)生隨機(jī)數(shù)的情況,并且是在短時(shí)間內(nèi)產(chǎn)生一組隨機(jī)數(shù)。如果這組隨機(jī)數(shù)中有大量重復(fù)的,則達(dá)不到我們的要求2013-02-02