cancel
Showing results for 
Search instead for 
Did you mean: 

Read a character from the UART

FLamb.2
Associate II

I want to read one character from the UAR and display it.

I am using CoolTerm.

But nothing is displayed.

What's wrong with my getchar function?

Or is the code in the while loop wrong?

char getchar() {
  char data[1];
  HAL_UART_Receive(&huart2, (void*)data, 1, HAL_MAX_DELAY);
  return data[0];
}
 
while (1)
  {
    HAL_UART_Transmit(&huart2,(uint8_t *) "Test",4,HAL_MAX_DELAY);
    HAL_UART_Transmit(&huart2,(uint8_t *) getchar(),1,HAL_MAX_DELAY);
  }

4 REPLIES 4

Hello

getchar returns char type and in second transmit function is interpeted as pointer to char (uint8_t*)

To echo back a charater came from coolterm use this code

uint8_t data;

while (1)

{

HAL_UART_Receive(&huart2, &data, 1, HAL_MAX_DELAY);

HAL_UART_Transmit(&huart2, &data,1,100);// dont wait too much for transmitting

}

FLamb.2
Associate II

No idea whether the HAL_UART_Receive is blocking or not.

I don't know what the blocking means either.

So, my current code looks like this, and it still doesn't work.

See attachement.

void getchar() {
  uint8_t data;
  HAL_UART_Receive(&huart2, &data, 1, 100);
  HAL_UART_Transmit(&huart2, &data,1,100);
}
 
  while (1)
  {
    uprints("Test\n");
    getchar();
  }

ocourse will not work if wait only 100msec to get a character from your keyboard. Increase the read timeout to max

Blocking is the function(this purpose) that doesn't return before timeout or finish the transactions

0693W000007CXTcQAO.jpg