1:串口名,波特率,数据位,停止位,有无奇偶校验 serialPort1.PortName = "COM4";serialPort1.BaudRate = 9600;serialPort1.DataBits = 8;serialPort1.StopBits = StopBits.One;serialPort1.Parity = Parity.None;serialPort1.Open(
1:串口名,波特率,数据位,停止位,有无奇偶校验
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
serialPort1.Parity = Parity.None;
serialPort1.Open();
2:接收时间需定一定时间的延迟,否则会有断续收数据的情况
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
Thread.Sleep(100);//设定一定时间的延迟
this.Invoke(new Action(() =>
{
textBox1.AppendText(result);
textBox1.AppendText(System.Environment.NewLine);//换行
}));
}
3:写读
写:serialPort1.Write(":010187");
读:serialPort1.ReadExisting();
4:可能涉及的字符串对应进制转换
当str为“A”,便会转换成int类型的10
int k = int.Parse(str, NumberStyles.AllowHexSpecifier);
5.遍历当前计算机可用串口
foreach (string item in SerialPort.GetPortNames())
{
comboBox1.Items.Add(item);
comboBox1.Text = item;
}//遍历串口名称数组,并将其添加到ComboBox控件中。