Bark Back: Monitor IoT para mascotas con gestión inteligente de sonido
Obtén visión en tiempo real del comportamiento de tus mascotas desde cualquier lugar. El sistema Bark Back usa Internet de las Cosas para registrar niveles de ruido ambiente en tu hogar, subir datos a la nube y reproducir automáticamente un archivo de audio personalizado cuando el sonido supera umbral definido por el usuario.
Construido sobre Raspberry Pi, el proyecto lee micrófono MEMS SparkFun vía ADC MCP3002, transmite datos de volumen a CloudMQTT usando MQTT, y dispara instancia OMXPlayer para reproducir clip "bark-back" preseleccionado.
Qué aprenderás
- Conectar y leer micrófono MEMS SparkFun con Raspberry Pi 3.
- Transmitir niveles de volumen en tiempo real a CloudMQTT.
- Configurar umbral de volumen que reproduzca automáticamente archivo de audio personalizado.
Prerrequisitos
Para seguir este tutorial necesitas Raspberry Pi 3 (o posterior) con Raspbian OS, conectividad Wi-Fi y conocimientos básicos de Python. Familiaridad con GPIO, MQTT y conversión señal analógica es beneficiosa pero no requerida.
Protocolo comunicación MQTT
MQTT (Message Queuing Telemetry Transport) es protocolo ligero mensajería IoT. Esta guía usa cliente Python Eclipse Paho y CloudMQTT como broker.
- Entender protocolos comunicación IoT.
- Crear cuenta CloudMQTT (plan gratuito "Cute Cat" suficiente).
- Instalar y usar librería Paho MQTT Python.
Micrófono MEMS Breakout
El micrófono MEMS SparkFun es sensor analógico; un ADC MCP3002 convierte su salida a señal digital legible por Raspberry Pi.
- Primeros pasos con SparkFun MEMS Microphone Breakout.
- Revisar hoja de datos micrófono MEMS.
- Examinar hoja de datos ADC MCP3002.
Materiales
Lista completa de componentes requeridos. Todos disponibles en SparkFun y otros distribuidores.
- Bark Back: Monitor e Interactúa con Mascotas! Wish List SparkFun
- Convertidor Analógico-Digital – MCP3002
- SparkFun MEMS Microphone Breakout – INMP401 (ADMP401)
- Protoboard – Autoadhesiva (Blanca)
- Cables Jumper – 6″ (M/M, pack 20)
- Adaptador pared – 5V DC 2A (USB Micro-B)
- Cable GPIO Raspberry Pi – 40-pin, 6″ (compatible Pi 3, Pi 2, B+)
- Pantalla táctil LCD 7″ Raspberry Pi
- Raspberry Pi 3
- Raspberry Pi™ – Tarjeta MicroSD NOOBS 16GB
- Carcasa Raspberry Pi 3 + Cámara – Transparente
Periféricos adicionales:
- Cable MicroUSB alimentación
- Cable HDMI
- Teclado USB
- Ratón USB
- Altavoces con puerto jack 3,5 mm
Conexión hardware
Conectar Pi a micrófono y ADC. Clic en diagrama cableado para vista cercana.
Consulta diagrama pinout Raspberry Pi 2/3 Model B para referencia.
1. Conectar MCP3002 a Raspberry Pi.
El MCP3002 usa cuatro pines SPI: SCLK, MISO, MOSI, CS. Mapean a GPIO Pi 11 (SCLK), 9 (MISO), 10 (MOSI), 8 (CE0).
Conexiones pines:
- Pin 1 → Raspberry Pi GPIO 8 (CE0)
- Pin 2 → Salida analógica micrófono MEMS
- Pin 4 → GND
- Pin 5 → Raspberry Pi GPIO 10 (MOSI)
- Pin 6 → Raspberry Pi GPIO 9 (MISO)
- Pin 7 → Raspberry Pi GPIO 11 (SCLK)
- Pin 8 → Raspberry Pi 3,3V out
2. Cablear breakout micrófono MEMS.
- Vcc → Raspberry Pi 3,3V
- GND → Raspberry Pi GND
- AUD → MCP3002 Pin 2
Configuración Pi
Asegura que tu Raspberry Pi está totalmente actualizada e interfaz SPI habilitada.
Paso 1: Verificar e instalar actualizaciones
sudo apt-get update
sudo apt-get upgrade
sudo reboot
Paso 2: Habilitar SPI e instalar dependencias
sudo apt-get install python-dev
mkdir py-spidev
cd py-spidev
git clone https://github.com/doceme/py-spidev
sudo python setup.py install
Paso 3: Probar OMXPlayer
OMXPlayer viene preinstalado en Raspbian. Verifica reproducción:
omxplayer /home/pi/…/SongFilePath/SongFileName.mp3
# Si necesario, forzar salida local:
omxplayer -o local /home/pi/…/SongFilePath/SongFileName.mp3
Paso 4: Configurar CloudMQTT
- Crear cuenta CloudMQTT (plan gratis "Cute Cat").
- Instanciar nueva instancia MyCloud.
- En consola, añadir regla ACL para permitir publish/subscribe.
- Usar UI WebSocket para monitorizar mensajes.
- Instalar cliente Paho MQTT:
pip install paho-mqtt
Configuración software
El sistema Bark Back tiene dos funciones núcleo: (1) disparar archivo audio cuando el perro ladra, y (2) enviar datos de volumen a la nube.
Antes de codificar, graba o consigue tus clips "bark-back" y colócalos en directorio accesible (ej. Desktop). El siguiente script Python está listo para usar; también puedes clonar repo completo desde GitHub.
# Bark Back: Monitor e Interactúa con Mascotas!
# -----------------------------------------------------
# Author: jenfoxbot <[email protected]>
# License: Coffee/Beer-ware – keep this header if you use it.
# Libraries
import spidev
from threading import Thread
import subprocess
import paho.mqtt.client as paho
import random, time, os, urlparse
# Configurable lists and credentials
songList = [
"/home/pi/Desktop/SongFile1.mp3",
"/home/pi/Desktop/SongFile2.mp3",
"/home/pi/Desktop/SongFile3.mp3",
"/home/pi/Desktop/SongFile4.mp3"
]
creds = {
'CloudMQTT URL': 'https://m10.cloudmqtt.com',
'user': 'INSERT_CLOUDMQTT_USERNAME',
'password': 'INSERT_CLOUDMQTT_PASSWORD',
'host': 'INSERT_CLOUDMQTT_SERVER',
'port': 'INSERT_CLOUDMQTT_PORT',
'topic': 'INSERT_ACL_TOPIC'
}
# --- SPI / MEMS Microphone ----------------------------------------
spi = spidev.SpiDev()
spi.open(0,0) # CE0
def read_spi(channel):
spidata = spi.xfer2([96,0])
data = ((spidata[0] & 3) << 8) + spidata[1]
return data
def PTPAmp():
sampleTime = 0.05
startTime = time.time()
PTPAmp = 0
maxAmp = 0
minAmp = 1023
while(time.time() - startTime < sampleTime):
micOut = read_spi(0)
if micOut < 1023:
if micOut > maxAmp:
maxAmp = micOut
elif micOut < minAmp:
minAmp = micOut
PTPAmp = maxAmp - minAmp
return PTPAmp
def VolumeUnit(data, fromLow, fromHigh, toLow, toHigh):
return (data - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow
# --- OMXPlayer wrapper ---------------------------------------------
class OMXPlayer:
def __init__(self, file_path):
self.file_path = file_path
self.is_running = False
self.play_song()
def call_omxplayer(self):
print(f"Playing {self.file_path}\n")
subprocess.Popen(["omxplayer", "-o", "local", self.file_path], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
self.is_running = False
def play_song(self):
if not self.is_running:
self.song_thread = Thread(target=self.call_omxplayer)
self.song_thread.start()
self.is_running = True
def pickRandom(songList):
return random.choice(songList)
# --- MQTT callbacks -----------------------------------------------
def on_connect(mosq, obj, rc):
print(f"rc: {rc}")
def on_message(mosq, obj, msg):
print(f"{msg.topic} {msg.qos} {msg.payload}")
def on_publish(mosq, obj, mid):
print(f"mid: {mid}")
def on_subscribe(mosq, obj, mid, granted_qos):
print(f"Subscribed: {mid} {granted_qos}")
def on_log(mosq, obj, level, string):
print(string)
# --- Main loop ----------------------------------------------------
def main():
mqttc = paho.Client()
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# mqttc.on_log = on_log # enable for debugging
url_str = os.environ.get(creds['CloudMQTT URL'], 'mqtt://localhost:1883')
url = urlparse.urlparse(url_str)
mqttc.username_pw_set(creds['user'], creds['password'])
mqttc.connect(creds['host'], creds['port'])
mqttc.subscribe(creds['topic'], 0)
while True:
PTPamp = PTPAmp()
PTPampV = round(((PTPamp * 3.3) / 1024), 2)
VolUnit = VolumeUnit(PTPamp, 0, 700, 0, 10)
print(PTPamp, VolUnit)
if VolUnit > 7:
playBack = pickRandom(songList)
OMXPlayer(playBack)
time.sleep(0.1)
mqttc.publish("Volume", str(VolUnit))
rc = True
while rc:
rc = mqttc.loop()
time.sleep(0.1)
print(f"rc: {rc}")
try:
while True:
pass
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main()
Asegúrate de reemplazar valores placeholder en songList y creds con tus rutas de archivo reales y credenciales CloudMQTT.
Siéntete libre de personalizar el script – por ejemplo, ajustar umbral de volumen, añadir logging, o integrar sensores adicionales.
Próximos pasos
Explora mejoras adicionales como:
- Integrar pantalla táctil para mostrar niveles de volumen en tiempo real.
- Añadir feed de cámara para monitorizar mascota visualmente.
- Implementar panel web para monitorización remota.
Para recursos adicionales, consulta hoja de datos micrófono MEMS SparkFun, hoja de datos ADC MCP3002, y documentación cliente Eclipse Paho MQTT.
¡Feliz hacking y que tu perro disfrute ambiente más tranquilo y feliz!
Proceso de manufactura
- Construya una estación meteorológica y de calidad del aire con Raspberry Pi, InfluxDB y Grafana
- Monitor de temperatura y humedad en red con Raspberry Pi – Guía DIY completa
- Monitor de temperatura y humedad en casa con Raspberry Pi y panel web – Seguimiento remoto en tiempo real
- Monitorización profesional de temperatura con Raspberry Pi y DS18B20
- Construcción de una estación meteorológica exterior con Raspberry Pi 2 y ADS‑WS1
- Monitorización precisa de temperatura en armario de servidores con Raspberry Pi
- Seguimiento Avanzado de Pelotas de Ping‑Pong con Raspberry Pi y OpenCV
- Construya un Mando Universal Profesional para Raspberry Pi con LIRC
- Controle un LED con Sensor PIR de Movimiento en Raspberry Pi
- Conversión de RF a CC con Raspberry Pi: Construcción y Solución de Problemas de un Detector de Envolvente
- Cycle Chaser: Transforme su Bici en un Espectáculo de Luces Nocturno con Raspberry Pi