Parsing serial data doesn't end loop

I'm having another problem with the 3G libellous shield.

I'm parsing incoming serial data and want it to stop when the serial reads okay - this works for all my other scripts - but for some reason its never printing "FINISH" after the serial read while loop.

Here's the code.

int led = 13;
int onModulePin = 2;        // the pin to switch on the module (without press on button) 

int timesToSend = 1;        // Numbers of SMS to send
int count = 0;

int n_sms,x,sms_start;
char data[256];

void switchModule(){
    digitalWrite(onModulePin,HIGH);
    delay(2000);
    digitalWrite(onModulePin,LOW);
}

void setup(){

    Serial.begin(115200);                // UART baud rate
    delay(2000);
    pinMode(led, OUTPUT);
    pinMode(onModulePin, OUTPUT);
    switchModule();                    // switches the module ON

     Serial.println("SWITCHING ON");

    for (int i=0;i< 5;i++){

        delay(5000);
          Serial.println(5-i);
    } 

    Serial.println("AT+CMGF=1");         // sets the SMS mode to text
    delay(100);
}

void loop(){

        Serial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");    //selects SIM memory
        Serial.flush();
         while(Serial.read()!='K'); 


        Serial.println("  SMS stored in SIM memory. Showing last SMS:");    
        // shows the total number of SMS and the last SMS

        Serial.println("AT+CMGR=1");    //Reads the last SMS 
        Serial.flush();
   
    do{
        while(Serial.available()==0);
        data[x]=Serial.read();  
        Serial.print(data[x]);
        x++;  
    }while(!(data[x]=='K'&& data[x-1]=='O'));
    

     Serial.println("FINISH");    
 

}

I know its outputting the correct info to the serial as I'm writing data[x] to see the output. It looks like this:

SWITCHING ON
5
4
3
2
1
AT+CMGF=1
AT+CPMS="SM","SM","SM"
  SMS stored in SIM memory. Showing last SMS:
AT+CMGR=1

AT+CMGR=1

+CMGR: "REC READ","8611110097102111110101","","12/03/07,18:04:55+00"
ointz towards something bigger. vodafone.co.uk/rewardz Code expires 06/04/12 Terms apply

OK

Also the loop does stop - its not continuing - so I'm just a bit perplexed as to why FINISH isn't printed to serial?

Also not sure why AT+CMGR=1 is printed twice.

You're comparing the contents of your array after incrementing x.

So, your data[x-1] will have "K", and data[x] will have ... um... who knows? It's not been assigned yet. data[x-2] will have "O".

Ah perfect - it works.

Thanks for sorting this out as well. You've saved me a lot of time and head scratching today!!! :slight_smile: