Skip to content

Instantly share code, notes, and snippets.

@heltonmarx
Last active May 9, 2023 23:25
Show Gist options
  • Save heltonmarx/4fc2b4294ab77da5bc6364124d18c2c9 to your computer and use it in GitHub Desktop.
Save heltonmarx/4fc2b4294ab77da5bc6364124d18c2c9 to your computer and use it in GitHub Desktop.
rs485 forcing set rst and dtr
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include "esp_mac.h"
#include "esp_log.h"
#include "config.h"
#include "rs485.h"
#define RS485_BAUDRATE (115200)
#define RS485_UART_PORT (UART_NUM_2)
#define RS485_UART_TXD (GPIO_NUM_16) // DI
#define RS485_UART_RXD (GPIO_NUM_17) // RO
#define RS485_UART_RTS (GPIO_NUM_13) // RE
#define RS485_UART_CTS (UART_PIN_NO_CHANGE)
#define RS485_BUF_SIZE 125
static const char *TAG = "rs485";
esp_err_t Rs485::setup()
{
uart_config_t uart_config = {
.baud_rate = RS485_BAUDRATE,
.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_APB,
};
ESP_ERROR_CHECK(uart_driver_install(RS485_UART_PORT, RS485_BUF_SIZE * 2, 0, 0, NULL, 0));
ESP_ERROR_CHECK(uart_param_config(RS485_UART_PORT, &uart_config));
ESP_ERROR_CHECK(uart_set_pin(RS485_UART_PORT, RS485_UART_TXD, RS485_UART_RXD, RS485_UART_RTS, RS485_UART_CTS));
ESP_ERROR_CHECK(uart_set_mode(RS485_UART_PORT, UART_MODE_RS485_HALF_DUPLEX));
return ESP_OK;
}
esp_err_t Rs485::reset()
{
esp_err_t err = uart_driver_delete(RS485_UART_PORT);
if (err != ESP_OK) {
return err;
}
return this->setup();
}
bool Rs485::send(const uint8_t * buffer, size_t size)
{
bool response = false;
uart_set_rts(RS485_UART_PORT, 1);
size_t ret = uart_write_bytes(RS485_UART_PORT, buffer, size);
if (ret == size) {
uart_wait_tx_done(RS485_UART_PORT, (50 / portTICK_PERIOD_MS));
}
uart_set_rts(RS485_UART_PORT, 0);
return ret != size ? false : true;
}
int16_t Rs485::read(uint8_t *buffer, size_t size)
{
uart_set_dtr(RS485_UART_PORT, 1);
register int16_t n = uart_read_bytes(RS485_UART_PORT, buffer, size, (10 / portTICK_PERIOD_MS));
if (n != 0 && n != -1) {
uart_flush_input(RS485_UART_PORT);
}
uart_set_dtr(RS485_UART_PORT, 0);
return n == -1 ? 0 : n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment