您好,登錄后才能下訂單哦!
本篇內容主要講解“C#怎么實現連接電子秤串口自動稱重”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“C#怎么實現連接電子秤串口自動稱重”吧!
private SerialPort com; private void FormCheck_Load(object sender, EventArgs e) { //初始化COMList initCOMList(); } #region private void initCOMList() { ManageCOM com = new ManageCOM(); List<string> s = com.AutoGetCOM(); string[] comNames = s.ToArray(); comboxCOM.Items.Clear(); comboxCOM.Items.Add("請選擇COM"); comboxCOM.SelectedIndex = 0; foreach (string portName in comNames) { //添加COM口到界面下拉框 comboxCOM.Items.Add(portName); } } #endregion private void btnStart_Click(object sender, EventArgs e) { getWeightfromCOM(); } #region private void getWeightfromCOM() { int selectIndex= comboxCOM.SelectedIndex; if (selectIndex!=0) { string COM = comboxCOM.Items[selectIndex].ToString(); com = new SerialPort(COM); //實例化SerialPort并設置COM口 com.BaudRate = 9600;//波特率 com.Parity = Parity.None;//無奇偶校驗位 com.StopBits = StopBits.Two;//兩個停止位 com.Handshake = Handshake.RequestToSend;//控制協議 com.ReceivedBytesThreshold = 13;//設置 DataReceived 事件發生前內部輸入緩沖區中的字節數,我這里是13字節為一組 com.Open(); //打開串口 com.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived); //接受數據線程 } else { MessageBox.Show("請選擇COM"); } } /// <summary> /// 監聽串口數據線程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e) { Thread.Sleep(500);//線程休眠500毫秒,方便接收串口的全部數據 try { if (com.IsOpen) { byte[] readBuffer = new byte[com.ReadBufferSize + 1]; try { int count = com.Read(readBuffer, 0, com.ReadBufferSize); //讀取串口數據(監聽) String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer, 0, count);//將字節數組解碼為字符串 if (count != 0) { //這里強調一下,線程里不可以直接對UI進行賦值,只能使用委托操作控件 this.BeginInvoke(new System.Threading.ThreadStart(delegate () { rbResult.Text = SerialIn; })); } } catch (TimeoutException) { } } else { TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50); Thread.Sleep(waitTime); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } #endregion
到此,相信大家對“C#怎么實現連接電子秤串口自動稱重”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。