前面设计好了界面,现在就开始写代码了,首先定义一个串口对象..
SerialPort serialport = new SerialPort();//定义串口对象
string[] ArryPort = SerialPort.GetPortNames();
comboBox1.Items.Clear();
for (int i = 0; i < ArryPort.Length; i++)
{
comboBox1.Items.Add(ArryPort[i]);
}
comboBox1.SelectedIndex = 0;
serialport.DataReceived += serialport_DataReceived;
void serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[2];
int adc_dat = 0;
serialport.Read(buffer, 0, buffer.Length);
adc_dat += buffer[i + 1];
adc_dat = (adc_dat << 8) + buffer[i + 2];;
this.Dispatcher.Invoke(new Action(() =>
{
progressBar1.Value = adc_dat;
}));
}
private void set_PortName()//将下拉框中的内容设置串口
{
serialport.PortName = comboBox1.SelectedItem.ToString();
}
private void set_BaudRate()//设置波特率
{
serialport.BaudRate = 115200;
}
private void Open_serial()//启动串口开始接收
{
set_PortName();//选择串口号
set_BaudRate();//选择波特率
try
{
serialport.Open();//打开当前串口
}
catch (Exception)
{
MessageBox.Show("串口被占用", "error");
}
}