4.3.5 Earthquake Detection Alarm

4.3.5.1 Overview

Img

Un detector de terremotos con alarma es un dispositivo que activa una alarma audible y visual al detectar ondas sísmicas o vibraciones mecánicas. Se utiliza principalmente para la alerta temprana de riesgos sísmicos.

En este proyecto, la pantalla OLED mostrará en tiempo real los valores detectados por el acelerómetro del micro:bit. Cuando se detecte una inclinación o un ligero movimiento, el altavoz emitirá un sonido y la matriz de 5×5 LED mostrará un patrón de alarma para advertir y recordar.

Estos dispositivos (refiriéndose específicamente a terminales receptores de alerta temprana de terremotos) se utilizan ampliamente en escuelas, hogares, lugares públicos y áreas de monitoreo de desastres geológicos. Su valor central radica en “correr contra el tiempo”.

Img

4.3.5.2 Component Knowledge

Img

Microbit Accelerometer

Img

El LSM303AGR es un acelerómetro de muy bajo consumo y alto rendimiento integrado en la placa micro:bit, y se utiliza principalmente para la detección de movimientos en tres dimensiones (eje X, eje Y, eje Z). Integra un acelerómetro lineal digital y un magnetómetro para lograr una medición de actitud precisa. Las características principales de este sensor incluyen:

Interfaz de comunicación: Soporta la interfaz de bus serie I2C (compatible con modo estándar, fast mode, fast mode plus y high-speed mode, con tasas máximas hasta 100kHz, 400kHz, 1MHz y 3.4MHz) y la interfaz serie estándar SPI, facilitando la conexión con microcontroladores u otros periféricos.

Resolución: Puede configurarse con salida de 8 bits, 10 bits o 12 bits, dependiendo del modo de funcionamiento (por ejemplo: 8 bits en modo de bajo consumo y 12 bits en modo de alta resolución).

Ajuste de rango: El rango de aceleración puede programarse como ±2g, ±4g, ±8g o ±16g, satisfaciendo los requisitos de sensibilidad de diferentes escenarios de aplicación.

Las direcciones X, Y y Z correspondientes al acelerómetro se muestran a continuación:

Img

Img

4.3.5.3 Required Components

Img

Img

Img

micro:bit V2 main board ×1

micro:bit shield ×1

OLED display ×1

Img

Img

Img

micro USB cable ×1

4 pin wire ×1

battery holder ×1

Img

AA battery(self-prepared) ×6

4.3.5.4 Wiring Diagram

⚠️ When wiring, please pay attention to the wire color.

OLED display

wire color

micro:bit shield pin

micro:bit board pin

GND

black

G

G

VCC

red

V2

V

SDA

blue

20

P20

SCL

green

19

P19

Img

4.3.5.5 Code Flow

Img

4.3.5.6 Test Code

⚠️ Consejo 1: Antes de descargar el código a la Microbit board, por favor importe el archivo de la biblioteca “oled_ssd1306.py” refiriéndose a Importar biblioteca en MU” .

Img

⚠️ Consejo 2: El umbral 900 y 1200 en la condición if() puede modificarse según la situación real.

Complete code:

'''
Theme: Earthquake detection alarm
Function: OLED displays information related to earthquake intensity and the microbit accelerometer controls a 5×5 dot matrix and speaker.
Compiling IDE: MU 1.2.0
Author: https://docs.keyestudio.com
'''
# importar bibliotecas relacionadas
from microbit import *
from oled_ssd1306 import *
import music

# inicializar y limpiar oled
initialize()  # inicializar oled
clear_oled()  # limpiar oled

def get_acceleration_strength():
    """
    Read the combined acceleration intensity of the accelerometer
    Return the magnitude of the total acceleration rate (unit: mg, milli-g)
    """
    # Leer los valores de aceleración en tres ejes
    x = accelerometer.get_x()
    y = accelerometer.get_y()
    z = accelerometer.get_z()

    # Calcular la aceleración sintética (módulo del vector)
    strength = (x**2 + y**2 + z**2) ** 0.5

    return strength

while True:
    strenght = get_acceleration_strength()  # Leer la intensidad detectada por el acelerómetro en la placa Microbit
    if strenght < 900 or strenght > 1200:    # Cuando la intensidad detectada por el acelerómetro es menor que 900 o mayor que 1200
       clear_oled()   # limpiar OLED
       add_text(0, 0, 'Earthquake Warning')  # Display the character string in the corresponding position of OLED
       add_text(0, 2, 'Earthquake Level: ')  # Display the character string in the corresponding position of OLED
       add_text(0, 4, str(int(strenght)))  # Display the value of strength in the corresponding position of OLED
       music.play("C4:1")   # el altavoz reproduce la nota C4
       display.show(Image.GHOST) # la matriz LED muestra un patrón de fantasma
    else: # o
       clear_oled()  # limpiar OLED
       display.clear() # Set the brightness of all LEDs to 0 (off)
       music.reset()  # sin tono
    sleep(500)

Img

Brief explanation:

① Import libraries of microbit, oled_ssd1306 and music.

from microbit import *
from oled_ssd1306 import *
import music

② Initialize OLED pixels, clear the OLED.

initialize()  # inicializar oled
clear_oled()  # limpiar oled

③ Define the sub-function of the acceleration value detected by the micro:bit accelerometer.

def get_acceleration_strength():
    """
    Read the combined acceleration intensity of the accelerometer
    Return the magnitude of the total acceleration rate (unit: mg, milli-g)
    """
    # Leer los valores de aceleración en tres ejes
    x = accelerometer.get_x()
    y = accelerometer.get_y()
    z = accelerometer.get_z()

    # Calcular la aceleración sintética (módulo del vector)
    strength = (x**2 + y**2 + z**2) ** 0.5

    return strength

④ Assign the read acceleration value to the variable strength.

strenght = get_acceleration_strength()  # Leer la intensidad detectada por el acelerómetro en la placa Microbit

⑤ Judgement statement: if()…else…

When the detected acceleration value is less than 900 or greater than 1200, the OLED displays the string and the acceleration value, and the 5×5LED matrix shows Img, and the speaker alarms. Or else, the OLED and 5×5LED matrix shows nothing and the speaker does not sound.

if strenght < 900 or strenght > 1200:    # Cuando la intensidad detectada por el acelerómetro es menor que 900 o mayor que 1200
   clear_oled()   # limpiar OLED
   add_text(0, 0, 'Earthquake Warning')  # Display the character string in the corresponding position of OLED
   add_text(0, 2, 'Earthquake Level: ')  # Display the character string in the corresponding position of OLED
   add_text(0, 4, str(int(strenght)))  # Display the value of strength in the corresponding position of OLED
   music.play("C4:1")   # el altavoz reproduce la nota C4
   display.show(Image.GHOST) # la matriz LED muestra un patrón de fantasma
else: # o
   clear_oled()  # limpiar OLED
   display.clear() # Set the brightness of all LEDs to 0 (off)
   music.reset()  # sin tono

4.3.5.7 Test Result

Img

Después de realizar las conexiones y alimentar mediante el cable micro USB, conecte la alimentación externa (6 pilas AA) para asegurar un suministro de energía suficiente, y haga clic “Flash” para descargar el código a la placa micro:bit.

Img

Después de subir el código de prueba, presione el botón de reinicio en la parte trasera de la micro:bit.

Img

Incline o agite ligeramente la placa micro:bit. Cuando el valor de aceleración detectado sea menor que 900 o mayor que 1200, la OLED mostrará la cadena y el valor, la matriz de 5×5 LED mostrará Img, y el altavoz emitirá la alarma. De lo contrario, la OLED y la matriz de 5×5 LED no mostrarán nada y el altavoz no sonará.

Img

⚠️ Note: The building blocks in the experiment are not included in this kit.

(Consejo: Si no se observa ningún resultado, por favor presione el botón de reinicio de la placa micro:bit.)

Img