byte   gSeq = 0;
String gInputString = "";         
String gOutputString = "";
String gInputBuffer = "";

boolean stringComplete = false;  

void setup(){
  Serial.begin(9600);
}
void loop(){
  
  int val=analogRead(0);
  String m = "analog input:";
  m += val;
  analogWrite(3,val/4);
  sendMessage(m);
  delay(50);
}

void sendMessage(String message)
{
  gOutputString = "M" + message;
  serialSend();
}

void setData()
{
  serialSendAndLoad();  
}

void getData()
{
  serialSendAndLoad();    
}

void serialSendAndLoad()
{
  serialSend();
  
  unsigned long timeout = millis() + 1000;
  gInputString = "";
  int isDataRecieved = false;
  while(!isDataRecieved && millis() < timeout)
  {
    while (Serial.available() > 0)
    {
      // get the new byte:
      char inChar = (char)Serial.read(); 
      // add it to the inputString:
      if (inChar != '\n' && inChar != '\r')
      {
        gInputBuffer += inChar;
      }
      // if the incoming character is a newline, set a flag
      // so the main loop can do something about it:
      if (inChar == '\n') 
      {
        //check input data
        if (gInputBuffer.length() >= 2)
        {
          char rsecChars[3];
          gInputBuffer.toCharArray(rsecChars,2);
          rsecChars[2] = 0;
          if (int(rsecChars) == gSeq)
          {
            gInputString = gInputBuffer;
            isDataRecieved = true;
          }
        }
        gInputBuffer = "";
      }
    }
  }
}

void serialSend()
{
  gSeq ++;
  if (gSeq > 99)
  {
    gSeq = 1;
  }
  if (gSeq < 10)
  {
    Serial.print("0");
  }
  Serial.print(gSeq, DEC);
  Serial.println(gOutputString);
}
