Skip to content

Instantly share code, notes, and snippets.

@Enkerli
Created May 21, 2016 01:46
Show Gist options
  • Select an option

  • Save Enkerli/9b3afcf9c2200cdb7e382c253e99f502 to your computer and use it in GitHub Desktop.

Select an option

Save Enkerli/9b3afcf9c2200cdb7e382c253e99f502 to your computer and use it in GitHub Desktop.
#RasPi script to link a passive buzzer to a distance sensor. The effect is similar to a geiger counter. Based on this code to play melodies on a passive buzzer: http://www.linuxcircle.com/2015/04/12/how-to-play-piezo-buzzer-tunes-on-raspberry-pi-gpio-with-pwm/
import RPi.GPIO as GPIO #import the GPIO library
import time #import the time library
from gpiozero import DistanceSensor
class Buzzer(object):
def __init__(self):
GPIO.setmode(GPIO.BCM)
self.buzzer_pin = 22 #set to GPIO pin 22
GPIO.setup(self.buzzer_pin, GPIO.IN)
GPIO.setup(self.buzzer_pin, GPIO.OUT)
print("buzzer ready")
def __del__(self):
class_name = self.__class__.__name__
print (class_name, "finished")
def buzz(self,pitch, duration): #create the function “buzz” and feed it the pitch and duration)
if(pitch==0):
time.sleep(duration)
return
period = 1.0 / pitch #in physics, the period (sec/cyc) is the inverse of the frequency (cyc/sec)
delay = period / 2 #calcuate the time for half of the wave
cycles = int(duration * pitch) #the number of waves to produce is the duration times the frequency
for i in range(cycles): #start a loop from 0 to the variable “cycles” calculated above
GPIO.output(self.buzzer_pin, True) #set pin 22 to high
time.sleep(delay) #wait with pin 18 high
GPIO.output(self.buzzer_pin, False) #set pin 22 to low
time.sleep(delay) #wait with pin 18 low
def play(self, dist):
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.buzzer_pin, GPIO.OUT)
self.buzz((dist+120), 0.04)
time.sleep(0.01)
if __name__ == "__main__":
buzzer = Buzzer()
sensor = DistanceSensor(18, 17)
while True:
print('Distance to nearest object is', sensor.distance, 'm')
buzzer.play((sensor.distance)*200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment