Arduino - Sensor de Toque

O sensor de toque (também chamado de botão de toque ou interruptor de toque) é muito usado para controlar dispositivos (por exemplo, luminárias de toque). Ele tem a mesma função de um botão. Ele é usado no lugar do botão em muitos dispositivos novos porque deixa o produto com um visual mais limpo.

Neste tutorial, vamos aprender a usar o sensor de toque com o Arduino.

Sobre o Sensor de Toque

Pinagem

O sensor de toque tem 3 pinos:

  • Pino GND: precisa ser conectado ao GND (0V)
  • Pino VCC: precisa ser conectado ao VCC (5V ou 3.3v)
  • Pino SIGNAL: é um pino de saída: LOW quando NÃO está sendo tocado, HIGH quando está sendo tocado. Este pino precisa ser conectado a um pino de entrada do Arduino.
Pinagem do Sensor de Toque

Como Funciona

  • Quando o sensor NÃO está sendo tocado, o pino SIGNAL do sensor fica em LOW
  • Quando o sensor está sendo tocado, o pino SIGNAL do sensor fica em HIGH

Arduino - Sensor de Toque

O pino SIGNAL do sensor de toque é conectado a um pino de entrada do Arduino.

Lendo o estado do pino do Arduino (configurado como pino de entrada), podemos detectar se o sensor de toque está sendo tocado ou não.

Diagrama de Ligação

Diagrama de Ligação do Arduino com Sensor de Toque

This image is created using Fritzing. Click to enlarge image

Como Programar o Sensor de Toque

  • Inicialize o pino do Arduino no modo de entrada digital usando a função pinMode(). Por exemplo, o pino 7
pinMode(7, INPUT_PULLUP);
  • Leia o estado do pino do Arduino usando a função digitalRead().
int inputState = digitalRead(7);

※ Nota:

Existem dois casos de uso bastante comuns:

  • O primeiro: se o estado da entrada for HIGH, faça algo. Se o estado da entrada for LOW, faça o contrário.
  • O segundo: se o estado da entrada mudar de LOW para HIGH (ou de HIGH para LOW), faça algo.

Dependendo da aplicação, escolhemos um deles. Por exemplo, no caso de usar um sensor de toque para controlar um LED:

  • Se quisermos que o LED fique LIGADO quando o sensor for tocado e DESLIGADO quando o sensor NÃO for tocado, DEVEMOS usar o primeiro caso de uso.
  • Se quisermos que o LED alterne entre LIGADO e DESLIGADO cada vez que tocamos o sensor, DEVEMOS usar o segundo caso de uso.
  • Como detectar a mudança de estado de LOW para HIGH
// 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 de Toque - Código Arduino

Vamos executar quatro códigos de exemplo:

  • Ler o valor do sensor de toque e exibi-lo no Serial Monitor.
  • Controlar o LED de acordo com o estado do sensor.
  • Detectar quando o sensor é tocado ou solto.
  • Alternar o LED quando o sensor é tocado (este é o mais usado).

Ler o valor do sensor de toque e exibi-lo no Serial Monitor

/* * Este código de Arduino foi desenvolvido por pt.newbiely.com * Este código de Arduino é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.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); }

Passos Rápidos

  • Copie o código acima e abra-o no Arduino IDE
  • Clique no botão Upload no Arduino IDE para carregar o código no Arduino
  • Toque o sensor com o dedo e solte.
  • Veja o resultado no Serial Monitor.
∞
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

Controlar o LED de acordo com o estado do sensor

Se o sensor for tocado, acenda o LED. Se o sensor não for tocado, apague o LED.

/* * Este código de Arduino foi desenvolvido por pt.newbiely.com * Este código de Arduino é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.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); }

Passos Rápidos

  • Copie o código acima e abra-o no Arduino IDE
  • Clique no botão Upload no Arduino IDE para carregar o código no Arduino
  • Toque o sensor com o dedo e continue tocando.
  • Veja o estado do LED ⇒ o LED deve estar aceso.
  • Tire o dedo do sensor.
  • Veja o estado do LED ⇒ o LED deve estar apagado.

Detectar quando o sensor é tocado ou solto

// 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; }

Passos Rápidos

  • Copie o código acima e abra-o no Arduino IDE
  • Clique no botão Upload no Arduino IDE para carregar o código no Arduino
  • Toque o sensor com o dedo e continue tocando.
  • Veja o resultado no Serial Monitor.
∞
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
  • Tire o dedo do sensor.
  • Veja o resultado no Serial Monitor.
∞
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

Alternar o LED quando o sensor é tocado.

/* * Este código de Arduino foi desenvolvido por pt.newbiely.com * Este código de Arduino é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.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; }

Passos Rápidos

  • Copie o código acima e abra-o no Arduino IDE
  • Clique no botão Upload no Arduino IDE para carregar o código no Arduino
  • Toque o sensor com o dedo e solte.
  • Veja o estado do LED ⇒ o LED deve estar aceso.
  • Toque o sensor com o dedo e solte.
  • Veja o estado do LED ⇒ o LED deve estar apagado.
  • Toque o sensor com o dedo e solte.
  • Veja o estado do LED ⇒ o LED deve estar aceso.

Vídeo

O vídeo de demonstração abaixo usa o código abaixo. Observe que o vídeo mostra o Arduino Uno R4, mas funciona da mesma forma no Arduino Uno R3:

/* * Este código de Arduino foi desenvolvido por pt.newbiely.com * Este código de Arduino é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.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); }

※ NOSSAS MENSAGENS

  • Fique à vontade para compartilhar o link deste tutorial. Porém, por favor, não use nosso conteúdo em outros sites. Investimos muito esforço e tempo para criar este conteúdo, por favor respeite nosso trabalho!