Find numeric values between 2 letters

Hi everyone, I'm trying to find sensor measurements in a string that I sent via serial communication. the format of the string is as follows: @"temperature"A"humidity"B/n

I have been trying to use the indexOf function but I don't know how to apply it, I don't know if someone could help me, I would really appreciate it.

You might try Serial.parseFloat() or parseInt().

Your topic was MOVED to its current forum category as it is more suitable than the original

1 Like

do you really have double quotes or is the format something like @40.3A77B\n ?
do you have a string (cString) or a String (String class instance)

an example which assumes the format is right:

String message = "@40.3A77B\n";

void setup() {
  Serial.begin(115200);

  double t = message.substring(message.indexOf('@') + 1).toFloat();
  int h = message.substring(message.indexOf('A') + 1).toInt();
  Serial.print("T° = "); Serial.println(t, 3);
  Serial.print("H% = "); Serial.println(h);
}

void loop() {}
1 Like

what @J-M-L said but using c-strings instead :wink:

char message[] = "@40.3A77B\n";

void setup() {
  Serial.begin(115200);

  float t = atof(strchr(message, '@')+1);
  int h = atoi(strchr(message, 'A')+1);
  Serial.print("T° = "); Serial.println(t, 3);
  Serial.print("H% = "); Serial.println(h);
}

void loop() {}

hope that helps...

1 Like

no, it does not have quotes, it is only to indicate that there is a numerical value, and if it helped me, it served me well. Thank you very much, and how fast they respond in these forums, thank you very much

If you help me, it's perfect, thank you very much

I would have written it this way :slight_smile:

char message[] = "@40.3A77B\n";

void setup() {
  double t;
  int h;
  bool error = false;

  Serial.begin(115200);

  const char *  ptr1 = strchr(message, '@');
  const char *  ptr2 = strchr(message, 'A');

  if ((ptr1 != nullptr) && (ptr2 != nullptr)) {
    char * endPtr;
    t = strtod(ptr1 + 1, &endPtr);
    error |= (endPtr != ptr2);
    h = strtol(ptr2 + 1, &endPtr, 10);
    error |= (strcmp(endPtr, "B\n") != 0);
  } else error = true;

  if (error) {
    Serial.println(F("Wrong input"));
  } else {
    Serial.print("T° = "); Serial.println(t, 3);
    Serial.print("H% = "); Serial.println(h);
  }
}

void loop() {}

the functions strtod() and strtol() provide a better way to ensure you did read something correctly formatted. atof() and atoi() will just return 0 if they could not read a correct number and so can't differentiate without extra code if that 0 is the real value or if it's an error

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.