using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO.Ports; using System.Threading; namespace TestSerialPort { public partial class frmTESTSerialPort : Form { public frmTESTSerialPort() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; } private Button button1; private TextBox txtSend; private TextBox txtReceive; private Label label1; private Label label2; /// <summary> /// 必需的設計器變量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的資源。 /// </summary> /// <param name="disposing">如果應釋放託管資源,爲 true;否則爲 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗體設計器生成的代碼 /// <summary> /// 設計器支持所需的方法 - 不要 /// 使用代碼編輯器修改此方法的內容。 /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.txtSend = new System.Windows.Forms.TextBox(); this.txtReceive = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(440, 379); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "發送"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // txtSend // this.txtSend.Location = new System.Drawing.Point(59, 12); this.txtSend.Multiline = true; this.txtSend.Name = "txtSend"; this.txtSend.Size = new System.Drawing.Size(456, 164); this.txtSend.TabIndex = 2; // // txtReceive // this.txtReceive.Location = new System.Drawing.Point(59, 200); this.txtReceive.Multiline = true; this.txtReceive.Name = "txtReceive"; this.txtReceive.Size = new System.Drawing.Size(456, 164); this.txtReceive.TabIndex = 2; // // label1 // this.label1.Location = new System.Drawing.Point(13, 15); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(41, 12); this.label1.TabIndex = 0; this.label1.Text = "發送"; // // label2 // this.label2.Location = new System.Drawing.Point(13, 213); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(41, 12); this.label2.TabIndex = 0; this.label2.Text = "接收"; // // frmTESTSerialPort // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(546, 434); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.txtReceive); this.Controls.Add(this.txtSend); this.Controls.Add(this.button1); this.Name = "frmTESTSerialPort"; this.Text = "串口試驗"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private void button1_Click(object sender, EventArgs e) { //實例化串口對象(默認:COMM1,9600,e,8,1) SerialPort serialPort1 = new SerialPort(); //更改參數 serialPort1.PortName = "COM1"; serialPort1.BaudRate = 19200; serialPort1.Parity = Parity.Odd; serialPort1.StopBits = StopBits.Two; //上述步驟可以用在實例化時調用SerialPort類的重載構造函數 //SerialPort serialPort = new SerialPort("COM1", 19200, Parity.Odd, StopBits.Two); //打開串口(打開串口後不能修改端口名,波特率等參數,修改參數要在串口關閉後修改) serialPort1.Open(); //發送數據 SendStringData(serialPort1); //也可用字節的形式發送數據 //SendBytesData(serialPort1); //開啓接收數據線程 ReceiveData(serialPort1); } //發送字符串數據 private void SendStringData(SerialPort serialPort) { serialPort.Write(txtSend.Text); } /// <summary> /// 開啓接收數據線程 /// </summary> private void ReceiveData(SerialPort serialPort) { //同步阻塞接收數據線程 Thread threadReceive=new Thread(new ParameterizedThreadStart(SynReceiveData)); threadReceive.Start(serialPort); //也可用異步接收數據線程 //Thread threadReceiveSub = new Thread(new ParameterizedThreadStart(AsyReceiveData)); //threadReceiveSub.Start(serialPort); } //發送二進制數據 private void SendBytesData(SerialPort serialPort) { byte[] bytesSend=System.Text.Encoding.Default.GetBytes(txtSend.Text ); serialPort.Write(bytesSend, 0, bytesSend.Length); } //同步阻塞讀取 private void SynReceiveData(object serialPortobj) { SerialPort serialPort = (SerialPort)serialPortobj; System.Threading.Thread.Sleep(0); serialPort.ReadTimeout = 1000; try { //阻塞到讀取數據或超時(這裏爲2秒) byte firstByte=Convert.ToByte(serialPort.ReadByte()); int bytesRead=serialPort.BytesToRead ; byte[] bytesData=new byte[bytesRead+1]; bytesData[0] = firstByte; for (int i = 1; i <=bytesRead; i++) bytesData = Convert.ToByte( serialPort.ReadByte()); txtReceive.Text = System.Text.Encoding.Default.GetString(bytesData); } catch(Exception e) { MessageBox.Show(e.Message); //處理超時錯誤 } serialPort.Close(); } //異步讀取 private void AsyReceiveData(object serialPortobj) { SerialPort serialPort = (SerialPort)serialPortobj; System.Threading.Thread.Sleep(500); try { txtReceive.Text = serialPort.ReadExisting(); } catch (Exception e) { MessageBox.Show(e.Message); //處理錯誤 } serialPort.Close(); } } static class Program { /// <summary> /// 應用程序的主入口點。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmTESTSerialPort()); } } }
(以下是附加同步和異步線程)
using System; using System.Collections.Generic; using System.Text; using System.IO.Ports; using System.ComponentModel; using System.Threading; namespace Cserver { class ToCom { priva using System; using System.Collections.Generic; using System.Text; using System.IO.Ports; using System.ComponentModel; using System.Threading; namespace Cserver { class ToCom { private System.IO.Ports.SerialPort serialPort1 = new SerialPort(); public delegate byte[] getDate(byte[] bts); private getDate mygetDate; private string com; public ToCom(string com) { this.com = com; serialPort1.PortName = com; //端口號 serialPort1.BaudRate = 9600; //比特率 serialPort1.Parity = Parity.None;//奇偶校驗 serialPort1.StopBits = StopBits.One;//停止位 serialPort1.ReadTimeout = 1000; //讀超時,即在1000內未讀到數據就引起超時異常 } #region 發送接收數據 public void SendMsg(string senStr) { serialPort1.Open(); byte[] myByte = StringToByte_2(senStr); serialPort1.Write(myByte, 0, myByte.Length); serialPort1.Close(); } public string ReadMsg() { serialPort1.Open(); string rd="null "; #region 讀數據老方法 ////------------mothed1---- //int i = serialPort1.ReadBufferSize; // byte[] data = Convert.FromBase64String(serialPort1.ReadLine()); // rd = Encoding.Unicode.GetString(data); // // mothed2 //int DataLength = serialPort1.BytesToRead; //int i = 0; //StringBuilder sb = new StringBuilder(); //while (i < DataLength) //{ // byte[] ds = new byte[1024]; // int len = serialPort1.Read(ds, 0, 1024); // // sb.Append(Encoding.ASCII.GetString(ds, 0, len)); // sb.Append(ByteToString(ds)); // i += len; //} // // mothed2 //byte[] data= new byte[serialPort1.BytesToRead]; //int i = serialPort1.Read(data, 0, serialPort1.BytesToRead); //rd = ByteToString(data); #endregion // mothed3 byte[] data = new byte[serialPort1.BytesToRead]; int i = serialPort1.Read(data, 0, serialPort1.BytesToRead); rd = ByteToString(data); return rd; } // string getdate(byte[]) public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { byte[] readBuffer = new byte[serialPort1.ReadBufferSize]; serialPort1.Read(readBuffer, 0, readBuffer.Length); //this.Invoke(interfaceUpdataHandle, new string[] { Encoding.UTF8.GetString(readBuffer) }); // this.Invoke(interfaceUpdataHandle, new string[] { ToCom.ByteToString(readBuffer) }); string s = ToCom.ByteToString(readBuffer); } #endregion /// <summary> /// 串口讀(非阻塞方式讀串口,直到串口緩衝區中沒有數據 /// </summary> /// <param name="readBuf">串口數據緩衝 </param> /// <param name="bufRoom">串口數據緩衝空間大小 </param> /// <param name="HowTime">設置串口讀放棄時間 </param> /// <param name="ByteTime">字節間隔最大時間 </param> /// <returns>串口實際讀入數據個數 </returns> public int ReadComm(out Byte[] readBuf, int bufRoom, int HowTime, int ByteTime) { //throw new System.NotImplementedException(); readBuf = new Byte[64]; Array.Clear(readBuf, 0, readBuf.Length); int nReadLen, nBytelen; if (serialPort1.IsOpen == false) return -1; nBytelen = 0; serialPort1.ReadTimeout = HowTime; try { readBuf[nBytelen] = (byte)serialPort1.ReadByte(); byte[] bTmp = new byte[1023]; Array.Clear(bTmp, 0, bTmp.Length); nReadLen = ReadBlock(out bTmp, bufRoom - 1, ByteTime); if (nReadLen > 0) { Array.Copy(bTmp, 0, readBuf, 1, nReadLen); nBytelen = 1 + nReadLen; } else if (nReadLen == 0) nBytelen = 1; } catch (Exception ex) { throw new Exception(ex.Message); } return nBytelen; } /// <summary> /// 串口同步讀(阻塞方式讀串口,直到串口緩衝區中沒有數據,靠字符間間隔超時確定沒有數據) /// </summary> /// <param name="ReadBuf">串口數據緩衝 </param> /// <param name="ReadRoom">串口數據緩衝空間大小 </param> /// <param name="ByteTime">字節間隔最大時間 </param> /// <returns>從串口實際讀入的字節個數 </returns> public int ReadBlock(out byte[] ReadBuf, int ReadRoom, int ByteTime) { //throw new System.NotImplementedException(); ReadBuf = new byte[1024]; Array.Clear(ReadBuf, 0, ReadBuf.Length); sbyte nBytelen; //long nByteRead; if (serialPort1.IsOpen == false) return 0; nBytelen = 0; serialPort1.ReadTimeout = ByteTime; while (nBytelen < (ReadRoom - 1)) { try { ReadBuf[nBytelen] = (byte)serialPort1.ReadByte(); nBytelen++; // add one } catch (Exception ex) { throw new Exception( ex.Message); break; } } ReadBuf[nBytelen] = 0x00; return nBytelen; } /// <summary> /// 字符數組轉字符串16進制 /// </summary> /// <param name="InBytes"> 二進制字節 </param> /// <returns>類似"01 02 0F" </returns> public static string ByteToString(byte[] InBytes) { string StringOut = ""; foreach (byte InByte in InBytes) { StringOut = StringOut + String.Format("{0:X2}", InByte) + " "; } return StringOut.Trim(); } /// <summary> /// strhex 轉字節數組 /// </summary> /// <param name="InString">類似"01 02 0F" 用空格分開的 </param> /// <returns> </returns> public static byte[] StringToByte(string InString) { string[] ByteStrings; ByteStrings = InString.Split(" ".ToCharArray()); byte[] ByteOut; ByteOut = new byte[ByteStrings.Length]; for (int i = 0; i <= ByteStrings.Length - 1; i++) { ByteOut[i] = byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber); } return ByteOut; } /// <summary> /// strhex 轉字節數組 /// </summary> /// <param name="InString">類似"01 02 0F" 中間無空格 </param> /// <returns> </returns> public static byte[] StringToByte_2(string InString) { byte[] ByteOut; InString = InString.Replace(" ",""); try { string[] ByteStrings = new string[InString.Length/2]; int j = 0; for (int i = 0; i < ByteStrings.Length ; i++) { ByteStrings[i] = InString.Substring(j,2); j += 2; } ByteOut = new byte[ByteStrings.Length]; for (int i = 0; i <= ByteStrings.Length - 1; i++) { ByteOut[i] = byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber); } } catch (Exception ex) { throw new Exception(ex.Message); } return ByteOut; } /// <summary> /// 字符串 轉16進制字符串 /// </summary> /// <param name="InString">unico </param> /// <returns>類似“01 0f” </returns> public static string Str_To_0X(string InString) { return ByteToString (UnicodeEncoding.Default.GetBytes(InString)); } } }
本篇是系列最後一篇,本系統所有內容均來自 俞志宏 老師的 《我在硅谷管芯片:芯片產品線經理生存指南》一書的總結整理。 工程師 工作比較線性,需要深挖專業知識,但也僅需要專注於專業知識。通常的工作內容是::設計某個電路,測試某些參數,解決某
前言 注意: 學習源碼一定一定不要太關注代碼的編寫,而是注意代碼實現思想: 通過設問方式來體現代碼中的思想;方法:5W+1H 源代碼: https://gitee.com/xbhog/mybatis-xbhog ; https://gi
kubeadm init --control-plane-endpoint="192.168.215.200" --kubernetes-version=v1.28.2 --pod-network-cidr=10.244.0.0/16 --
根據提示,賦權限,刪除文件等 jimmy@MacBook-Pro ~ % brew link node Linking /usr/local/Cellar/node/20.0.0... Er
在網頁內可以輕鬆反覆登陸Microsoft賬戶,但是在EDGE瀏覽器上無法登陸。瀏覽器原本有一個用戶配置,已經登陸了一個賬號,在創建新的用戶配置時,始終無法登陸賬戶。這個情況持續了兩個星期 若是有使用代理,加速器,hosts修改器
無論hosts文件丟失還是被更改了內容,都可以嘗試以下的內容來恢復原樣。 一、 技術難度:★☆(1星半) 閱讀時間:大約2分鐘 hosts文件所在位置:C:\Windows\System32\drivers\etc 二、
python gdal 安裝使用 python GDAL有兩種安裝方式: 第一種 是利用 pip install gdal 安裝 如果安裝失敗,可以採用下面的方法:第二種 離線安裝 步驟: (1)查看python版本;(2)下載gdal的
看到二維碼,很容易猜到黑白相間的小方格就是二進制比特。那麼這些比特是怎麼得到的?小方格又是按照什麼規則排布的?今天咱們就從零開始將一個 url 畫成二維碼。 考慮到大多數人可能不太瞭解二維碼,所以先講下基礎概念。你也可以先看看左耳朵耗子寫的
爲什麼規劃是高階能力 明確 什麼是正確的事(what、why),前置於 如何正確的做(how)。真有能力明確,就可以不用親自做 提出正確的問題,比解決問題更難 權力/權威/影響力,建立在 比別人都更正確 規劃強依賴的 事理
title: Vue TypeScript 實戰:掌握靜態類型編程 date: 2024/6/10 updated: 2024/6/10 excerpt: 這篇文章介紹瞭如何在TypeScript環境下爲Vue.js應用搭建項目結構,包括
# 假設puzzle是一個包含多個字符串的列表,每個字符串都是同一長度的,代表字母網格的一行 puzzle = [ "JGJGDDAOYD", "IDGFHSPOSA", "FGDIOSAFSC
前言 大家好,我是老馬。很高興遇到你。 我們爲 java 開發者實現了 java 版本的 nginx https://github.com/houbb/nginx4j 如果你想知道 servlet 如何處理的,可以參考我的另一個項目:
查詢以36823206字符開頭以951字符結尾的SPU數據 select * from lingyejun_product where spu_code regexp '^36823206' and spu_code regexp '95
Web Page Marker Pen All In One Web 網頁標記筆 Free Screenshot Capture & Annotation Tool Useful extension for taking screen
2024 上海市居民小區的電動自行車使用共享充電服務的充電收費標準和依據 All In One 電動自行車 充電服務 收費標準 合法性、合理性 按照實際的充電度數和電費價格收取電費,服務費應該單獨收取 每次充電收取的服務費的佔比不能高