日期:2014-05-18 浏览次数:20837 次
public Form1() { InitializeComponent(); } //初始化SerialPort对象方法.PortName为COM口名称,例如"COM1","COM2"等,注意是string类型 public void InitCOM(string PortName) { serialPort1 = new SerialPort(PortName); serialPort1.BaudRate = 9600;//波特率 serialPort1.Parity = Parity.None;//无奇偶校验位 serialPort1.StopBits = StopBits.Two;//两个停止位 serialPort1.Handshake = Handshake.RequestToSend;//控制协议 serialPort1.ReceivedBytesThreshold = 4;//设置 DataReceived 事件发生前内部输入缓冲区中的字节数 } //打开串口的方法 public void OpenPort() { try { serialPort1.Open(); } catch { } if (serialPort1.IsOpen) { Console.WriteLine("the port is opened!"); } else { Console.WriteLine("failure to open the port!"); } } //关闭串口的方法 public void ClosePort() { serialPort1.Close(); if (!serialPort1.IsOpen) { Console.WriteLine("the port is already closed!"); } } //调用实例,发送数据 private void button1_Click(object sender, EventArgs e) { InitCOM("COM3"); OpenPort(); byte[] data = Encoding.Unicode.GetBytes(this.textBox1.Text); string str = Convert.ToBase64String(data); serialPort1.WriteLine(str); ClosePort(); MessageBox.Show(this, "利用串口成功发送数据!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } //接收数据 private void button2_Click(object sender, EventArgs e) { try { byte[] datar = Convert.FromBase64String(serialPort1.ReadLine()); textBox2.Text = Encoding.Unicode.GetString(datar); ClosePort(); MessageBox.Show(this, "利用串口成功接收数据!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { ClosePort(); MessageBox.Show(this, "利用串口接收数据失败!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } }