Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Arduino.h>
- #include <stdlib.h>
- #include <stdint.h>
- #include <stddef.h>
- #include <driver/uart.h>
- #define ECHO_UART_PORT UART_NUM_2
- #define ECHO_TEST_TXD (23)
- #define ECHO_TEST_RXD (22)
- #define ECHO_TEST_RTS (18)
- #define ECHO_TEST_CTS UART_PIN_NO_CHANGE
- #define BUF_SIZE (127)
- #define BAUD_RATE (115200)
- #define PACKET_READ_TICS (100 / portTICK_RATE_MS)
- static const char *TAG = "RS485_ECHO_APP";
- void setup() {
- Serial.begin(115200); //uses UART_NUM_0
- //configure UART_NUM_2 for RS485
- const uart_port_t uart_num = ECHO_UART_PORT;
- 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,
- };
- Serial.println("Start RS485 application test and configure UART.");
- // Configure UART parameters
- uart_param_config(uart_num, &uart_config);
- Serial.println("UART set pins, mode and install driver.");
- // Set UART1 pins(TX: IO23, RX: I022, RTS: IO18, CTS: IO19)
- uart_set_pin(uart_num, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS);
- // Install UART driver (we don't need an event queue here)
- // In this example we don't even use a buffer for sending data.
- uart_driver_install(uart_num, BUF_SIZE * 2, 0, 0, NULL, 0);
- // Set RS485 half duplex mode
- uart_set_mode(uart_num, UART_MODE_RS485_HALF_DUPLEX);
- ESP_LOGI(TAG, "UART start recieve loop.\r\n");
- uart_write_bytes(uart_num, "Start RS485 UART test.\r\n", 24);
- }
- void loop() {
- const uart_port_t uart_num = ECHO_UART_PORT;
- // Allocate buffers for UART
- uint8_t* data = (uint8_t*) malloc(BUF_SIZE);
- //Read data from UART
- int len = uart_read_bytes(uart_num, data, BUF_SIZE, PACKET_READ_TICS);
- //Write data back to UART
- if (len > 0) {
- uart_write_bytes(uart_num, "\r\n", 2);
- char prefix[] = "RS485 Received: [";
- uart_write_bytes(uart_num, prefix, (sizeof(prefix) - 1));
- Serial.println("Received "+ String(len) + " bytes:");
- printf("[ ");
- for (int i = 0; i < len; i++) {
- printf("0x%.2X ", (uint8_t)data[i]);
- uart_write_bytes(uart_num, (const char*)&data[i], 1);
- // Add a Newline character if you get a return charater from paste (Paste tests multibyte receipt/buffer)
- if (data[i] == '\r') {
- uart_write_bytes(uart_num, "\n", 1);
- }
- }
- printf("] \n");
- uart_write_bytes(uart_num, "]\r\n", 3);
- } else {
- // Echo a "." to show we are alive while we wait for input
- uart_write_bytes(uart_num, ".", 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement