在.netframework2.0引入了System.IO.Ports命名,简化了我们串口的编程代码.
首先创建一个winform窗体,在窗体上建两个文本框和一个按钮,两个文本框分别用来发送和接收数据,按钮用来触发发送事件,然在工具箱中一个serialPort控件,或者在代码中进行实例化。下面为后如代码:
- private delegate void GetStr1(string str);
- public Form1()
- {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- serialPort1.PortName = "COM1";
- serialPort1.BaudRate = 9600;
- serialPort1.Parity = Parity.None;
- serialPort1.DataBits = 8;
- serialPort1.StopBits = StopBits.One;
- serialPort1.Open();
- serialPort1.Write(textBox1.Text);
- }
- private void input1(string s){
- textBox2.Text = s;
- }
- private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- GetStr1 gg = new GetStr1(input1);
- textBox2.Invoke(gg, new object[] { serialPort1.ReadExisting() });
- serialPort1.Close();
- }
代码写好后可以将计算机串口的2针和3针相连接对以上代码进行测试.