Search code examples
pythoncuart

How to read just the first two numbers ? python +UART


I want to make communication between my laptop and my module. For that I create a python file which will send some packets to the UART, which it must read them. I have a python script (laptop) that creates a packet:

SOF= '24'
SEND_PLAINTEXT= '72'
SEND_KEY  ='73'
RECEIVE_CIPHERTEXT='74'
SIZE_OF_FRAME= '10'
for a in range (0,1):

   line_array=lines[a]
   plaintxt_16b=line_array[0:32]
   plaintext= '24'+'72'+'32'+plaintxt_16b
   ser.write (plaintext.encode())

The final packet is 247232ccddeeff8899aabb4455667700112233

UART read the packet by using these lines of code in c:

uint8_t rx_buffer[38];
int rx_length = dev_uart_ptr->uart_read(rx_buffer, 38);

if (rx_length <38)
{
    printf( rx_buffer);
}

I need to read just the two first numbers in order to test if it is the start of the frame or not. Thus, I have changed my code:

uint8_t rx_buffer[2];
int rx_length = dev_uart_ptr->uart_read(rx_buffer,2);

if (rx_length <2)
{
    printf( rx_buffer);
}

The problem is that numbers which are displayed are 33, despite I want to read 24, I would be very grateful if you could help me.


Solution

  • This line plaintext= '24'+'72'+'32'+plaintxt_16b seems to be executed from right to left. So the first thing in the buffer will be plaintxt_16b, then the rest.

    The order of the bytes are also from right to left in the packet 247232ccddeeff8899aabb4455667700112233. So the first byte (index of 0) is 0x33

    18.| 17.| 16.| 15.| 14.| 13.| 12.| 11.| 10.| 9. | 8. | 7. | 6. | 5. | 4. | 3. | 2. | 1. | 0.
    ---------------------------------------------------------------------------------------------
    24 | 72 | 32 | cc | dd | ee | ff | 88 | 99 | aa | bb | 44 | 55 | 66 | 77 | 00 | 11 | 22 | 33
    

    Try the following:

    plaintext= plaintxt_16b + '32' + '72' + '24'
    

    and leave the UART code the same.