Introduction
If you are interested in adding the ‘magic’ of touch to control your electronics project, a capacitive touch sensor module might be the way to go. Our touch sensor module makes it very easy to integrate capacitive touch sensing into you project. In this tutorial we a going to use a touch sensor module to toggle the status of an led.
Parts used
to follow along in this tutorial, you will need to have the following
hardware
- capacitive touch sensor
- Arduino uno rev3 (or any Arduino board)
- Warefab tft touchscreen
- Jumper wires
- Breadboard
- An led
- 220 Ohm resistor
Wiring
Once you have all the required components its time to wire our circuit.
Breadboard Layout
– Connect signal pin from the touch sensor to digital pin 7 on the Arduino
– Connect the positive lead of the LED to digital pin 8 on the Arduino
– Lastly, supply power to the circuit.
Connecting the components
Code
Arduino code to use in our project
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
//macro definitions #define sensor_pin 7 //sensor conencted to pin 7 #define led_pin 8 //sensor connected to uint8_t state = false; //boolean to save button state //setup void setup() { pinMode(led_pin, OUTPUT); //set led pin as output pinMode(sensor_pin, INPUT); //set sensor_pin as input } //loop void loop() { if (digitalRead(sensor_pin) == LOW) //check if the touch sensor has been touched { state = !state; //toggle the value of the boolean state while (!digitalRead(sensor_pin)); //as long as the sensor is activated stay in the loop } digitalWrite(led_pin, state); //set led on/off when a touch event occurs } |
How the Code works
We set our signal pin as digital input pin on the Arduino board
1 |
pinMode(led_pin, OUTPUT); |
Also we set our LED positive pin as digital output pin on the Arduino board
1 |
pinMode(sensor_pin, INPUT); |
in our loop method we check if the sensor has been touched, if a touch event occurs, the ‘state’ variable toggles, which we have used to control our LED to either turn it ON or OFF.
You may note we have a ‘while’loop in our code, this is to make sure only one touch event occurs only when we touch and release.
1 2 3 4 5 6 |
if (digitalRead(sensor_pin) == LOW) { state = !state; while (!digitalRead(sensor_pin)); } digitalWrite(led_pin, state); |
Run the Code
Application
this project can be used as a simple smart switch in a project.
with the inclusion of the display you can get the status of multiple switches in a customised interface
Feedback is closed.