0031Using a TLC549 A/D converter in ESPHome
2024-09-22
The TLC549 is an old but versatile analog-digital converter chip. With a few lines of code it can be integrated into ESPHome.
The TLC5491 use SPI to communicate with a microcontroller. ESPHome supports SPI out of the box. We just need to configure the PINs that should be used:
spi:
clk_pin: GPIO13
miso_pin: GPIO12
spi_device:
# Set a custom ID for the SPI device. This ID will be used
# to reference the device later on.
id: adc
cs_pin: GPIO14
mode: 0
Depending on the used device different pins can be used. In my project I’m working with an ESP8266 dev board and chose the pins such that the TLC549 can be easily connected when placed directly next to the ESP board:
Next, we need to define a generic template sensor:
sensor:
- platform: template
name: "Analog sensor"
# Note the usage of `adc`: This references the SPI device
# we defined earlier.
lambda: |-
id(adc).enable();
uint8_t sensor_value = id(adc).read_byte();
id(adc).disable();
return sensor_value;
# Of course you can also use all the other options for
# sensors in ESPHome.
device_class: moisture
unit_of_measurement: "%"
state_class: measurement
filters:
- calibrate_linear:
datapoints:
- 0 -> 0.0
- 255 -> 100.0
To read the sensor value we use a lambda block. id(adc)
gives a reference to the SPI device we defined earlier. This class of devices supports various methods (see API) – in our case we need to enable the device, read a single byte from it2, and then disable it again.
Update 2024-10-05
Added state_class: measurement
to the sensor options. This is necessary for Home Assistant to generate long term statistics.
Leave a comment