西安軟件開發之串口開發
日期:2018/8/20 發布人:潤宇軟件
瀏覽量:14
1.字符發送
1 string strSend = "00 01 02 03";
2 serialPort1.Write(strSend);
2.字符接收
1 ReadDataFromSerial Rdfs_str = new ReadDataFromSerial(DataShowMthod);
2 Serialdata = serialPort1.ReadExisting();
3 Invoke(Rdfs_str);
1 this.txtDataReceive.Text +=Serialdata;
3.ASCII發送
1 string strSend = "00 01 02 03";
2 string str = strSend.Replace(" ","");
3 int len = str.Length / 2;
4 byte[] ret = new byte[len];
5 for(int i=0;i<len;i++)
6 ret[i]=(byte)(Convert.ToInt32(str.Substring(i*2,2),16));
7 serialPort1.Write(ret,0,ret.Length);
4.ASCII接收
方法1:
1 ReadDataFromSerial Rdfs_hex = new ReadDataFromSerial(DataShowMethod);
2 Serialdata = serialPort1.ReadExisting();
3 Invoke(Rdfs_hex);
1 string str="";
2 byte[] bt = System.Text.Encoding.Default.GetBytes(Serialdata);
3 for (int i = 0; i < bt.Length; i++)
4 str += bt[i].ToString("X2");
5 this.txtDataReceive.Text += str;
方法2:
1 byte[] bt=new byte[SP.BytesToRead];
2 SP.Read(bt,0,bt.Length);
3 for(int i=0;i<bt.Length;i++)
4 Str += bt[i].ToString("X2");