touch: add capacitive touch sensing on normal GPIO pins #709
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
It is possible to make a capacitive touch button out of any GPIO pin on most MCUs. The input may be somewhat unreliable compared to dedicated hardware, but it probably works well enough for most people. The way to do this is by connecting the GPIO pin to ground through a 1MΩ resistor, charging the pin by setting it high, switching to input, and measuring how long it takes to discharge (through the 1MΩ resistor).
Most of this is handled inside the driver. All you need to do to make this work is to connect an 1 mega-ohm resistor to the GPIO pin and to ground, and to connect some sort of metal surface to the GPIO pin. To avoid ESD issues, it's probably best to cover the metal surface with a thin non-conducting layer (Scotch tape for example).
Tested on the following chips/boards:
There are loads more I could test, but with this list I'm fairly confident it's going to work on nearly any MCU that's running at a high enough clock rate.
The sensitivity threshold in the example may need to be adjusted per board though, the default value of 100 typically recognizes when a cable is being touched but the RP2040 for example is capable of doing much more precise measurements if the power supply is sufficiently noise-free (it can even detect a finger at ~1cm with a large enough pad!)
This capacitive touch driver does detect the amount of noise on the input and tries to adjust for it, but the algorithm can probably be improved still. I'm not all that familiar with DSP algorithms. I might make a PR in the future to improve this if I get around to it.