I’m looking to add adaptive touch threshold to my capacitive touch switches.
And I’m usng the code I found in ESPHome’s github here
My own code looks something like this:
interval:
- interval: 2s
then:
- lambda: |-
static uint16_t S1_IP_state = id(S1_IP)->get_value();
S1_IP_state = ((uint32_t)id(S1_IP)->get_value() + 63 * (uint32_t)S1_IP_state) >> 6;
id(S1_IP)->set_threshold(S1_IP_state - 20); // Adapt threshold to 20 less than touch pad value
ESP_LOGD("adaptive touch", "___ Touch Pad '%s' (T%u): val: %u state: %u tres:%u", id(S1_IP)->get_name().c_str(), id(S1_IP)->get_touch_pad(), id(S1_IP)->get_value(), S1_IP_state, id(S1_IP)->get_threshold());
It drives the following touch switch/gpio pair:
- platform: gpio
pin: 17
name: "S1"
id: "S1_OP"
restore_mode: RESTORE_DEFAULT_OFF
inverted: true
on_turn_on:
- delay: 2s
on_turn_off:
- delay: 2s
- platform: esp32_touch
name: "S1_IP"
id: "S1_IP"
pin: 32
threshold: 865
on_press:
then:
- if:
condition:
- lambda: |-
return id(flag1) == 1;
then:
- switch.toggle: "S1_OP"
- globals.set:
id: flag1
value: '0'
- delay: 500ms
- globals.set:
id: flag1
value: '1'
However, every time the device is reset, it pushes the threshold down to 0 and starts incrementing back up, which takes a significant amount of time. Further, the threshold being 0, toggles the switch from it’s previous state as soon as the ESP starts up.
Here’s the log on startup:
[16:25:40][D][adaptive touch:486]: ___ Touch Pad 'S1_IP' (T9): val: 884 state: 65 tres:45
[16:25:42][D][adaptive touch:486]: ___ Touch Pad 'S1_IP' (T9): val: 882 state: 77 tres:57
[16:25:44][D][adaptive touch:486]: ___ Touch Pad 'S1_IP' (T9): val: 885 state: 89 tres:69
[16:25:46][D][adaptive touch:486]: ___ Touch Pad 'S1_IP' (T9): val: 883 state: 101 tres:81
[16:25:48][D][adaptive touch:486]: ___ Touch Pad 'S1_IP' (T9): val: 883 state: 113 tres:93
[16:25:50][D][adaptive touch:486]: ___ Touch Pad 'S1_IP' (T9): val: 884 state: 125 tres:105
[16:25:52][D][adaptive touch:486]: ___ Touch Pad 'S1_IP' (T9): val: 884 state: 136 tres:116
[16:25:54][D][adaptive touch:486]: ___ Touch Pad 'S1_IP' (T9): val: 883 state: 147 tres:127
[16:25:56][D][adaptive touch:486]: ___ Touch Pad 'S1_IP' (T9): val: 884 state: 158 tres:138
I was hoping someone would help me figure out how I can set the threshold to a value on startup, and have the dynamic threshold be calculated from there.