cancel
Showing results for 
Search instead for 
Did you mean: 

HAL_UART Transmit/Receive dont work when not using a fixed size as parameter?

BMo.1
Associate II

in my program is receive first data that tells me what's the size of the payload i am getting next through UART ,When i use that variable as parameter in the UART functions it doesnt work ,however when i hard code a value say HAL_Uart_Receive(&huart1,buffer,5,...) it does indeed work.

Here is my code

#define Max_Buffer_Size		16384UL
uint8_t buffer[Max_Buffer_Size];
 
HAL_UART_Receive(&huart1,buffer,1,HAL_MAX_DELAY);
int payload_length =buffer[0];
HAL_UART_Receive(&huart1,buffer,payload_length,HAL_MAX_DELAY);

as i said if replace line 6 with this is it works :

HAL_UART_Receive(&huart1,buffer,5,HAL_MAX_DELAY);

Thank you for your help.

24 REPLIES 24

Or just drop Cube/HAL and write your own blocking UART receiver. It's literally 5 lines of code.

JW

So, try to blink LED when buffer[0] is equal 5. You probably dont receive what you expected.

BMo.1
Associate II

So I tried to implement my own Receive function like this :

void Serial_Receive(uint8_t* buffer ,uint8_t size){
	int i=0 ;
	while(i < size ){
		while (!(USART1->SR & USART_SR_RXNE));
		buffer[i]=USART1->DR;
		i++;	
	}
}

When i call it with payload_length as a parameter it blocks exactly like the HAL fucntion

		Serial_Receive(buffer2,payload_length);

A call with a hard coded value proceeds smoothly and the program continues its execution.

Serial_Receive(buffer2,5);

The problem probably lies with payload_length variable and I don't see why honestly.

S.Ma
Principal

I would use DMA in polling modr. Use a cyclic mode over 16 bytes buffer, that is simpler.... and is non blocking...

What exactly does the transmitter transmit? Is it

05 xx xx xx xx

or

05 xx xx xx xx xx

?

JW

BMo.1
Associate II

Okay will try it.

I just want to understand what's the problem in this case tbh.

BMo.1
Associate II

first he transmits 5 and then transmits a 5byte string lets say "Hello".

Okay, and what is the result of something like

if (payload_length == 5)

LED_ON();

else

LED_OFF();

?

You should consider using a working environment which enables the nowadays usual debugging facilities (breakpoints, single-stepping, observing memories/variables etc.)

JW

TDK
Guru

Probably payload_length isn't what you think it is. What other explanation could there be? The variable is passed by value. The function itself has no idea if you passed a literal or a variable.

If you feel a post has answered your question, please click "Accept as Solution".

Led doesn't turn on payload_length is the problem.Also i test buffer[0] instead of payload_length,LED doesn't turn on.

I am not getting the data i expect i guess ?

Also can't really debug because i use those chinese st-link clone to flash and then and FTDI chip to test the uart communication.Can't have both at the same time.