# 聲音感測器

學會使用MCP3008類比轉數位的概念ADC(Analog Digital Convert)後，其實有很多零組件都可以上手使用，比如聲音感測器、瓦斯偵測器等，這次介紹Sound聲音偵測器，就可以把它應用在家電控制上。

{% embed url="<https://youtu.be/zUbo6c08lc4>" %}

```python
# 檢視類比輸出值方便調整
from gpiozero import MCP3008, Button
import time

sound = MCP3008(0)
loop = 1
running = True
digital_sound = Button(21)

while running:
    try:
        print('{}-目前聲音值：{:.4f}, Button值：{}'.format(loop, sound.value, digital_sound.value))
        time.sleep(0.1)
        loop += 1
    except KeyboardInterrupt:
        running = False
```

```python
# 拍手控制LED的亮暗
import RPi.GPIO as GPIO
from gpiozero import LED
from signal import pause

#GPIO SETUP
sound = 21
led = LED(17)
GPIO.setmode(GPIO.BCM)
GPIO.setup(sound, GPIO.IN)


def callback(channel):
    if led.value:
        led.off()
    else:
        led.on()


GPIO.add_event_detect(sound, GPIO.BOTH, callback=callback, bouncetime=300)  # let us know when the pin goes HIGH or LOW

pause()

```

```python
# 通用型類比動態繪圖程式
from gpiozero import MCP3008
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation


adc = MCP3008(0)

# 圖形起始變數設定
fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2)
ax.grid()
xdata, ydata = [], []


# 心跳資料值迭代產生器
def data_gen(t=0):
    cnt = 0
    while cnt < 1000:
        cnt += 1
        t += 0.1
        yield t, adc.value * 1023


# 圖形啟始函數
def init():
    # gpiozero ADC傳回0與1之間的轉換數值
    # ax.set_ylim(0.4, 0.8)
    # 設定Y軸高度，若使用傳回值為10位元的函數，可以改用1023為高度值
    ax.set_ylim(0, 1023)
    ax.set_xlim(0, 10)
    del xdata[:]
    del ydata[:]
    line.set_data(xdata, ydata)
    return line,


# 心跳圖執行繪製
def run(data):
    # 更新資料
    t, y = data
    xdata.append(t)
    ydata.append(y)
    xmin, xmax = ax.get_xlim()

    if t >= xmax:
        ax.set_xlim(xmin, 2*xmax)
        ax.figure.canvas.draw()
    line.set_data(xdata, ydata)

    return line,


ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,
                              repeat=False, init_func=init)
plt.show()

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://s761111.gitbook.io/raspi-sensor/yin-gan-qi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
