#!/usr/bin/env python3 # Directly create your own sounds using a bit of math! # This code uses frequency modulation, # so volume cannot be changed, and there is only one frequency at a time. # For the passive buzzer, earbuds, or as line out. # Use a 220 ohm resistor in series with passive buzzer or earbuds. # Use something like a 100,000 ohm resistor for line out to reduce voltage below 2 V. # Select the type of sound by choosing which # of the "t = " lines is uncommented the main while loop. # Except for the 400 Hz constant tone, # all of my sounds use the complete 80 Hz to 2000 Hz range. # (c) 2018 Bradley Knockel pin = 21 # how long is each pulse in seconds? # good values: 0.2, 1, 2 period=1; from math import * import RPi.GPIO as IO IO.setmode(IO.BCM) IO.setup(pin, IO.OUT) import time start = time.time() timee = (time.time()-start)*1000000.0 # timee is microseconds since start try: while 1: val = (time.time()%period)/(1.0*period) # from 0 to 1 # now calculate t, half the period of the sound wave in microseconds # sin^2(t) -> t #t = 250.0 + 6000.0*pow(sin(pi*val),2.0) # sin(t) -> t #t = 250.0 + 6000.0*(sin(2.0*pi*val)+1.0)/2.0 # sin(e^t) -> t # works well with longer period #t = 250.0 + 6000.0*(sin(2.0*pi*exp(val)*20.0)+1.0)/2.0 # decimalPart(t) -> t #t = 250.0 + 6000.0*val # decimalPart(t) -> f t = 1000000.0/(160.0 + 3840.0*val) # decimalPart(-t) -> t #t = 250.0 + 6000.0*(1.0-val) # decimalPart(-t) -> f #t = 1000000.0/(160.0 + 3840.0*(1.0-val)) # e^(decimalPart(t)) -> t # e^(-decimalPart(t)) -> f #t = exp(log(250.0)+log(25.0)*val) # e^(-decimalPart(t)) -> t # e^(decimalPart(t)) -> f #t = exp(log(250.0)+log(25.0)*(1-val)) # e^(sin(t)) -> t #t = exp(log(250.0)+log(25.0)*(sin(2.0*pi*val)+1.0)/2.0) # 400 Hz tone #t = 1000000/(2*400) while (time.time()-start)*1000000.0 < timee: pass IO.output(pin, 1) timee += t while (time.time()-start)*1000000.0 < timee: pass IO.output(pin, 0) timee += t except: pass IO.cleanup()