You seem to have the assumption, that the string "QUICK" is send as one package of characters, because you send it with one keypress from the Serial Monitor. But Serial (UART) is a "serial" protocol, meaning, that each byte (aka character for ASCII encoding) is send sequentially.
At 9600 baud each byte will take about 1ms to transmit. Also: small random delays can be introduced by the PC or in the USB communication (if you are communication through a USB to Serial chip, like when you connect the Uno via USB).
Your code runs faster than the data arrives at the Unos microcontroller. The first if
clause is entered as soon, as there is one byte in your Serial buffer. Then you start reading the data from the buffer, but at that time no further bytes did arrive. So the loop is exited after one iteration.
If you want to process the Serial data line by line, you should send a line ending from the Serial Monitor (or whichever program you are using) via the Line ending option. The common way is to use \n
aka the newline character as line ending. Then in your code you should read the data until you receive the newline character.
That can be done in multiple ways. One way is to read each arriving character into your own buffer, which is big enough to hold the maximum number of characters, that can occur in your messages. Then, when receiving the newline character you can process the data in the buffer. A variables holds the current position in the buffer:
unsigned int pos = 0;
char buffer[20] = ""; // enough space for 19 characters + the null character for terminating the string correctly
void setup(){
Serial.begin(9600);
}
void loop(){
if(Serial.available()){
char c = Serial.read();
if(c != '\n'){
buffer[pos] = c; // Adding the received character to the buffer
if(pos < sizeof(buffer) - 1){
// incrementing the position variable to point to the next position in the buffer
// but only, if there is enough space in the buffer left
// otherwise this code will overwrite the last character
pos++;
}
} else {
buffer[pos] = 0; // Terminating the string correctly
// Process the message here
Serial.println(buffer);
// Reset buffer by setting the position back to zero
pos = 0;
}
}
}
Note: This code needs your loop()
function to iterate fast enough, so that you won't miss more data, than the internal buffer of Serial can hold (I think 32 characters). So you probably don't want to use long delays (which is nearly always a bad idea anyways, see non-blocking coding and the millis()
function).