1.添加引用
using System.IO.Ports;
2.建立序列槽,選擇參數
//擷取序列槽名稱數組
string[] SerialportName = SerialPort.GetPortNames();//
//第一個參數為序列槽名稱,比特率
SerialPort serialPort = new SerialPort(Settings.Default.strCom, 115200, Parity.None, 8, StopBits.One);
//委托
disp_delegate = new Displaydelegate(DispUI);
//設定資料接收函數
serialPort.DataReceived += new SerialDataReceivedEventHandler(Comm_DataReceived);
//資料接收函數
void Comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Byte[] InputBuf = new Byte[32];
try
{
serialPort.Read(InputBuf, 0, serialPort.BytesToRead); //讀取緩沖區的資料直到“}”即0x7D為結束符
System.Threading.Thread.Sleep(50);
this.Invoke(disp_delegate, InputBuf);
}
catch (TimeoutException ex) //逾時處理
{
MessageBox.Show(ex.ToString());
}
}
//接收到的資料轉換,并處理
public void DispUI(byte[] InputBuf)
{
ASCIIEncoding encoding = new ASCIIEncoding();
strReadString = encoding.GetString(InputBuf);
SaveLeftProductInfo();
}
3.調試 下載下傳序列槽調試工具,進行序列槽調試。筆記本沒有序列槽,也可以同序列槽調試工具添加虛拟序列槽。
4.序列槽資料發送
//參數(位元組數組,從0開始的偏移量,位元組數)/或者直接string 指定字元串 參見系統文檔。
Byte[] msg = new Byte[3];
msg[0] = 0x16;
msg[1] = 0x54;
msg[2] = 0x0D;
serialPort.Write(msg, 0, 3);