C# .net8 串口通信

            Thread thread = new Thread(new ThreadStart(() =>
            {


                Console.WriteLine("可用串口列表:");
                string[] ports = SerialPort.GetPortNames();
                foreach (string port in ports)
                {
                    Console.WriteLine(port);
                }

                Console.Write("请输入要连接的串口(例如COM3):");
                string portName = "COM3"; // Console.ReadLine();

                SerialPort serialPort = new SerialPort(
                    portName: portName,
                    baudRate: 9600,
                    parity: Parity.None,
                    dataBits: 8,
                    stopBits: StopBits.One
                );

                serialPort.Encoding = Encoding.UTF8; // 设置编码格式
                serialPort.ReadTimeout = 500;       // 读取超时时间(毫秒)
                serialPort.WriteTimeout = 500;      // 写入超时时间(毫秒)
                int i = 0;
                // 注册数据接收事件
                serialPort.DataReceived += async (sender, e) =>
                {
                    var sp = (SerialPort)sender;
                    try
                    {
                        if (sp.IsOpen)
                        {
                            string data = sp.ReadExisting();
                            Console.WriteLine($"[接收] {data}");
                            // 在 UI 线程上开始作业并立即返回。


                            if (i % 10 == 0)
                            {
                                // 在 UI 线程上开始作业并立即返回。
                                await Dispatcher.UIThread.InvokeAsync(() => {
                                    this.textBlock.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "称重数据:" + data;
                                });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"接收数据时出错:{ex.Message}");
                    }
                    i++;
                };

                try
                {
                    serialPort.Open();
                    Console.WriteLine("串口已成功打开。输入消息发送(输入 'exit' 退出)...");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"打开串口失败:{ex.Message}");
                    return;
                }

                // 发送消息循环
                string input;
                do
                {
                    input = Console.ReadLine() ?? "";
                    if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
                        break;

                    try
                    {
                        if (serialPort.IsOpen)
                        {
                            serialPort.WriteLine(input);
                            Console.WriteLine($"[发送] {input}");
                        }
                        else
                        {
                            Console.WriteLine("串口未打开,无法发送。");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"发送数据时出错:{ex.Message}");
                    }
                } while (true);

                // 关闭串口(using语句会自动处理)
                Console.WriteLine("程序退出。");

            }));

            thread.Start();

 

posted @ 2025-07-11 08:57  liliyou  阅读(138)  评论(0)    收藏  举报