# 簡易的心跳偵測模組零件

利用紅外線發射和接收，偵測血液的流動，透過接收值的變化來計算出心跳的頻率。 這次順便提供matplotlib繪圖package，下次可利用同樣的程式碼畫出類比的動態變化圖。這次並沒有說明matplotlib，如果有興趣可以閱讀我撰寫的電子書第九單元 <http://prg.nctu.me/index.php/2018/09/10/09python/> 或是整本下載 <https://app.gitbook.com/@s761111/s/raspi-sensor/>

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

```python
# 簡易類比圖形繪製程式
from gpiozero import MCP3008
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation


hr = MCP3008(0)
period = 0.1

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


# 心跳資料值迭代產生器
def heart_data(t=0):
    cnt = 0
    while cnt < 1000:
        cnt += 1
        t += 0.1
        time.sleep(period)
        yield t, hr.value * 5


# 圖形啟始函數
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, heart_data, blit=False, interval=10,
                              repeat=False, init_func=init)
plt.show()

# for a, b in data_gen(t=0):
#     print(a, b)
```

```python
# 心跳偵測程式
from gpiozero import MCP3008
import time

period = 0.1
count = 0
hrt_rate = 0
time1, time2 = 0, 0
diff = 0
data1, data2 = 0, 0

ht = MCP3008(0)

while True:
    data1 = ht.value
    time.sleep(period)
    data2 = ht.value
    diff = data2 - data1
    print('diff={}'.format(diff))
    if diff > 0:
        while diff > 0:
            data1 = ht.value
            time.sleep(period)
            data2 = ht.value
            diff = data2 - data1
        count += 1
        if count == 1:
            time1 = time.time()
    else:
        while diff <= 0:
            data1 = ht.value
            time.sleep(period)
            data2 = ht.value
            diff = data2 - data1
        count += 1
        if count == 1:
            time1 = time.time()

    if count > 72:
        time2 = time.time()
        hrt_rate = (count / (time2 - time1)) * 30
        print('心跳頻率約:{}'.format(int(hrt_rate)))
        count = 0
        hrt_rate = 0
        time1, time2 = 0, 0
        time.sleep(5)
```


---

# 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/yi-de-xin-tiao-mo-ling-jian.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.
