Search code examples
cstm32

Convert int to High byte and low byte to be sent via usart using Modbus RTU


I am working on a program to be run on a STM32 microcontroller. The point is that I need to send the Modbus RTU telegram to control a device.

This would be the structure of the telegram:

uint8_t pBuffer [8] = { Address, Function, 
                        Register High byte, Register Low byte, 
                        Value High byte, Value Low byte, 
                        CRC High byte, CRC Low Byte};

Example:

uint8_t pBuffer [8] = {0x02,0x06,0x0C, 0x21,0x01,0xC7,0x9A, 0xA1};

And I send it via uart using:

HAL_UART_Transmit(&huart2, pBuffer, 8, 0xFFFF);

What I need at the moment to convert an int variable:

int freq = 455;

To the high byte and low byte:

high_byte = 0x01;
low_byte = 0xC7;

Which correspond to Value High byte and Value Low byte from the telegram

I tried to use sprintf:

int freq = 455;
char freq_hex[4];
sprintf(freq_hex, "%x", freq);

Solution

  • sprintf generates string output, that is not what you need here.

    Simply:

    uint8_t high_byte = (freq >> 8) & 0xff ;
    uint8_t low_byte = freq & 0xff ;