C#实现自动连接串口
using System;
using System.IO.Ports;
using System.Text;
using System.Threading;

namespace ConsoleApplication3
{
    internal class Program
    {
        public SerialPort serialPort;
        public bool IsConnected = false;

        public static void Main(string[] args)
        {
            Program p = new Program();
            while (true)
            {
                while (true)
                {
                    bool status =  p.PortConnect();
                    if (status)
                        break;
                }

                while (true)
                {
                    if (p.serialPort == null || !p.serialPort.IsOpen)
                    {
                        continue;
                    }
                    p.serialPort.WriteLine("Hello world");
                    Thread.Sleep(500);
                }
            }
        }

        public bool PortConnect()
        {
            string[] portNames = SerialPort.GetPortNames();
            foreach (string name in portNames)
            {
                try
                {
                    serialPort = new SerialPort(name, 9600);
                    serialPort.Open();
                    if (serialPort.IsOpen)
                    {
                        serialPort.Write("ok");
                        Thread.Sleep(100);
                        byte[] bytes = new byte[serialPort.BytesToRead];
                        serialPort.Read(bytes, 0, serialPort.BytesToRead);
                        string code = Encoding.UTF8.GetString(bytes);
                        if (code.Contains("ok"))
                        {
                            return true;
                        }
                    }
                    {
                        Console.WriteLine("串口打开失败");
                    }
                    if (serialPort != null) serialPort.Close();
                    serialPort = null;
                }
                catch (Exception e)
                {
                    if (serialPort != null) serialPort.Close();
                    serialPort = null;
                    Console.WriteLine(e.Message);
                }
            }
            return false;
        }
    }
}
上一篇
下一篇