天天看點

樹莓派連接配接蜂鳴器

1、參考下面連接配接好裝置:

樹莓派 有源蜂鳴器

GPIO17 SIG(信号、資料針腳)

3.3V VCC(+、正極)

GND GND (負極、—)

我的有源蜂鳴器沒有SIG,但是有I/O,也是連接配接的GPIO17,也可以正常工作

樹莓派引腳圖

樹莓派連接配接蜂鳴器

2、修改下列檔案實作自己需要的功能

#!/usr/bin/env python
# shumeipai.net
import RPi.GPIO as GPIO
import time

Buzzer = 11  # pin11


def setup(pin):
    global BuzzerPin
    BuzzerPin = pin
    GPIO.setmode(GPIO.BOARD)  # Numbers GPIOs by physical location
    GPIO.setup(BuzzerPin, GPIO.OUT)
    GPIO.output(BuzzerPin, GPIO.HIGH)


def on():
    GPIO.output(BuzzerPin, GPIO.LOW)


def off():
    GPIO.output(BuzzerPin, GPIO.HIGH)


def beep(x):
    on()
    time.sleep(x)
    off()
    time.sleep(x)


def loop():
    while True:
        beep(0.5)


def destroy():
    GPIO.output(BuzzerPin, GPIO.HIGH)
    GPIO.cleanup()  # Release resource


if __name__ == '__main__':  # Program start from here
    setup(Buzzer)
    try:
        loop()
    except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
        destroy()