Convert String to unsigned Char [16];

How to convert a String var to unsigned char var[16]; the variables I will use to decrypt the value.
The code is :
void komunikasiSerial(void) {
if (Serial2.available() > 0) {
String baca = Serial2.readString();
char dataChar[16];
baca.toCharArray(dataChar, sizeof(baca));
unsigned char tes = (unsigned char)dataChar
Serial.println(tes);
}
}

-- Error --
if (Serial2.available() > 0) {
^~
exit status 1
cast from 'char*' to 'unsigned char' loses precision [-fpermissive]

You're missing a semi-colon at unsigned char tes = (unsigned char)dataChar. After that your function compiles (with warnings). If it does not compile, post your complete sketch; please use code tags when posting code (and error messages) as described in How to get the best out of this forum.

dataChar is an array, test is a character, hence the cast warning. This will work

unsigned char *tes = (unsigned char*)dataChar;

But you can't print tes that way; use a for-loop to print all elements.

wait i will try it

The 2nd parameter of toCharArray() is the size of the target array, not the source String.

Try this...

String str = "Hello World!";

char array[16];


void setup()
{
  Serial.begin(115200);
  
  str.toCharArray(array, sizeof(array));
  
  Serial.println(array);
}

void loop()
{}

No idea what you're trying to do with this statement...

You don't need it to convert to a char array.

why not read the string directly into char array

possible output

charlie
 63 68 61 72 6C 69 65
char buf [80];

void
loop (void)
{
    if (Serial.available ())  {
        int n   = Serial.readBytesUntil ('\n', buf, sizeof(buf)-1);
        buf [n] = '\0';

        Serial.println (buf);

        for (int i = 0; i < n; i++)  {
            Serial.print (" ");
            Serial.print (buf [i], HEX);
        }
        Serial.println ();
    }
}

void
setup (void)
{
    Serial.begin (9600);
}
1 Like

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