命名空間:
using System.IO.Ports;
實例化:
//public SerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits);
//portName:
// 要使用的端口(例如 COM1)。
//
// baudRate:
// 波特率。
//
// parity:
// System.IO.Ports.SerialPort.Parity 值之一。
//
// dataBits:
// 數據位值。
//
// stopBits:
// System.IO.Ports.SerialPort.StopBits 值之一。
SerialPort serialPortBestCode1 = new SerialPort("COM1", 115200, Parity.None, 8, StopBits.One);
返回函數:
//表示將處理 System.IO.Ports.SerialPort 對象的數據接收事件的方法。
serialPortBestCode1.DataReceived += new SerialDataReceivedEventHandler(Comm_BestCode1DataReceived);
//...
void Comm_BestCode1DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (sender.GetType() != typeof(System.IO.Ports.SerialPort))
{
return;
}
string strReceive = string.Empty;
string strCollect = string.Empty;
System.IO.Ports.SerialPort comPort = (System.IO.Ports.SerialPort)sender;
try
{
comPort.ReceivedBytesThreshold = comPort.ReadBufferSize;
while (true)
{
strReceive = comPort.ReadExisting();
if (string.Equals(strReceive, string.Empty))
{
break;
}
else
{
strCollect += strReceive;
Application.DoEvents();
Thread.Sleep(100);
}
}
strCollect = strCollect.Replace("\0", string.Empty);
strCollect = strCollect.Replace("\r\n", string.Empty);
strCollect = strCollect.Replace("\r", string.Empty);
strCollect = strCollect.Replace("\n", string.Empty);
}
catch (Exception ex)
{
MessageBox.Show("主動異常捕捉:Comm_BestCode1DataReceived函數報錯:"+ex.Message);
//MessageBox.Show(this, ex.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
comPort.ReceivedBytesThreshold = 1;
if (strCollect.IndexOf("1-1") > -1)
{
Log("成功開啓噴碼機1校驗功能");
}
if (strCollect.IndexOf("R") > -1)
{
aTimer.Stop();
Log("噴碼機1#校驗成功,收到返回內容:" + strCollect);
Thread.Sleep(5000);
TestPenma();
}
}
}
數據發送:
public void ModifyBCP1Messages(string[] fields, string[] values)
{
try
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fields.Length; ++i)
{
sb.Append(string.Format("^{0} {1}", fields[i], values[i]));
}
string cmd = string.Format("^MD{0}\r", sb.ToString());
if (serialPortBestCode1.IsOpen)
serialPortBestCode1.WriteLine(cmd);
}
catch (Exception ex)
{
MessageBox.Show("主動異常捕捉:ModifyBCP1Messages函數報錯:" + ex.Message);
}
}