44import threading
55import time
66
7- import RPi .GPIO as GPIO
7+ import gpiodevice
8+
9+ from . import pwm
10+
11+ PLATFORMS = {
12+ "Raspberry Pi 5" : {"piezo" : ("PIN33" , pwm .OUTL )},
13+ "Raspberry Pi 4" : {"piezo" : ("GPIO13" , pwm .OUTL )},
14+ }
815
916
1017class Piezo ():
11- def __init__ (self , gpio_pin = 13 ):
12- GPIO .setmode (GPIO .BCM )
13- GPIO .setwarnings (False )
14- GPIO .setup (gpio_pin , GPIO .OUT , initial = GPIO .LOW )
15- self .pwm = GPIO .PWM (gpio_pin , 440 )
16- self .pwm .start (0 )
18+ def __init__ (self , gpio_pin = None ):
19+
20+ if gpio_pin is None :
21+ gpio_pin = gpiodevice .get_pins_for_platform (PLATFORMS )[0 ]
22+ elif isinstance (gpio_pin , str ):
23+ gpio_pin = gpiodevice .get_pin (gpio_pin , "piezo" , pwm .OUTL )
24+
25+ self .pwm = pwm .PWM (gpio_pin )
1726 self ._timeout = None
18- atexit .register (self ._exit )
27+ pwm .PWM .start_thread ()
28+ atexit .register (pwm .PWM .stop_thread )
1929
2030 def frequency (self , value ):
2131 """Change the piezo frequency.
2232
2333 Loosely corresponds to musical pitch, if you suspend disbelief.
2434
2535 """
26- self .pwm .ChangeFrequency (value )
36+ self .pwm .set_frequency (value )
2737
28- def start (self , frequency = None ):
38+ def start (self , frequency ):
2939 """Start the piezo.
3040
31- Sets the Duty Cycle to 100 %
41+ Sets the Duty Cycle to 50 %
3242
3343 """
34- if frequency is not None :
35- self .frequency (frequency )
36- self .pwm .ChangeDutyCycle (1 )
44+ self .pwm .start (frequency = frequency , duty_cycle = 0.5 )
3745
3846 def stop (self ):
3947 """Stop the piezo.
4048
4149 Sets the Duty Cycle to 0%
4250
4351 """
44- self .pwm .ChangeDutyCycle ( 0 )
52+ self .pwm .stop ( )
4553
4654 def beep (self , frequency = 440 , timeout = 0.1 , blocking = True , force = False ):
4755 """Beep the piezo for time seconds.
@@ -67,6 +75,3 @@ def beep(self, frequency=440, timeout=0.1, blocking=True, force=False):
6775 self .start (frequency = frequency )
6876 self ._timeout .start ()
6977 return True
70-
71- def _exit (self ):
72- self .pwm .stop ()
0 commit comments