cancel
Showing results for 
Search instead for 
Did you mean: 

FILE *stream via USART

asttekin
Associate

Hi,

I'am reading data through USART1 and USART2. I am sending the data over USART3 using printf. It works for a while but then stops.

Here is my code:

FILE *stream;
char *buf;
size_t len;
 
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
	if (huart->Instance == USART1)
	{
		uart_1_Ready	= SET;
		HAL_UART_Receive_IT (&huart1, UART_1_rxBuffer, UART_1_RX_BUFFER_SIZE);
 
		fprintf(stream, UART_1_rxBuffer);
	}
	else if (huart->Instance == USART2)
	{
		uart_2_Ready	= SET;
		HAL_UART_Receive_IT (&huart2, UART_2_rxBuffer, UART_2_RX_BUFFER_SIZE);
				
		fprintf(stream, UART_2_rxBuffer);
	}
}
void sendDataUsart3(void)
{
         if(len >= 600)
	{
		printf(buf);
		fclose(stream);
		free(buf);
		buf = (char *)realloc(buf, 600);
		stream = open_memstream(&buf, &len);
	}
}
int main(void)
{
    buf 		= (char *) malloc(600);
    stream	= open_memstream(&buf , &len);
....
}

3 REPLIES 3
Bassett.David
Associate III

Hello asttekin,

Correct me if I'm wrong, but I don't think you should free(buf) before realloc(buff...). realloc is expecting a valid pointer to allocated memory(?)

Regards,

Dave

How do you ensure the buffers are properly NUL terminated?

Any code to recover the situation if the receiver overruns or gets some framing or parity error?

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
asttekin
Associate

Actually I don't know exactly how to do it.I am using FILE stream for the first time in a project.

I manually insert the NULL after each UART data read.The UART data receiving code is as follows.Same as USART2.

if (huart->Instance == USART1)
	{
		uart_1_Ready	= SET;
		uart_1_Timeout	= 0;
		HAL_UART_Receive_IT (&huart1, UART_1_rxBuffer, UART_1_RX_BUFFER_SIZE);
 
		tempUart_1_Val	= huart->Instance->DR;
 
		if (tempUart_1_Val == '$')
		{
			uart_1_record			= 1;
			nmea_1_InputBufferIndex	= 0;
			}
		if (uart_1_record)
		{
			nmea_1_InputBuffer[nmea_1_InputBufferIndex]	= tempUart_1_Val;
			nmea_1_InputBufferIndex++;
 
			if (tempUart_1_Val == 0x0A)
			{
				nmea_1_InputBuffer[nmea_1_InputBufferIndex]	= '\0';
				navDataInput_1_ChecksumHigh		= nmea_1_InputBuffer[nmea_1_InputBufferIndex - 4];
				navDataInput_1_ChecksumLow		= nmea_1_InputBuffer[nmea_1_InputBufferIndex - 3];
				uart_1_dataReceived				= 1;
				if(workingMode == MODE1)
				{
					nmea_1_InputBufferIndex			= 0;
				}
				if (workingMode == MODE2)
				{
					fprintf(stream, nmea_1_InputBuffer);
					memset(nmea_1_InputBuffer,'\0', NMEA_BUFFER_SIZE);
				}
				uart_1_record					= 0;
			}
		}
 
	}