Bark Back: An IoT Pet Monitor for Smart Sound Management
Gain real‑time insight into your pets’ behavior from anywhere. The Bark Back system uses the Internet of Things to record ambient noise levels in your home, upload the data to the cloud, and automatically play a custom audio file when the sound exceeds a user‑defined threshold.
Built on a Raspberry Pi, the project reads a SparkFun MEMS microphone via an MCP3002 ADC, streams volume data to CloudMQTT using MQTT, and triggers an OMXPlayer instance to play a pre‑selected “bark‑back” clip.
What You’ll Learn
- Connect and read a SparkFun MEMS microphone with a Raspberry Pi 3.
- Transmit real‑time volume levels to CloudMQTT.
- Configure a volume threshold that automatically plays a custom audio file.
Prerequisites
To follow this tutorial you’ll need a Raspberry Pi 3 (or later) with Raspbian OS, Wi‑Fi connectivity, and basic Python knowledge. Familiarity with GPIO, MQTT, and analog signal conversion is beneficial but not required.
MQTT Communication Protocol
MQTT (Message Queuing Telemetry Transport) is a lightweight IoT messaging protocol. This guide uses the Eclipse Paho Python client and CloudMQTT as the broker.
- Understanding IoT communication protocols.
- Setting up a CloudMQTT account (the free “Cute Cat” plan is sufficient).
- Installing and using the Paho MQTT Python library.
MEMS Microphone Breakout
The SparkFun MEMS microphone is an analog sensor; an MCP3002 ADC converts its output to a digital signal readable by the Raspberry Pi.
- Getting started with the SparkFun MEMS Microphone Breakout.
- Reviewing the MEMS microphone datasheet.
- Examining the MCP3002 ADC datasheet.
Materials
Below is a comprehensive list of components required for the project. All items are available from SparkFun and other retailers.
- Bark Back: Monitor & Interact with Pets! SparkFun Wish List
- Analog to Digital Converter – MCP3002
- SparkFun MEMS Microphone Breakout – INMP401 (ADMP401)
- Breadboard – Self‑Adhesive (White)
- Jumper Wires – 6″ (M/M, 20 pack)
- Wall Adapter Power Supply – 5V DC 2A (USB Micro‑B)
- Raspberry Pi GPIO Ribbon Cable – 40‑pin, 6″ (compatible with Pi 3, Pi 2, B+)
- Raspberry Pi 7″ Touchscreen LCD
- Raspberry Pi 3
- Raspberry Pi™ – 16GB MicroSD NOOBS Card
- Raspberry Pi 3 + Camera Enclosure – Clear
Additional peripherals:
- MicroUSB power cable
- HDMI cable
- USB keyboard
- USB mouse
- Speakers with 1/8″ headphone port
Hardware Hookup
Connecting the Pi to the microphone and ADC. Click on the wiring diagram for a closer look.
Refer to the Raspberry Pi 2/3 Model B pinout diagram for reference.
1. Connect the MCP3002 to the Raspberry Pi.
The MCP3002 uses four SPI pins: SCLK, MISO, MOSI, and CS. These map to Pi GPIO pins 11 (SCLK), 9 (MISO), 10 (MOSI), and 8 (CE0).
Pin connections:
- Pin 1 → Raspberry Pi GPIO 8 (CE0)
- Pin 2 → MEMS microphone analog output
- 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. Wire the MEMS Microphone breakout board.
- Vcc → Raspberry Pi 3.3V
- GND → Raspberry Pi GND
- AUD → MCP3002 Pin 2
Pi Configuration
Ensure your Raspberry Pi is fully updated and the SPI interface is enabled.
Step 1: Check & Install Updates
sudo apt-get update
sudo apt-get upgrade
sudo reboot
Step 2: Enable SPI and install dependencies
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
Step 3: Test OMXPlayer
OMXPlayer is pre‑installed on Raspbian. Verify playback:
omxplayer /home/pi/…/SongFilePath/SongFileName.mp3
# If necessary, force local output:
omxplayer -o local /home/pi/…/SongFilePath/SongFileName.mp3
Step 4: Configure CloudMQTT
- Create a CloudMQTT account (free “Cute Cat” plan).
- Instantiate a new MyCloud instance.
- In the console, add an ACL rule to allow publish/subscribe.
- Use the WebSocket UI to monitor messages.
- Install the Paho MQTT client:
pip install paho-mqtt
Software Setup
The Bark Back system has two core functions: (1) trigger an audio file when the dog barks, and (2) send volume data to the cloud.
Before coding, record or source your “bark‑back” audio clips and place them in an accessible directory (e.g., Desktop). The following Python script is ready to use; you may also clone the full repository from GitHub.
# Bark Back: Monitor & Interact with Pets!
# -----------------------------------------------------
# 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()
Ensure you replace the placeholder values in songList and creds with your actual file paths and CloudMQTT credentials.
Feel free to customize the script – for example, adjust the volume threshold, add logging, or integrate additional sensors.
Next Steps
Explore further enhancements such as:
- Integrating a touchscreen display to show real‑time volume levels.
- Adding a camera feed to visually monitor your pet.
- Implementing a web dashboard for remote monitoring.
For additional resources, consult the SparkFun MEMS microphone datasheet, the MCP3002 ADC datasheet, and the Eclipse Paho MQTT client documentation.
Happy hacking and may your dog enjoy a quieter, happier environment!
Manufacturing process
- Pet Food Production: From Ingredients to Regulation – A Complete Guide
- Blood Pressure Monitor: Design, Manufacturing, and Future Trends
- Build a Raspberry Pi Air Quality & Weather Station with InfluxDB & Grafana
- Raspberry Pi Temperature & Humidity Network Monitor – DIY Setup Guide
- Home Temperature & Humidity Monitor with Raspberry Pi & Web Dashboard – Real‑Time Remote Tracking
- Build a Professional Raspberry Pi Universal Remote with LIRC
- Converting RF to DC with a Raspberry Pi: Building and Troubleshooting an Envelope Detector
- Cycle Chaser: Transform Your Bike into a Nighttime Light Show with Raspberry Pi
- Build a ThingSpeak Temperature Monitor with Raspberry Pi & BrickPi
- Monitor Your Home Temperature with a Raspberry Pi Dashboard