C#串口初始化

 

           //通信端口
            string[] PortList = SerialPort.GetPortNames();

            if (PortList.Length > 0)
            {
                this.cmb_Port.DataSource = PortList;
                this.cmb_Port.SelectedIndex = 0;
            }
            //波特率
            string[] BaudList = new string[] { "2400", "4800", "9600", "19200", "38400" };
            this.cmb_Baud.DataSource = BaudList;
            this.cmb_Baud.SelectedIndex = 2;
            //校验位
            this.cmb_Parity.DataSource = Enum.GetNames(typeof(Parity));
            this.cmb_Parity.SelectedIndex = 0;
            //停止位
            this.cmb_StopBits.DataSource = Enum.GetNames(typeof(StopBits));
            this.cmb_StopBits.SelectedIndex = 1;
            //数据位
            int[] DataList = new int[] { 5, 6, 7, 8 };
            this.cmb_DataBits.DataSource = DataList;
            this.cmb_DataBits.SelectedIndex = 3;
            //校验方式
            this.cmb_ParityMethod.DataSource = Enum.GetNames(typeof(ParityMethod));
            this.cmb_ParityMethod.SelectedIndex = 0;

 设置串口属性

            this.serialPort.PortName = this.cmb_Port.Text.Trim();
            this.serialPort.BaudRate = Convert.ToInt32(this.cmb_Baud.Text.Trim());
            this.serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), this.cmb_Parity.Text.Trim(), true);
            this.serialPort.DataBits = Convert.ToInt32(this.cmb_DataBits.Text.Trim());
            this.serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), this.cmb_StopBits.Text.Trim(), true);

 

posted @ 2021-05-19 20:53  WellMandala  阅读(921)  评论(0编辑  收藏  举报