日期:2014-05-18  浏览次数:20919 次

读取和发生串口数据
C# code

  private void btnWrite_Click(object sender, EventArgs e)         
  {             
       this.serialPort1.PortName = "COM4";                     
       this.serialPort1.BaudRate = 9600;                     
       this.serialPort1.DataBits = 8;                     
       this.serialPort1.Parity = System.IO.Ports.Parity.None;   
       this.serialPort1.StopBits = System.IO.Ports.StopBits.One;       
       if (this.serialPort1.IsOpen == false)              
       {               
          this.serialPort1.Open();                 
          byte[] data = Encoding.Unicode.GetBytes(textBox3.Text);  
          string str = Convert.ToBase64String(data);      
          serialPort1.WriteLine(str);         
          MessageBox.Show("数据发送成功!","系统提示");
       }
  }


  private void button2_Click(object sender, EventArgs e)      
     {         第一种接收
                byte[] data = Convert.FromBase64String(serialPort1.ReadLine());     
                textBox2.Text = Encoding.Unicode.GetString(data);  
                serialPort1.Close();     
               MessageBox.Show("数据接收成功!","系统提示");   
                第二种接收
                 int n = this.serialPort1.BytesToRead;        
                byte[] buf = new byte[n];      
                this.serialPort1.Read(buf, 0, n);
                  string receiveData = Encoding.ASCII.GetString(buf);
                   MessageBox.Show(receiveData.ToString());

      }


为什么第二种接收没有数据? 第一种接收会卡在 byte[] data = Convert.FromBase64String(serialPort1.ReadLine()); 这一步? 求指教

------解决方案--------------------
两种迹象表明缓冲区内无数据
你在serialPort1.WriteLine(str); 后马上读取,看看能不能读到数据