//建立一個串列埠通訊SerialPort CurrentPort = null;CurrentPort = new SerialPort(); CurrentPort.ReadBufferSize = 128; CurrentPort.PortName = comName; //埠號 CurrentPort.BaudRate = bandRate; //位元率 CurrentPort.Parity =parity;//奇偶校驗 CurrentPort.StopBits = stop;//停止位 CurrentPort.DataBits = databit;//資料位 CurrentPort.ReadTimeout = 1000; //讀超時,即在1000內未讀到資料就引起超時異常 //繫結資料接收事件,因為傳送是被動的,所以你無法主動去獲取別人傳送的程式碼,只能透過這個事件來處理 CurrentPort.DataReceived += Sp_DataReceived; CurrentPort.Open(); 定義一個變數 byte[] receiveStr; //繫結的事件處理函式 private static void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { SerialPort sp = sender as SerialPort; if (sp == null) return; byte[] readBuffer = new byte[sp.ReadBufferSize]; sp.Read(readBuffer, 0, readBuffer.Length); //賦值 receiveStr=readBuffer;//當然你可以透過轉換將byte[]轉換為字串。 } //你要求的按鈕事件可以這麼寫 private void button1_Click(object sender, EventArgs e) { if(receiveStr!=null) { 變數 xxx=receiveStr; } }
使用C#中的串列埠類,然後進行串列埠類的初始化後【串列埠的設定,波特率,停止位等】,就可以進行串列埠的接收和傳送資料了。
//建立一個串列埠通訊SerialPort CurrentPort = null;CurrentPort = new SerialPort(); CurrentPort.ReadBufferSize = 128; CurrentPort.PortName = comName; //埠號 CurrentPort.BaudRate = bandRate; //位元率 CurrentPort.Parity =parity;//奇偶校驗 CurrentPort.StopBits = stop;//停止位 CurrentPort.DataBits = databit;//資料位 CurrentPort.ReadTimeout = 1000; //讀超時,即在1000內未讀到資料就引起超時異常 //繫結資料接收事件,因為傳送是被動的,所以你無法主動去獲取別人傳送的程式碼,只能透過這個事件來處理 CurrentPort.DataReceived += Sp_DataReceived; CurrentPort.Open(); 定義一個變數 byte[] receiveStr; //繫結的事件處理函式 private static void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { SerialPort sp = sender as SerialPort; if (sp == null) return; byte[] readBuffer = new byte[sp.ReadBufferSize]; sp.Read(readBuffer, 0, readBuffer.Length); //賦值 receiveStr=readBuffer;//當然你可以透過轉換將byte[]轉換為字串。 } //你要求的按鈕事件可以這麼寫 private void button1_Click(object sender, EventArgs e) { if(receiveStr!=null) { 變數 xxx=receiveStr; } }