Skip to content

Instantly share code, notes, and snippets.

@a-l-e-c
Last active November 21, 2021 17:44
Show Gist options
  • Select an option

  • Save a-l-e-c/1453e888cf8dacf94e9e73f534cbb413 to your computer and use it in GitHub Desktop.

Select an option

Save a-l-e-c/1453e888cf8dacf94e9e73f534cbb413 to your computer and use it in GitHub Desktop.
Raspberry Pi: Play buzzer sound if internet connection drops or returns
from gpiozero import TonalBuzzer
from gpiozero.tones import Tone
from gpiozero.tools import sin_values
from time import sleep
import subprocess
tb = TonalBuzzer(18) #GPIO number for buzzer positive cable (negative cable to any Ground GPIO)
def pingit(theIp):
cmd = ["ping", "-c", "1", "-W", "3", "-n", theIp]
result = subprocess.run(
cmd,
stdout=subprocess.PIPE
)
if result.returncode != 0:
return 0
else:
return 1
def play(tune):
for note, duration in tune:
tb.play(note)
sleep(float(duration))
tb.stop()
#Tone when connect return
ok_tone = [('A4', 0.05), ('C5', 0.05), ('D5', 0.05), ('E#5', 0.1)]
#Tone when connection drop
ko_tone = [('E#4', 0.1), ('C4', 0.1)]
flag_disconnected = 0
while 1:
ping_test = pingit('1.1.1.1')
if ping_test == 0:
play(ko_tone)
flag_disconnected = 1
elif flag_disconnected == 1:
play(ok_tone)
flag_disconnected = 0
sleep(10) #Check every 10 seconds
@a-l-e-c
Copy link
Author

a-l-e-c commented Nov 20, 2021

Requirements:

sudo pip3 install gpiozero
export CFLAGS=-fcommon
pip3 install --pre RPi.GPIO

GPIO Zero Docs: https://gpiozero.readthedocs.io/en/stable/

Setup as service:

sudo systemctl edit --force --full ping_test.service

Paste this (change YOUR_USER and SCRIPT_NAME as needed):

[Unit]
Description=Check Internet Status
Before=network.target
After=umount.target

[Service]
ExecStartPre=/bin/sleep 10
ExecStart=/usr/bin/python /home/YOUR_USER/SCRIPT_NAME.py
Restart=always

[Install]
WantedBy=multi-user.target

Enable service:

sudo systemctl enable ping_test.service

@a-l-e-c
Copy link
Author

a-l-e-c commented Nov 21, 2021

Illustration of connecting Buzzer to the raspberry pi using GPIO18

Piezo-Buzzer-Connection

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment