Search code examples
c++arduinoesp32

convert uint_8 ascii to string


I am sending a string from RaspberryPi to ESP32 via BT.I am getting an ascii values one per line. How to convert it into a whole one String? I tried as follow but I get an error while running the method printReceivedMEssage(buffer):

invalid conversion from 'uint8_t {aka unsigned char}' to 'uint8_t* {aka unsigned char*}' [-fpermissive]

uint8_t buffer; 

void printReceivedMessage(const uint8_t* buf) {
  char string_var[100];
  size_t bufflen = sizeof(buf);

  for (int i = 0; i < bufflen; ++i) {
    Serial.println(static_cast<char>(buf[i]));
  }

  memcpy( string_var, buf, bufflen );
  string_var[bufflen] = '\0'; // 'str' is now a string
  Serial.print("string_var=");
  Serial.println(string_var);
}

void loop() 
{
  buffer = (char)SerialBT.read();  
  Serial.println(buffer); // THIS SHOWS AN ASCII VALUES ONE PER LINE
  printReceivedMessage(buffer); // ERROR
  delay(1000);
}

Solution

  • One error that should be fixed is the incorrect sizeof(). The code is getting the size of a pointer, which in C and C++ does simply that (you will get the value 4 for 32-bit pointers for example), but doesn't return the size of any "contents" being pointed to. In your case, where the buffer contains a null-terminated string, you can use strlen()

    size_t bufflen = strlen(buf);
    

    To remove the compiler error you need to pass a byte array to printReceivedMessage(). For example:

    uint8_t buffer[200];
    

    Also, you could print the buffer in one call with Serial.println(a_string), but then you need to read a whole string with SerialBT.readString().

    The byte array seems to be an unnecessary intermediary. Just read a String over BT, and print it, as in the post I linked to.

    Serial.println(SerialBT.readString());