打开串口
SerialPort port = new SerialPort();
public void OpenSerialPort()
{
port.BaudRate =Convert.ToInt32(SettingsModel.rs232_rate);
port.PortName = SettingsModel.com;
port.Parity = Parity.None;
port.DataBits = Convert.ToInt32(SettingsModel.data_bits);
port.StopBits = StopBits.One;
try
{
if (!port.IsOpen)
{
port.Open();
lab_scan_result.Text += "\n"+"串口"+port.PortName+"已打开";
}
port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
}
catch (Exception ex)
{
lab_scan_result.Text+=ex.Message;
}
}
接收回调
private void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[port.BytesToRead];
int length = port.Read(buffer, 0, buffer.Length);
string str = System.Text.Encoding.Default.GetString(buffer, 0, length);
if (length>0) {
m_SyncContext.Post(SetTextSafePost, str);
if (lab_scan_result.TextLength > 1024 * 1024)
{
lab_scan_result.Text = "执行过程:";
}
}
}
发送数据
public void Send_Data() {
port.Write("123");
}
关闭串口
public void closedSerialPort()
{
port.Close();
lab_scan_result.Text += "\n"+"串口已断开";
}