UART read until CR \n

paddynoob
Posts: 9
Joined: Tue Sep 24, 2019 10:08 am

UART read until CR \n

Postby paddynoob » Wed Feb 03, 2021 2:10 pm

Hello,

I use ESP32 as a bridge between Arduino based Robot and ROS2 on PC.
Arduino provides sensor data of robot by sending data via UART to ESP32

ESP32 needs to read each single line and process/translate this message for ROS2.

Currently, I read UART like this

Code: Select all

	uart_config_t uart_config = {
		.baud_rate = UART_BAUD_RATE,
		.data_bits = UART_DATA_8_BITS,
		.parity = UART_PARITY_DISABLE,
		.stop_bits = UART_STOP_BITS_1,
		.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
		.source_clk = UART_SCLK_APB,
	};
	int intr_alloc_flags = 0;

#if CONFIG_UART_ISR_IN_IRAM
	intr_alloc_flags = ESP_INTR_FLAG_IRAM;
#endif

	ESP_ERROR_CHECK(uart_driver_install(UART_PORT_NUM, BUF_SIZE , 0, 0, NULL, intr_alloc_flags));
	ESP_ERROR_CHECK(uart_param_config(UART_PORT_NUM, &uart_config));
	ESP_ERROR_CHECK(uart_set_pin(UART_PORT_NUM, UART_TXD, UART_RXD, UART_RTS, UART_CTS));

	// Configure a temporary buffer for the incoming data
	uint8_t *data = (uint8_t *)malloc(BUF_SIZE);

	while (1)
	{
		// Read data from the UART
		int len = uart_read_bytes(UART_PORT_NUM, data, BUF_SIZE, 20 / portTICK_RATE_MS);
		// Write data back to the UART
		if (len > 0)
		{
			data[len] = 0;
			ESP_LOGI(TAG, "Data received: %i", len);
			xQueueSend(uartQueue, data, (TickType_t)0);
		}
	}
with BUF_SIZE of 256

In general it works, however I receive multiple messages with one uart_read_bytes

Code: Select all

$EV|1|25
$RS|0|1|1|1|1|1|0|1|1                                                                                                                          
$RS|0|8|0.00|0.00|0.00|0.00|0.00|0.00|0|0|0|0.00|0.00|0                                                                                        
$RS|0|15|11|0|0|0                                                                                                                              
$RS|0|19|-132.52|7.38|-2.51|-0.11|-0.29|0.05|-0.12|-0.04|0.99|-32304.00|-32145.00|31016.00                                                     
$RS|0|20|0|0   
Each message starts with $ and type identifier, $RS means sensor value, $EV means raised event of robot.

How can I read each sentence individually? I don't want to send a fixed length as some messages are much shorter than others.

Is there a simple way to read until '\n'?
Sure I can read individual chars until '\n' occurs but I wonder if there is some pre-build solution for this.

Greetings

becorey
Posts: 92
Joined: Sat Mar 28, 2020 4:18 pm

Re: UART read until CR \n

Postby becorey » Tue Feb 16, 2021 5:47 am

See this post for a similar request:
viewtopic.php?t=15342

Who is online

Users browsing this forum: No registered users and 31 guests