ESP32+RS485参考代码要点+@环境esp-idf-v5.1.2 +vscode 草稿
在环境esp-idf-v5.1.2 +vscode 中,如何在一个文件内,调用另外一个文件夹内定义的函数。
设置帧内间隔( 在传输线上,两个发送的字节之间的时间间隔,不超过3.5发送单个字节的时间。)
通过函数 esp_err_t uart_set_rx_timeout(uart_port_t uart_num, const uint8_t tout_thresh)实现此功能。
在RTOS中,主机发送查询命令后,一般可以阻塞等待从机应答。这个阻塞接收应答的函数可以由uart_read_bytes()实现。此函数用法:
int len = uart_read_bytes(uart_num, data, BUF_SIZE, PACKET_READ_TICS);
其中:#define PACKET_READ_TICS (100 / portTICK_PERIOD_MS)
/** * @brief UART set threshold timeout for TOUT feature * * @param uart_num Uart number to configure, the max port number is (UART_NUM_MAX -1). * @param tout_thresh This parameter defines timeout threshold in uart symbol periods. The maximum value of threshold is 126. * tout_thresh = 1, defines TOUT interrupt timeout equal to transmission time of one symbol (~11 bit) on current baudrate. * If the time is expired the UART_RXFIFO_TOUT_INT interrupt is triggered. If tout_thresh == 0, * the TOUT feature is disabled. * * @return * - ESP_OK Success * - ESP_ERR_INVALID_ARG Parameter error * - ESP_ERR_INVALID_STATE Driver is not installed */ esp_err_t uart_set_rx_timeout(uart_port_t uart_num, const uint8_t tout_thresh);
举例 初始化为半双工RS485工作模式
/** * @brief 初始化RS485 * @param 串口编号 * @retval 无 */ void mcu_rs485_init(uint16_t ncom) { uint16_t uart_num = 0; uart_num =ncom; uart_config_t uart_config = { .baud_rate = BAUD_RATE, .data_bits = UART_DATA_8_BITS, .parity = UART_PARITY_DISABLE, .stop_bits = UART_STOP_BITS_1, .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, .rx_flow_ctrl_thresh = 122, .source_clk = UART_SCLK_DEFAULT, }; // Set UART log level esp_log_level_set(TAG, ESP_LOG_INFO); ESP_LOGI(TAG, "Start RS485 configure UART."); // Install UART driver (we don't need an event queue here) // In this example we don't even use a buffer for sending data. ESP_ERROR_CHECK(uart_driver_install(uart_num, BUF_SIZE * 2, 0, 0, NULL, 0)); // Configure UART parameters ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config)); ESP_LOGI(TAG, "UART set pins, mode and install driver."); // Set UART pins as per KConfig settings ESP_ERROR_CHECK(uart_set_pin(uart_num, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS)); // Set RS485 half duplex mode ESP_ERROR_CHECK(uart_set_mode(uart_num, UART_MODE_RS485_HALF_DUPLEX)); // Set read timeout of UART TOUT feature 3.5 bytesTime ECHO_READ_TOUT =3 ESP_ERROR_CHECK(uart_set_rx_timeout(uart_num, ECHO_READ_TOUT)); // // Allocate buffers for UART // uint8_t* data = (uint8_t*) malloc(BUF_SIZE); ESP_LOGI(TAG, "UART %d ready.\r\n", uart_num); //echo_send(uart_num, "Start RS485 UART test.\r\n", 24); }