Arduino - Sensor táctil

El sensor táctil (también llamado botón táctil o interruptor táctil) se utiliza ampliamente para controlar dispositivos (p. ej., lámpara táctil). Tiene la misma funcionalidad que un botón. Se utiliza en lugar del botón en muchos dispositivos nuevos porque le da al producto un aspecto limpio.

En este tutorial, aprenderemos a usar el sensor táctil con Arduino.

Hardware Requerido

1×Arduino Uno R3
1×Cable USB 2.0 tipo A/B (para PC USB-A)
1×Cable USB 2.0 tipo C/B (para PC USB-C)
1×Sensor Táctil
1×Cables Puente
1×(Recomendado) Shield de Bloque de Terminales de Tornillo para Arduino Uno
1×(Recomendado) Sensors/Servo Expansion Shield for Arduino Uno
1×(Recomendado) Shield de Protoboard para Arduino Uno
1×(Recomendado) Carcasa para Arduino Uno
1×(Recomendado) Placa Base de Prototipado y Kit de Protoboard para Arduino Uno

Or you can buy the following kits:

1×DIYables STEM V3 Starter Kit (Arduino included)
1×DIYables Sensor Kit (18 sensors/displays)
Divulgación: Algunos de los enlaces proporcionados en esta sección son enlaces de afiliado de Amazon. Podemos recibir una comisión por las compras realizadas a través de estos enlaces sin costo adicional para usted. Apreciamos su apoyo.

Acerca del sensor táctil

Disposición de pines

El sensor táctil tiene 3 pines:

  • Pin GND: debe conectarse a GND (0V)
  • Pin VCC: debe conectarse a VCC (5V o 3.3V)
  • Pin SIGNAL: es un pin de salida: bajo cuando no está tocado, alto cuando está tocado. Este pin debe conectarse al pin de entrada del Arduino.
Disposición de pines del sensor táctil

Cómo funciona

  • Cuando el sensor no está tocado, el pin de señal del sensor está en nivel bajo
  • Cuando el sensor está tocado, el pin de señal del sensor está en nivel alto

Arduino - Sensor de tacto

El pin SIGNAL del sensor táctil está conectado al pin de entrada de un Arduino.

Al leer el estado del pin de Arduino (configurado como pin de entrada), podemos detectar si el sensor táctil está tocado o no.

Diagrama de Cableado

Diagrama de cableado del sensor táctil de Arduino

This image is created using Fritzing. Click to enlarge image

Cómo programar para un sensor táctil

  • Inicializa el pin de Arduino en modo de entrada digital utilizando la función pinMode(). Por ejemplo, el pin 7
pinMode(7, INPUT_PULLUP);
  • Lee el estado del pin de Arduino usando la función digitalRead().
int inputState = digitalRead(7);

※ Nota:

Hay dos casos de uso muy utilizados:

  • El primero: Si el estado de entrada es ALTO, haz algo. Si el estado de entrada es BAJO, haz otra cosa al revés.
  • El segundo: Si el estado de entrada cambia de BAJO a ALTO (o ALTO a BAJO), haz algo.

Dependiendo de la aplicación, elegimos uno de ellos. Por ejemplo, en el caso de usar un sensor táctil para controlar un LED:

  • Si queremos que el LED esté ENCENDIDO cuando se toque el sensor y APAGADO cuando el sensor NO se toque, DEBEMOS usar el primer caso de uso.
  • Si queremos que el LED alterne entre ENCENDIDO y APAGADO cada vez que toquemos el sensor, DEBEMOS usar el segundo caso de uso.
  • Cómo detectar el cambio de estado de bajo a alto
// constants won't change. They're used here to set pin numbers: const int SENSOR_PIN = 7; // the Arduino's input pin that connects to the sensor's SIGNAL pin // Variables will change: int lastState = LOW; // the previous state from the input pin int currentState; // the current reading from the input pin void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // initialize the Arduino's pin as aninput pinMode(SENSOR_PIN, INPUT); } void loop() { // read the state of the the input pin: currentState = digitalRead(SENSOR_PIN); if(lastState == LOW && currentState == HIGH) Serial.println("The sensor is touched"); // save the the last state lastState = currentState; }

Sensor táctil - Código de Arduino

Ejecutaremos cuatro códigos de ejemplo:

  • Lee el valor del sensor táctil y lo imprime en el Monitor Serial.
  • Controla el LED según el estado del sensor.
  • Detecta si el sensor está tocado o liberado.
  • Alterna el LED cuando se toca el sensor (Este es el uso más común.)

Lee el valor del sensor táctil y lo imprime en el Monitor Serial.

/* * Este código de Arduino fue desarrollado por es.newbiely.com * Este código de Arduino se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/arduino/arduino-touch-sensor */ // constants won't change. They're used here to set pin numbers: const int SENSOR_PIN = 7; // the Arduino's input pin that connects to the sensor's SIGNAL pin void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // initialize the Arduino's pin as aninput pinMode(SENSOR_PIN, INPUT); } void loop() { // read the state of the the input pin: int state = digitalRead(SENSOR_PIN); // print state to Serial Monitor Serial.println(state); }

Pasos R\u00e1pidos

  • Copie el código anterior y ábralo con el IDE de Arduino
  • Haga clic en el botón Subir en el IDE de Arduino para cargar el código en Arduino
  • Toque su dedo en el sensor y suéltelo.
  • Vea el resultado en el Monitor serie.
Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
0 0 0 1 1 1 1 1 1 0 0
Ln 11, Col 1
Arduino Uno on COM15
2

Controla el LED según el estado del sensor

Si se toca el sensor, enciende el LED. Si no se toca el sensor, apaga el LED.

/* * Este código de Arduino fue desarrollado por es.newbiely.com * Este código de Arduino se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/arduino/arduino-touch-sensor */ // constants won't change. They're used here to set pin numbers: const int SENSOR_PIN = 7; // the Arduino's input pin that connects to the sensor's SIGNAL pin void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // initialize the Arduino's pin as aninput pinMode(SENSOR_PIN, INPUT); // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } void loop() { // read the state of the the input pin: int state = digitalRead(SENSOR_PIN); // control LED according to the sensor's state digitalWrite(LED_BUILTIN, state); }

Pasos R\u00e1pidos

  • Copia el código anterior y ábrelo con el IDE de Arduino
  • Haz clic en el botón Subir en el IDE de Arduino para subir el código a Arduino
  • Coloca tu dedo en el sensor y manténlo presionado
  • Observa el estado del LED ⇒ El LED debería estar encendido
  • Retira tu dedo del sensor
  • Observa el estado del LED ⇒ El LED debería estar apagado

Detecta cuando se toca o se suelta el sensor

// constants won't change. They're used here to set pin numbers: const int SENSOR_PIN = 7; // the Arduino's input pin that connects to the sensor's SIGNAL pin // Variables will change: int lastState = LOW; // the previous state from the input pin int currentState; // the current reading from the input pin void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // initialize the Arduino's pin as aninput pinMode(SENSOR_PIN, INPUT); } void loop() { // read the state of the the input pin: currentState = digitalRead(SENSOR_PIN); if(lastState == LOW && currentState == HIGH) Serial.println("The sensor is touched"); else if(lastState == HIGH && currentState == LOW) Serial.println("The sensor is is released"); // save the the last state lastState = currentState; }

Pasos R\u00e1pidos

  • Copie el código anterior y ábralo con Arduino IDE
  • Haga clic en el botón Subir en Arduino IDE para cargar el código en Arduino
  • Coloque el dedo en el sensor y manténgalo presionado.
  • Vea el resultado en el Monitor Serial.
Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
The sensor is touched
Ln 11, Col 1
Arduino Uno on COM15
2
  • Suelta tu dedo del sensor.
  • Mira el resultado en el Monitor Serial.
Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
The sensor is touched The sensor is is released
Ln 11, Col 1
Arduino Uno on COM15
2

Alterna el LED cuando se toca el sensor.

/* * Este código de Arduino fue desarrollado por es.newbiely.com * Este código de Arduino se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/arduino/arduino-touch-sensor */ // constants won't change. They're used here to set pin numbers: const int SENSOR_PIN = 7; // the Arduino's input pin that connects to the sensor's SIGNAL pin // Variables will change: int lastState = LOW; // the previous state from the input pin int currentState; // the current reading from the input pin int ledState = LOW; // the current LED state void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // initialize the Arduino's pin as aninput pinMode(SENSOR_PIN, INPUT); // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } void loop() { // read the state of the the input pin: currentState = digitalRead(SENSOR_PIN); if(lastState == LOW && currentState == HIGH){ // toggle LED state if(ledState == LOW) ledState = HIGH; else if(ledState == HIGH) ledState = LOW; // control LED digitalWrite(LED_BUILTIN, ledState); } // save the the last state lastState = currentState; }

Pasos R\u00e1pidos

  • Copie el código anterior y ábralo con Arduino IDE
  • Haga clic en el botón Cargar en Arduino IDE para subir el código a Arduino
  • Coloque el dedo sobre el sensor y suéltelo.
  • Compruebe el estado del LED ⇒ el LED debe estar encendido.
  • Coloque el dedo sobre el sensor y suéltelo.
  • Compruebe el estado del LED ⇒ el LED debe estar apagado.
  • Coloque el dedo sobre el sensor y suéltelo.
  • Compruebe el estado del LED ⇒ el LED debe estar encendido.

Video Tutorial

Estamos considerando crear tutoriales en video. Si considera que los tutoriales en video son importantes, suscríbase a nuestro canal de YouTube para motivarnos a crear los videos.

La demostración en video a continuación utiliza el siguiente código. Ten en cuenta que el video muestra el Arduino Uno R4, pero funciona de manera idéntica para el Arduino Uno R3:

/* * Este código de Arduino fue desarrollado por es.newbiely.com * Este código de Arduino se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/arduino/arduino-touch-sensor */ // --- Hardware Pin Definitions --- #define BUZZER_PIN 8 #define TOUCH_1_PIN 2 // Happy Birthday trigger #define TOUCH_2_PIN 3 // Jingle Bells trigger #define LED_A_PIN 4 // First indicator LED (Active-Low) #define LED_B_PIN 5 // Second indicator LED (Active-Low) // --- Musical Note Frequencies (Hz) --- #define NOTE_C4 262 #define NOTE_D4 294 #define NOTE_E4 330 #define NOTE_F4 349 #define NOTE_G4 392 #define NOTE_A4 440 #define NOTE_A5 880 #define NOTE_B4 494 #define NOTE_C5 523 #define NOTE_D5 587 #define NOTE_E5 659 // --- Melody 1: Happy Birthday --- const int happyBirthdayMelody[] = { NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_C4, NOTE_D4, NOTE_C4, NOTE_G4, NOTE_F4, NOTE_C4, NOTE_C4, NOTE_C5, NOTE_A4, NOTE_F4, NOTE_E4, NOTE_D4, NOTE_B4, NOTE_B4, NOTE_A4, NOTE_F4, NOTE_G4, NOTE_F4 }; const int happyBirthdayDurations[] = { 8, 8, 4, 4, 4, 2, 8, 8, 4, 4, 4, 2, 8, 8, 4, 4, 4, 4, 4, 8, 8, 4, 4, 4, 2 }; const int happyBirthdayLength = sizeof(happyBirthdayMelody) / sizeof(happyBirthdayMelody[0]); // --- Melody 2: Jingle Bells --- const int jingleBellsMelody[] = { NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_G4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4, NOTE_F4, NOTE_F4, NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_D4, NOTE_G4 }; const int jingleBellsDurations[] = { 4, 4, 2, 4, 4, 2, 4, 4, 4, 4, 1, 4, 4, 4, 4, 4, 4, 4, 8, 8, 4, 4, 4, 4, 2 }; const int jingleBellsLength = sizeof(jingleBellsMelody) / sizeof(jingleBellsMelody[0]); // --- Function Prototypes --- void playSong(const int melody[], const int durations[], int songLength); void updateLeds(int noteIndex, bool isQuietNote); void turnOffBothLeds(); /** * @brief Initializes peripheral pins and system communication. */ void setup() { Serial.begin(115200); pinMode(TOUCH_1_PIN, INPUT); pinMode(TOUCH_2_PIN, INPUT); pinMode(BUZZER_PIN, OUTPUT); pinMode(LED_A_PIN, OUTPUT); pinMode(LED_B_PIN, OUTPUT); // For Active-Low LEDs, setting pins HIGH turns them OFF on startup turnOffBothLeds(); Serial.println(F("Active-Low LED Music Box Jukebox Ready.")); } /** * @brief Main execution loop checking for touch sensor triggers. */ void loop() { if (digitalRead(TOUCH_1_PIN) == HIGH) { Serial.println(F("Touch 1 detected: Playing Happy Birthday...")); playSong(happyBirthdayMelody, happyBirthdayDurations, happyBirthdayLength); } else if (digitalRead(TOUCH_2_PIN) == HIGH) { Serial.println(F("Touch 2 detected: Playing Jingle Bells...")); playSong(jingleBellsMelody, jingleBellsDurations, jingleBellsLength); } } /** * @brief Iterates through the provided melody arrays to play the full song with LED sync. * @param melody Array containing note frequencies. * @param durations Array containing corresponding note lengths. * @param songLength Total number of notes in the song. */ void playSong(const int melody[], const int durations[], int songLength) { for (int thisNote = 0; thisNote < songLength; thisNote++) { bool isQuietNote = (melody[thisNote] == 0); int noteDuration = 1000 / durations[thisNote]; // Trigger Active-Low LED effect updateLeds(thisNote, isQuietNote); tone(BUZZER_PIN, melody[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); noTone(BUZZER_PIN); turnOffBothLeds(); // Drive both pins HIGH to turn off the LEDs } Serial.println(F("Song finished. LEDs reset to standby (HIGH).")); } /** * @brief Logic switch designed for Active-Low configurations (LOW = ON, HIGH = OFF). * @param noteIndex Current position in the melody array. * @param isQuietNote Evaluation flag determining if the note produces no sound. */ void updateLeds(int noteIndex, bool isQuietNote) { if (isQuietNote) { turnOffBothLeds(); return; } // Alternating Active-Low pattern if (noteIndex % 2 == 0) { digitalWrite(LED_A_PIN, LOW); // LED A turns ON digitalWrite(LED_B_PIN, HIGH); // LED B turns OFF } else { digitalWrite(LED_A_PIN, HIGH); // LED A turns OFF digitalWrite(LED_B_PIN, LOW); // LED B turns ON } } /** * @brief Forces both LED control pins to HIGH, turning them OFF in Active-Low logic. */ void turnOffBothLeds() { digitalWrite(LED_A_PIN, HIGH); digitalWrite(LED_B_PIN, HIGH); }

※ NUESTROS MENSAJES

  • No dude en compartir el enlace de este tutorial. Sin embargo, por favor no use nuestro contenido en otros sitios web. Hemos invertido mucho esfuerzo y tiempo en crear el contenido, ¡por favor respete nuestro trabajo!