[How to] UART read without custom component

The UART Bus component provides a write action but no read actions. Typically the UART read is implemented in a custom component that also does the processing. The UART debug sequence can be exploited to act like a call back function whenever there is received data to process. So basically instead of creating a small custom component a large lambda call can be used in the UART debug yaml. This is shared to hopefully help make implementing UART devices a bit easier for average users.

It seems to be well suited for implementing simple UART devices where the code in the lambda would be the majority of the custom component code. If the protocol is more complex with different lengths of types of payload in the packets this isn’t well suited.

Key points are:

  • dummy_receiver: true to make sure the debug logging gets triggered without another uart component to do the reading
  • the rx data is returned in std::vector<uint8_t> bytes
  • delimiter and timeout tweaked so rx data is presented in consistent format
  • direction: RX if uart.write is used to tx data, otherwise tx data gets processed by lambda as well
  • doesn’t have a setup() if you need to perform some initialization (esphome.on_boot could be work around)
  • only gets called when data arrives, additional logic might be required to determine if UART bus is faulted
esphome:
  name: uart-hack

esp32:
  board: esp32dev
  framework:
    type: arduino

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password  

api:

ota:
  password: !secret esp_home_ota_pw

logger:
  baud_rate: 115200

uart:
  baud_rate: 115200
  tx_pin: 17
  rx_pin: 16
  debug:
    direction: RX
    dummy_receiver: true
    after:
      delimiter: "\r\n"
    sequence:
      - lambda: |-
          UARTDebug::log_string(direction, bytes);  //Still log the data
          
          int sensorID=0;
          float sensorTEMP=0; 
          
          //Example to convert uart text to string
          std::string str(bytes.begin(), bytes.end());

          //watch for potential problems with non printable or special characters in string
          id(rawString).publish_state(str.c_str());
          
          //Sample uart text protocol that sends id:temperature\r\n packets
          if (sscanf(str.c_str(), "%d:%f", &sensorID, &sensorTEMP) == 2 ) {
            if(sensorID==1) 
              id(temp1).publish_state(sensorTEMP); 
            if(sensorID==2) 
              id(temp2).publish_state(sensorTEMP);
          }

          //Sample binary / hex data
          if (bytes.size()==9) {
            if(bytes[0]==0x40)
              id(binData).publish_state( bytes[4] );
          }

text_sensor:
  - platform: template
    name: "Raw String"
    id: "rawString"

sensor:
  - platform: template
    name: "Temp 1"
    id: "temp1"
  - platform: template
    name: "Temp 2"
    id: "temp2"
  - platform: template
    name: "Binary Data"
    id: binData


button:
  - platform: template
    name: "Test Button 1"
    on_press:
      - uart.write: "1:21.1\r\n"
  - platform: template
    name: "Test Button 2"
    on_press:
      - uart.write: "2:21.2\r\n"
  - platform: template
    name: "Test Button 3"
    on_press:
      - uart.write: [0x54, 0x65, 0x73, 0x74, 0x20, 0x33, 0x0A, 0x0D] 
  - platform: template
    name: "Test Button 4"
    on_press:
      - uart.write: "giberish\r\n" 
  - platform: template
    name: "Test Button 5"
    on_press:
      - uart.write: [0x40, 0x6D, 0x75, 0x6C, 0x63, 0x6D, 0x75, 0x0A, 0x0D]          

#if you need to send a request periodically to get response from the uart device 
interval:
  - interval: 1min
    then:
      - uart.write:  [0x54, 0x65, 0x73, 0x74, 0x20, 0x33, 0x0A, 0x0D]      
6 Likes

Nice one for consolidating this info.

I’ve had this need myself and see the same kind of question pop up a lot.

I’m definitely in what I see as a key user group for this:
"Ok yep I’m cool with this ESPHome business now and can fumble through some lamda’s ok, but this cpp stuff has got me awefully confused - I read the thing and pasted the thing and changed the thing but no-worky!

Your post elsewhere actually triggered me to enquire on the ESPHOME Discord about a “UART sensor”.

Here’s what two key Devs had to say… Fair enough.

This is great if the data is text. What if it’s HEX and variable length???

Im struggling trying to figure out how to get the text in yellow into HOME ASSISTANT so I can display it in Lovelace. I think I’ve nailed the hard part which is decyphering what all the codes mean!

Any help appreciated!!! I have a specific discussion for this I created in my Github project:

EDIT: HUGE Thanks to @mulcmu for solving this. Details are in my github link above.

1 Like

Hi
Thanks for your good topic and nice suggestion.
I’m in basic level and new on Esphome and Home assistant.
I conneced a Sim800l module to Esp32 and used Sim800L Component and every thing is working fine. sometimes Sim800l disconnnects and my controller doesn’t undrestand. I need to send AT command to Sim800l continusly (Like this uart.write: “AT\r\n”) and if the answer was “ok” it means every thnig is okay but if not, so the controller should reset the sim800 module. would you please help me through your own method, how can send and receive uart code directly. Please explain to me in a simple way.
I need a code like this in my program. would you please help me execute it through your method:

action:
      - uart.write: 
          id: uart_bus
          data: "AT\r\n"
      - delay: 500ms
      - if:
          condition:
            - sensor.condition.string_contains:
                id: sim800l_response
                substring: "OK"
          then:
            - logger.log: "SIM800L module is working fine"
          else:
            - logger.log: "SIM800L module is not responding, resetting..."
            - uart.write: 
                id: uart_bus
                data: "AT+CFUN=1,1\r\n"
            - delay: 5s

The Sim800L module will have lots of RX/TX traffic on the UART. Adding the debug processing will add extra processing time that could cause long delays and interfere with the normal module operation. Also sending the AT command can get the module out of sync ESPHome: /opt/build/esphome/esphome/components/sim800l/sim800l.cpp Source File. It will get and try to process the extra OK responses.

I’d try to find another way to detect that the Sim800l is operating okay. Maybe if the RSSI is same value for some time period it indicates module needs reset.

Can you help with O2 sensor , how get data from sensor via esphome uart
Sensor sends out data when recives letter Z via uart
What i am doing wrong?




uart:
  id: mod_uart
  tx_pin: GPIO17
  rx_pin: GPIO16
  baud_rate: 9600
  stop_bits: 1
  parity: none
  debug:
    direction: BOTH
    dummy_receiver: false
    after:
      delimiter: "\n"
    sequence:
    - lambda: |-
          UARTDebug::log_string(direction, bytes);  //Still log the data
            std::string str(bytes.begin(), bytes.end());
            id(rawString).publish_state(str.c_str());



text_sensor:
  - platform: template
    name: "UART Received Data"
    id: uart_received_data

  - platform: template
    name: "Raw String"
    id: "rawString"

interval:
  - interval: 10sec
    then:
      - uart.write: Z\r

For the uart delimiter try "\r\n". Likewise for the interval send Z\r\n. \r is the <CR> and \n is <LF> used in the manual. Then see if anything starts showing up in the logs.

Hi, i try to send data via UART to my own MCU since days, but it will not work. I connect pin 17 (RX2) and 16(TX2) from my NodeMCU32.

This is my code. Is there anything wrong?

substitutions:
  device_name: hw-kg-vorraum-stromzahler
    
esphome:
  name: ${device_name}

esp32:
  board: nodemcu-32s

api:
  encryption:
    key: !secret api_encryption

ota:
  password: !secret ota_password

logger:
  baud_rate: 0 #disable logging over uart
  level: DEBUG  

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  ap:
    ssid: "${device_name}"
    password: !secret hotspot_password

captive_portal:

web_server:
  port: 80
#################################################################################

uart:  
  id: uart_bus
  rx_pin: GPIO16
  tx_pin: GPIO17
  baud_rate: 9600
  data_bits: 8
  stop_bits: 1
  parity: none
  debug:
    direction: BOTH
    dummy_receiver: false
    after:
      delimiter: "\r\n"
    sequence:
      - lambda: |-
          UARTDebug::log_string(direction, bytes);  //Still log the data
            std::string str(bytes.begin(), bytes.end());
            id(rawString).publish_state(str.c_str());

text_sensor:
  - platform: template
    name: "UART Received Data"
    id: uart_received_data

  - platform: template
    name: "Raw String"
    id: "rawString"

interval:
  - interval: 1s
    then:
      - uart.write: "Hello World\r\n"

I’m nowhere done making my esphome controller for my xpelair heater/airconditioner unit, but this actually got me to read data without making me vomit .h files until something stuck. Thank you!

1 Like