Hello, Im a beginner in programming, trying to read data into an array. Im trying to build a communication between 2 arduinos via Tx/Rx. What im trying to do is send command from serial, read it into an array UI[7] and then try and check what command is received.
Commands:
#ACT1$ >>activate LED1
#ACT2$ >>activate LED2
#DAT1$ >>de-activate LED1
#DAT2$ >>de-activate LED2
All works well until #DAT2# command is send after existing command of #ACT1$
This turns off both LED's instead of only LED2.
After searching for long i inserted delay(5000) and found the serial is changing as below:
Serial Output
15:03:50.801 -> #ACT1$ <<previous command in UI array #ACT1$
15:03:50.801 -> #ACT1$
15:03:50.801 -> #ACT1$
15:03:50.801 -> #DCT1$ <<entered new command #DAT2$ but output changes in steps
first to #DCT1$ then #DAT1$ then#DAT2$
15:03:50.801 -> #DAT2$
15:03:55.756 -> #DAT2$
15:04:00.804 -> #DAT2$
How do i hold the program in while loop until all the data is received in array UI[7]? How can the program escape the while loop and execute the Serial.print(char(UI[0])); Serial.print(char(UI[1])); ... block
Any help is appreciated. Thanks
Code below:
int idx = 0;
char UI[7];
int act1_f = 0, act2_f = 0, password_f = 0;
void setup() {
Serial.begin(9600);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
digitalWrite(12, LOW);
digitalWrite(13, LOW);
}
void loop() {
while (Serial.available() > 0) {
UI[idx] = Serial.read();
idx = idx + 1;
if (idx == 7) {
idx = 0;
}
}
Serial.print(char(UI[0]));
Serial.print(char(UI[1]));
Serial.print(char(UI[2]));
Serial.print(char(UI[3]));
Serial.print(char(UI[4]));
Serial.print(char(UI[5]));
Serial.print(char(UI[6]));
if (UI[0] == '#' && UI[5] == '
) {
if (UI[1] == 'A' && UI[2] == 'C' && UI[3] == 'T' &&
UI[4] == '1') {
act1_f = 1;
//Serial.println("act1");
}
if (UI[1] == 'A' && UI[2] == 'C' && UI[3] == 'T' &&
UI[4] == '2') {
act2_f = 1;
//Serial.println("act2");
}
if (UI[1] == 'D' && UI[2] == 'A' && UI[3] == 'T' &&
UI[4] == '1') {
act1_f = 0;
//Serial.println("Dact1");
delay(5000);
}
if (UI[1] == 'D' && UI[2] == 'A' && UI[3] == 'T' &&
UI[4] == '2') {
act2_f = 0;
//Serial.println("Dact2");
delay(5000);
}
if (UI[1] == 'P' && UI[2] == '1' && UI[3] == '5' &&
UI[4] == '3') {
password_f == 1;
Serial.println("Pass");
}
}
switch (act1_f) {
case 0:
digitalWrite(12, LOW);
// Serial.println("LED1 OFF");
break;
case 1:
digitalWrite(12, HIGH);
// Serial.println("LED1 ON");
break;
}
switch (act2_f) {
case 0:
digitalWrite(13, LOW);
// Serial.println("LED2 OFF");
break;
case 1:
digitalWrite(13, HIGH);
// Serial.println("LED2 ON");
break;
}
}