asp.net c serialPort顯示資料代碼

來源:互聯網
上載者:User

asp教程.net c serialport顯示資料代碼
//serial port就是所謂的串口,或者串列口。是電腦的介面之一,串連某些裝置用的,如果你不需要仔細瞭解它的話,把它當成跟usb類似的介面就可以了。只是有時候串口不支援熱插拔

void comm_datareceived(object sender, serialdatareceivedeventargs e)  
  {  
  int n = comm.bytestoread;//先記錄下來,避免某種原因,人為的原因,操作幾次之間時間長,緩衝不一致  
  byte[] buf = new byte[n];//聲明一個臨時數組儲存當前來的串口資料  
  received_count += n;//增加接收計數  
  comm.read(buf, 0, n);//讀取緩衝資料  
  builder.clear();//清除字串構造器的內容  
  //因為要訪問ui資源,所以需要使用invoke方式同步ui。  
  this.invoke((eventhandler)(delegate  
  {  
  //判斷是否是顯示為16禁止  
  if (checkboxhexview.checked)  
  {  
  //依次的拼接出16進位字串  
  foreach (byte b in buf)  
  {  
  builder.append(b.tostring("x2") + " ");  
  }  
  }  
  else  
  {  
  //直接按ascii規則轉換成字串  
  builder.append(encoding.ascii.getstring(buf));  
  }  
  //追加的形式添加到文字框末端,並滾動到最後。  
  this.txget.appendtext(builder.tostring());  
  //修改接收計數  
  labelgetcount.text = "get:" + received_count.tostring();  
  }));  
  }

  
  //方法二
  
 

private void serialport1_datareceived(object sender,serialdatareceivedeventargs e)
  {
  system.threading.thread.sleep(100);
  int bytes = sepor.bytestoread;
  byte[] buffer=new byte[bytes];
  if (bytes == 0)
  {
  return;
  }
  sepor.read(buffer,0,bytes);
  string srt = string.empty;
  foreach(byte a in buffer)
  {
  srt += a.tostring();
  }
  textbox1.text =srt;
   
  }


 private void form1_load(object sender, eventargs e)
  {
  sepor.portname = "com4"; //選擇串口com4
  sepor.baudrate = 4800; //設定通訊口參數
  sepor.databits = 7; //資料位元
  sepor.parity = system.io.ports.parity.none; //校正位 無校正
  sepor.stopbits = system.io.ports.stopbits.one; //停止位 1位
  sepor.readbuffersize = 1024;

  sepor.open();
  sepor.readexisting(); //設定input從接收緩衝讀取全資料
  sepor.receivedbytesthreshold = 1; //設定引發oncomm事件的位元組長度
  sepor.discardinbuffer(); //清楚接受緩衝區
  timer1.start();
  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.