C# CS_Prj01 串口通信控制台程序
一直以来,玩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.技术实现
多线程结构