背景
C#串口接收一条数据之后才发送另外一条命令,依次发送一组命令。
代码实现
-
private void button1_Click(object sender, EventArgs e) { string[] cmd = new string[3]; cmd[0] = "第一条命令"; cmd[1] = "第二条命令"; cmd[2] = "第三条命令"; for (int i = 0; i < 3;) { serialPort1.Write(cmd[i]); Thread.Sleep(200);//很重要,不然会累积到一起接收 int zijie = serialPort1.BytesToRead; byte[] res = new byte[zijie]; serialPort1.Read(res, 0, zijie); string result = System.Text.Encoding.UTF8.GetString(res); if (cmd[i] == "第一条命令") { this.textBox1.Text = result;//第一条命令接受完的操作 } else if (cmd[i] == "第二条命令") { this.textBox2.Text = result;//第二条命令接受完的操作 } else if (cmd[i] == "第三条命令") { this.textBox3.Text = result;//第三条命令接受完的操作 } else { } Thread.Sleep(200); i++; } }