一直以來,玩8088單板機,上位機都是使用的綠色現成的串口軟件。
今天,感覺8088單板機的各部分測試都基本完成了。
本著玩的精神,自己寫一個上位機的簡單串口程序,與自己的8088單板機通訊。
功能:一個完整的C#命令行程序,使用串口8以9600波特率每秒發送字符'A',并實時顯示接收到的所有字
1.測試結果
2.完整程序
using System;
using System.IO.Ports;
using System.Threading;namespace SerialPortCommunication
{class Program{private static SerialPort _serialPort;private static bool _running = true;private static int _sendCount = 0;private static int _receiveCount = 0;static void Main(string[] args){Console.Title = "串口通信監控 (COM8, 9600 bps)";Console.ForegroundColor = ConsoleColor.Cyan;Console.WriteLine("串口通信命令行程序");Console.WriteLine("====================");Console.ResetColor();Console.WriteLine("配置: COM8, 9600 bps, 8N1");Console.WriteLine("功能: 每秒發送字符 'A',實時顯示接收數據");Console.WriteLine("按 Q 鍵退出程序");Console.WriteLine();// 初始化串口try{InitializeSerialPort();// 啟動接收線程Thread receiveThread = new Thread(ReceiveData);receiveThread.IsBackground = true;receiveThread.Start();// 啟動發送線程Thread sendThread = new Thread(SendData);sendThread.IsBackground = true;sendThread.Start();// 監控退出鍵while (_running){if (Console.KeyAvailable){var key = Console.ReadKey(true).Key;if (key == ConsoleKey.Q){_running = false;}}Thread.Sleep(100);}// 關閉串口_serialPort.Close();Console.ForegroundColor = ConsoleColor.Yellow;Console.WriteLine("\n程序已終止");Console.ResetColor();Console.WriteLine($"發送統計: {_sendCount} 條消息");Console.WriteLine($"接收統計: {_receiveCount} 個字符");}catch (Exception ex){Console.ForegroundColor = ConsoleColor.Red;Console.WriteLine($"錯誤: {ex.Message}");Console.ResetColor();}Console.WriteLine("按任意鍵退出...");Console.ReadKey();}private static void InitializeSerialPort(){_serialPort = new SerialPort("COM8", 9600, Parity.None, 8, StopBits.One){Handshake = Handshake.None,ReadTimeout = 500,WriteTimeout = 500,Encoding = System.Text.Encoding.ASCII};_serialPort.Open();Console.ForegroundColor = ConsoleColor.Green;Console.WriteLine("串口已成功打開");Console.ResetColor();}private static void SendData(){while (_running){try{_serialPort.Write("A");_sendCount++;// 在控制臺顯示發送狀態Console.ForegroundColor = ConsoleColor.Blue;Console.WriteLine($"[發送] A ({DateTime.Now:HH:mm:ss.fff})");Console.ResetColor();}catch (Exception ex){Console.ForegroundColor = ConsoleColor.Red;Console.WriteLine($"[發送錯誤] {ex.Message}");Console.ResetColor();}// 每秒發送一次Thread.Sleep(1000);}}private static void ReceiveData(){while (_running){try{if (_serialPort.BytesToRead > 0){string data = _serialPort.ReadExisting();_receiveCount += data.Length;// 在控制臺顯示接收數據Console.ForegroundColor = ConsoleColor.Magenta;Console.Write($"[接收] ");Console.ResetColor();// 特殊字符處理foreach (char c in data){if (c == '\n'){Console.WriteLine();}else if (c == '\r'){// 忽略回車符}else if (char.IsControl(c)){Console.Write($"[0x{((int)c):X2}]");}else{Console.Write(c);}}}}catch (Exception ex){Console.ForegroundColor = ConsoleColor.Red;Console.WriteLine($"[接收錯誤] {ex.Message}");Console.ResetColor();}Thread.Sleep(10); // 短暫休眠避免CPU占用過高}}}
}
3.技術實現
多線程結構
?