|
自己之前用arduino mega2560 写了一段与串口通讯,一问一答的程序,本来好好的,最近不知道为什么重新烧录进去却发现老是出错。通过各种检查,最后发现自己接受的数据多了一组,原来是发送指令时造成的。
请问下大神们,我的发送数组的方式错在哪里,特意加了延时还有不能解决。
- unsigned char data1[8] = {0x01,0x03,0x10,0x01,0x00,0x02,0x91,0x0B}; //温控表指令
- unsigned char data2[8] = {0x11,0x03,0x00,0x35,0x00,0x01,0x96,0x94}; //数控电源功率指令
- String comdata1 = "";
- String comdata2 = "";
- void setup() {
- Serial.begin(9600);
- Serial2.begin(9600); //设置串口波特率9600 温控表
- Serial3.begin(9600); //设置串口波特率9600 功率表
- }
- void loop() {
- // wenkongbiao();
- gonglvbiao();
- }
- void wenkongbiao(){ //温控表功率
- for (int i = 0; i < 8; i++)
- {
- delay(40);
- Serial2.write(data1[i]);//向串口2发送信息
- }
- delay(40);
- while (Serial2.available() > 0)
- {
- comdata1 += char(Serial2.read()); //每次读一个char字符,并相加 字符串
- delay(2);
- }
- delay(20);
- if (comdata1.length() > 0)
- {
- unsigned char data5 = comdata1[3];
- unsigned char data6 = comdata1[4];
- int val7 = (data5 * 256 + data6);
- delay(20);
- delay(20);
- Serial.print(comdata1);
- // delay(20);
- // Serial.print(gonglv);
- }
- }
- void gonglvbiao(){ //数控电源功率
- for (int i = 0; i < 8; i++)
- {
- delay(2);
- Serial3.write(data2[i]);//向串口3发送信息
- }
- delay(40);
- while (Serial3.available() > 0)
- {
- comdata2 += char(Serial3.read()); //每次读一个char字符,并相加 字符串
- delay(2);
- }
- delay(20);
- if (comdata2.length() > 0)
- {
- unsigned char data5 = comdata2[3];
- unsigned char data6 = comdata2[4];
- int val7 = (data5 * 256 + data6);
- delay(20);
- // delay(20);
- // Serial.print(comdata2);
- // delay(20);
- // Serial.print(gonglv);
- }
- }
复制代码
|
-
|