日期:2014-05-18 浏览次数:20919 次
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()); }