C#之串口

时间:2023-02-15 11:07:27

1.字符发送

   string strSend = "00 01 02 03";
serialPort1.Write(strSend);

2.字符接收

 ReadDataFromSerial Rdfs_str = new ReadDataFromSerial(DataShowMthod);
Serialdata = serialPort1.ReadExisting();
Invoke(Rdfs_str);
 this.txtDataReceive.Text +=Serialdata;

3.ASCII发送

   string strSend = "00 01 02 03";
string str = strSend.Replace(" ","");
int len = str.Length / ;
byte[] ret = new byte[len];
for(int i=;i<len;i++)
ret[i]=(byte)(Convert.ToInt32(str.Substring(i*,),));
serialPort1.Write(ret,,ret.Length);

4.ASCII接收

方法1:

 ReadDataFromSerial Rdfs_hex = new ReadDataFromSerial(DataShowMethod);
Serialdata = serialPort1.ReadExisting();
Invoke(Rdfs_hex);
 string str="";
byte[] bt = System.Text.Encoding.Default.GetBytes(Serialdata);
for (int i = ; i < bt.Length; i++)
str += bt[i].ToString("X2");
this.txtDataReceive.Text += str;

方法2:

 byte[] bt=new byte[SP.BytesToRead];
SP.Read(bt,,bt.Length);
for(int i=;i<bt.Length;i++)
Str += bt[i].ToString("X2");