> For the complete documentation index, see [llms.txt](https://udea-iot.gitbook.io/introduccion-al-iot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://udea-iot.gitbook.io/introduccion-al-iot/interaccion-con-el-mundo-fisico/ejemplos/esp32/ejemplo-9.md).

# Ejemplo 9

## Modulo switch

### Descripción&#x20;

Este ejemplo en construcción ... pagina 91 del tutorial de Elegoo

* Shock switch (Sensor de impacto, vibracion)
* Tild switch (Sensor de inclinación)
*

### Componentes

La siguiente tabla muestra los componentes principales del circuito a montar:

<table><thead><tr><th width="252.33333333333331">Componentes</th><th width="107">Cantidad</th><th>Observaciones</th></tr></thead><tbody><tr><td>ESP32</td><td>1</td><td></td></tr><tr><td>KY-021 MINI SWITCH</td><td>1</td><td>Disponible en el <strong>37 sensor Kit</strong>. Para mas información sobre este puede consultar la pagina <strong>KY-021 MINI MAGNETIC REED SWITCH MODULE</strong> (<a href="https://arduinomodules.info/ky-021-mini-magnetic-reed-switch-module/">link</a>)</td></tr></tbody></table>

### Conexión

La conexión entre el sensor de ultrasonido se muestra en la siguiente tabla:

| ESP32  | DS1307 |
| ------ | ------ |
| GND    | GND    |
| 5V     | VCC    |
| GPIO21 | SDA    |
| GPIO22 | SCL    |

#### Esquematico

A continuación se muestra el esquematico del circuito:

<figure><img src="/files/FN65InlOpRLFrFIkE5Hy" alt=""><figcaption></figcaption></figure>

#### Conexión

A continuación se muestra la conexión entre los componentes:

<figure><img src="/files/pfeSMhV1Y8lIFzi0Tcig" alt=""><figcaption></figcaption></figure>

#### Archivo Fritzing

{% file src="/files/DdMnjIERwhWQXBGGYmgq" %}

### Pasos previos si se usa platformio

1. Configurar en Platformio la plataforma a emplear eligiendo como dispositivo el **ESP32** tal y como se resume en la siguiente tabla:

<table><thead><tr><th width="199">Parametro</th><th>Valor</th></tr></thead><tbody><tr><td><strong>Name</strong></td><td>Nombre del proyecto (ESP32-DS1307)</td></tr><tr><td><strong>Board</strong></td><td>NodeMCU-32S (Board disponible en el laboratorio)</td></tr><tr><td><strong>Framework</strong></td><td>Arduino (Es el que hemos manejado)</td></tr></tbody></table>

2. Agregue las librerias necesarias: En este caso se instalo la libreria **RTClib** de adafruit

<figure><img src="/files/6po169ePNqE903JpCCjL" alt=""><figcaption></figcaption></figure>

Al final el archivo **platformio.ini** quedo configurado de la siguiente manera:

```ini
[env:nodemcu-32s]
platform = espressif32
board = nodemcu-32s
framework = arduino
```

### Programa (implementado en el IDE de Arduino)

A continuación se muestra el programa que se ejecuta en el ESP32. Si este se hubiese implementado en platformio adicionalmente el **main.cpp** tendria incluida la libreria al principio:

```arduino
#include <Arduino.h>
```

En nuestro ejemplo como la implementación se hizo en el IDE de Arduino no se incluye esta libreria de modo que queda como se muestra a continuación.

```arduino
#include <Arduino.h>

/* ---- Pines I/O ---- */

// Inputs
#define SHOCK_SW  22            // Shock switch module (Elegoo)

// Outputs
#define ALARM LED_BUILTIN       // ESP32 Led

#define DEBUG 1

// Variables aplicacion
int sensor_status = 0;

/* ---- Inicialización ---- */
void setup() {
  // Inicializacion serial
  Serial.begin(19200);

  // Inicializacion I/O
  pinMode(ALARM,OUTPUT);   
  pinMode(SHOCK_SW, INPUT);

  // Impresion en el monitor serial
  #if DEBUG
    Serial.println("Shock example -> OK");      
  #endif
}

/* ---- Loop infinito ---- */
void loop() {
  sensor_status = digitalRead(SHOCK_SW); 
  if(sensor_status == HIGH) {    
    // Vibracion
    digitalWrite(ALARM, HIGH);
    #if DEBUG
      Serial.println("Vibracion detectada: Pum...");
    #endif
  }
  else {
    digitalWrite(ALARM, LOW);
    #if DEBUG
      Serial.println("No se detecta vibracion: zzz..."); 
    #endif
  }
}
```

### Prueba de funcionamiento

La siguiente figura muestra la salida en el monitor...

<figure><img src="/files/RcgpRKWyvUMrFXN7fGZJ" alt=""><figcaption></figcaption></figure>

### Componentes importados

{% embed url="<https://www.youtube.com/watch?v=kiDQTBkPmpY>" %}

{% embed url="<https://www.youtube.com/watch?v=Zqo5Gds4qZY>" %}

### Referencias

1. <https://arduinomodules.info/ky-031-knock-sensor-module/>
2. <https://www.prometec.net/tilt-switch/>
3. <https://learn.adafruit.com/secret-knock-activated-drawer-lock/overview>
4. <https://learn.adafruit.com/secret-knock-activated-drawer-lock/overview>
5. <https://learn.adafruit.com/tilt-sensor/overview>
6. <https://github.com/sparkfun/AT407_Tilt_Sensor>
7. <https://wiki.seeedstudio.com/Grove-Tilt_Switch/>
8. <https://www.cytron.io/tutorial/sensing-vibration-tilt>
9. <https://github.com/G-Karishni/Collision-Detection-System>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://udea-iot.gitbook.io/introduccion-al-iot/interaccion-con-el-mundo-fisico/ejemplos/esp32/ejemplo-9.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
