diff --git a/esphome/components/uart/uart.h b/esphome/components/uart/uart.h index 1dc1e18412..8ac00658f4 100644 --- a/esphome/components/uart/uart.h +++ b/esphome/components/uart/uart.h @@ -118,6 +118,11 @@ class UARTComponent : public Component, public Stream { uint8_t stop_bits_; uint8_t data_bits_; UARTParityOptions parity_; + + private: +#ifdef ARDUINO_ARCH_ESP8266 + static bool serial0InUse; +#endif }; #ifdef ARDUINO_ARCH_ESP32 diff --git a/esphome/components/uart/uart_esp8266.cpp b/esphome/components/uart/uart_esp8266.cpp index c45f48644c..5cb625f2ff 100644 --- a/esphome/components/uart/uart_esp8266.cpp +++ b/esphome/components/uart/uart_esp8266.cpp @@ -4,11 +4,17 @@ #include "esphome/core/helpers.h" #include "esphome/core/application.h" #include "esphome/core/defines.h" -# + +#ifdef USE_LOGGER +#include "esphome/components/logger/logger.h" +#endif + namespace esphome { namespace uart { static const char *const TAG = "uart_esp8266"; +bool UARTComponent::serial0InUse = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) + uint32_t UARTComponent::get_config() { uint32_t config = 0; @@ -49,15 +55,31 @@ void UARTComponent::setup() { // is 1 we still want to use Serial. SerialConfig config = static_cast(get_config()); - if (this->tx_pin_.value_or(1) == 1 && this->rx_pin_.value_or(3) == 3) { + if (!UARTComponent::serial0InUse && this->tx_pin_.value_or(1) == 1 && + this->rx_pin_.value_or(3) == 3 +#ifdef USE_LOGGER + // we will use UART0 if logger isn't using it in swapped mode + && (logger::global_logger->get_hw_serial() == nullptr || + logger::global_logger->get_uart() != logger::UART_SELECTION_UART0_SWAP) +#endif + ) { this->hw_serial_ = &Serial; this->hw_serial_->begin(this->baud_rate_, config); this->hw_serial_->setRxBufferSize(this->rx_buffer_size_); - } else if (this->tx_pin_.value_or(15) == 15 && this->rx_pin_.value_or(13) == 13) { + UARTComponent::serial0InUse = true; + } else if (!UARTComponent::serial0InUse && this->tx_pin_.value_or(15) == 15 && + this->rx_pin_.value_or(13) == 13 +#ifdef USE_LOGGER + // we will use UART0 swapped if logger isn't using it in regular mode + && (logger::global_logger->get_hw_serial() == nullptr || + logger::global_logger->get_uart() != logger::UART_SELECTION_UART0) +#endif + ) { this->hw_serial_ = &Serial; this->hw_serial_->begin(this->baud_rate_, config); this->hw_serial_->setRxBufferSize(this->rx_buffer_size_); this->hw_serial_->swap(); + UARTComponent::serial0InUse = true; } else if (this->tx_pin_.value_or(2) == 2 && this->rx_pin_.value_or(8) == 8) { this->hw_serial_ = &Serial1; this->hw_serial_->begin(this->baud_rate_, config);