ultrasonic bananna
ultrasonic bananna

Reputation: 193

Do I need to convert ascii to uint8_t to write and display over uart (putty)

I've a sensor connected on UART to an mcu. The sensor outputs ascii characters. Below are my functions to read from the uart (the sensor) and write from the uart (to my computer over putty).

My question is, do I need to convert the ascii characters to be of type uint8_t to write over the uart as that is what putchar() requires? There is noting being displayed in putty.

Upvotes: 1

Views: 1938

Answers (1)

rodrigo
rodrigo

Reputation: 98348

The type uint8_t is a typedef of unsigned char, and it is required to have the same layout as a signed char or a plain char.

So, you can freely cast between uint8_t and char or between uint8_t* and char*, and everything will just work.

However, you cannot cast between int* and uint8_t*, because the base types will be of different size.

My advice would be to write something like:

void putcchar(uint8_t c) {
  ti_uart_write_buffer(TI_UART_0, &c, 1);
}

And then call it directly:

int l = getch();
putcchar(l);

Note that getch() returns an int instead of a char just to be able to return EOF, so the cast to char will be safe unless it is EOF. You may want to add:

int l = getch();
if (l == EOF) break;
putcchar(l);

This is true as long as you consider your char/uint8_t values as binary bytes or ASCII characters. If you happen to have a non ASCII characters (e.g. 'é') then you'd need to consider the character encoding.

PS: I'm assuming you are using a normal architecture for your program, that is the byte is 8 bits long and the character encoding is ASCII based. Since you are using Putty, you are probably on MS-Windows, so I'm pretty safe here.

Upvotes: 1

Related Questions