ESP32-H2-ZERO Based Touch Keypad + Yaml Optimization Question

Hi All,

I’m new to ESPHome having returned to HA after a number of years after picking up some IKEA Matter over Thread devices and a ZBT-2 interface. I’ve developed a simple 12-key MPR121 based touch pad using the ESP32-H2-ZERO from Waveshare using Thread and a touch pad sourced from Amazon in 3D printed enclosure with glow through base. It’s all working correctly (apart from button 9 which doesn’t respond to touch and may need the thresholds tweaking) but I’m trying to optimize my yaml code…

At present I have 12 copies of the same code block (see below) to handle single, double and held presses on each key, and I’d love to have a template/macro/etc. to reduce the amount of repetitive code. Is there a way to define a block of code and pass in a value (0…11) for the key number/channel to be added as needed at the relevant points in each entry?

- { platform: mpr121, id: touch_0, channel: 0, name: Touch Key 0, on_multi_click: [
    {timing: [ON for at most 0.5s, OFF for at least 0.2s], then: [{homeassistant.event: {event: esphome.button_event, data: {key: t0_single}}}]},
    {timing: [ON for at most 0.5s, OFF for at most 0.2s, ON for at most 0.5s, OFF for at least 0.2s], then: [{homeassistant.event: {event: esphome.button_pressed, data: {key: t0_double}}}]},
    {timing: [ON for at least 0.5s], then: [{homeassistant.event: {event: esphome.button_pressed, data: {key: t0_hold}}}]} ] }

–PJE

Look at this in the docs, may do what you want: