unexpected itoa() behavior

I am working with serial data coming from a sensor, the byte values I receive were puzzling to me as they would not print as characters which I know they are. Going back a couple steps I simply tried to convert an int to a character and print it but was unsuccessful. If you look at my code snippet, I define a character array "mystr" (I made it too large for a single int intentionally to make sure that mem allocation wasn't the problem) and an int "x". I then iterate from 32 to 49, expecting to get space, exclamation, quote, hash, dollar, etc. but have found no joy.

Using the code snippet below, the output is:

32 32 32 32 20 40 100000

Any thoughts on what I am doing incorrectly with itoa()? Thanks! Phil

char mystr[12];
int x;

for(x=32; x<50; x++){

(itoa(x, mystr, 10));

    Serial.write(mystr);
    Serial.print(" ");
    Serial.print(mystr);
    Serial.print(" ");  
  
    // print it out in many formats:
    Serial.print(x);       // print as an ASCII-encoded decimal - same as "DEC"
    Serial.print("\t");    // prints a tab

    Serial.print(x, DEC);  // print as an ASCII-encoded decimal
    Serial.print("\t");    // prints a tab

    Serial.print(x, HEX);  // print as an ASCII-encoded hexadecimal
    Serial.print("\t");    // prints a tab

    Serial.print(x, OCT);  // print as an ASCII-encoded octal
    Serial.print("\t");    // prints a tab

    Serial.println(x, BIN);  // print as an ASCII-encoded binary
}

Try replacing this:

    Serial.write(mystr);

with this:

    Serial.write(x);

Pete

Perfect! I'm not clear why that works, could you please explain?

33 33 ! 33 33 21 41 33 100001

Any thoughts on what I am doing incorrectly with itoa()?

Well, for one thing,

(itoa(x, mystr, 10));

You are wrapping it in unnecessary parentheses.

For another, you are printing a bunch of stuff, with no way to identify what is supposed to be being printed.

For instance,

Serial.print("myStr from write: [");
Serial.write(myStr);
Serial.println("]");

would be far better for understanding what the methods you are using are doing.

Finally, I fail to see what the problem is, if that data represents only one iteration of the loop. You convert the value 32 to a string, and then write that string, print that string, and print the value twice as a decimal value, once as a hex value, once as an octal value, and once as a binary value. The output is exactly what I would expect for the first iteration of the loop.

Nowhere have you printed x as a char.

Serial.print(x) prints the decimal value of the variable and itoa(x) converts the variable to a decimal string. Either way, you end up with the decimal representation of the integer. What you need is to print the integer as a single character and that is what Serial.write(x) does.

Pete