Home > Net >  STM32f sending uint16_t via uart
STM32f sending uint16_t via uart

Time:05-18

im trying to send uint16_t data with this code

uint16_t ADCValue;
uint8_t lowerMessage;
uint8_t upperMessage;
uint8_t message[2];

while (1)
{
      ADCValue = 2375;
      lowerMessage = (uint8_t)ADCValue;
      upperMessage = (uint8_t)(ADCValue >> 8);
      message[0]= lowerMessage;
      message[1]= upperMessage;
      HAL_UART_Transmit(&huart1,message, 8, 1000);
      //HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_9);
      HAL_Delay(2000);  
}

i split the 16 bit integer to 8 bit integers to send. But when i try the send this i recieve this -> Received Data. What should i do to send this data?

CodePudding user response:

In the call to HAL_UART_Transmit you pass 8 as the size. That's the size in bytes you want to send. And your array only have two bytes (i.e. sizeof message is equal to 2).

And on the receiving size, you should of course read two bytes. And treat them as raw bytes without any specific meaning. You should definitely not try to print it as a string, because it isn't. Instead you should take the individual bytes of the array and to the reverse of what you're doing in the sender program, to reconstruct the original uint16_t value.

CodePudding user response:

while (1)
{
      ADCValue = ReadADC();
      /* .... */
      HAL_UART_Transmit(&huart1,(uint8_t *)&ADCValue, sizeof(ADCValue), 1000);
      /* .... */
}

On the receiver side (assuming the same endianness - most systems use it nowadays)

HAL_UART_Receive(&huart1,(uint8_t *)&ADCValue, sizeof(ADCValue), 1000);

HAL library is written quite a bad way (instead of void * they expect uint8_t *) and the cast is to silence the warning. A believe that the 'message' magic you did was to avoid this warning.

Also check the return value for errors.

  • Related