I have a script reading the serial monitor and looking for an "OK" response. I am able to capture the OK response in a variable named message and print it to the serial monitor, but when I attempt to use the message variable in an if statement it is not performing as expected. When the variable message = OK the statement below is still giving a false. Does anyone know where the issue might be?
if (strcmp (message,"OK") == 0) {
Serial.println("true");
}
else {
Serial.println("false");
}
The complete code:
//#include <HardwareSerial.h>
const unsigned int MAX_MESSAGE_LENGTH = 12;
void setup() {
Serial2.begin(115200,SERIAL_8N1); //open modem serial port
Serial.println("serial ports are open");
}
void loop() {
Serial2.write("AT\r\n");
while (Serial2.available() > 0){
//Create a place to hold the incoming message
static char message[MAX_MESSAGE_LENGTH];
static unsigned int message_pos = 0;
//Read the next available byte in the serial receive buffer
char inByte = Serial2.read();
//Message coming in (check not terminating character) and guard for over message size
if ( inByte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1) )
{
//Add the incoming byte to our message
message[message_pos] = inByte;
message_pos++;
}
//Full message received...
else
{
//Add null character to string
message[message_pos] = '\0';
//Print the message (or do other things)
Serial.println("loop");
delay(100);
Serial.println(message);
//Reset for the next message
message_pos = 0;
if (strcmp (message,"OK") == 0) {
Serial.println("true");
}
else {
Serial.println("false");
}
}
}
delay(5000);
}
Serial monitor looks like this:
22:11:51.970 -> serial ports are open
22:12:16.984 -> loop
22:12:17.078 -> AT
22:12:17.078 -> false
22:12:17.078 -> loop
22:12:17.171 -> OK
22:12:17.171 -> false
22:12:17.171 -> loop
22:12:17.266 -> AT
22:12:17.266 -> false
22:12:17.266 -> loop
22:12:17.360 -> OK
22:12:17.360 -> false
The received response is "OK\r\n"
, so the actual message is "OK\r"
. It helps for debugging if you temporarily print each received character.
To ignore the echo of the command, insert another strcmp()
for it and react accordingly, for example do nothing.