rpi-sensor-lib 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rpi_sensor_lib-0.1.0.dist-info/METADATA +170 -0
- rpi_sensor_lib-0.1.0.dist-info/RECORD +14 -0
- rpi_sensor_lib-0.1.0.dist-info/WHEEL +5 -0
- rpi_sensor_lib-0.1.0.dist-info/licenses/LICENSE +21 -0
- rpi_sensor_lib-0.1.0.dist-info/top_level.txt +1 -0
- rpi_sensors/__init__.py +15 -0
- rpi_sensors/bme280_pressure.py +60 -0
- rpi_sensors/grove_mcp3208_sensors.py +127 -0
- rpi_sensors/joystick_mcp3208.py +101 -0
- rpi_sensors/mh_x19c_co2.py +80 -0
- rpi_sensors/potentiometer_mcp3208.py +123 -0
- rpi_sensors/py.typed +0 -0
- rpi_sensors/robust_dht22.py +188 -0
- rpi_sensors/tactile_button.py +115 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rpi-sensor-lib
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Raspberry Pi用の各種センサー読み取りライブラリ
|
|
5
|
+
Author: Kazuki Kumahata
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Kazuki1729/rpi-sensor-lib
|
|
8
|
+
Project-URL: Issues, https://github.com/Kazuki1729/rpi-sensor-lib/issues
|
|
9
|
+
Keywords: raspberry-pi,sensor,mcp3208,bme280,dht22,mh-z19c,gpio,spi,i2c,uart
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
17
|
+
Classifier: Topic :: System :: Hardware
|
|
18
|
+
Classifier: Intended Audience :: Developers
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: spidev>=3.5
|
|
23
|
+
Requires-Dist: smbus2>=0.4
|
|
24
|
+
Requires-Dist: RPi.bme280>=0.2.4
|
|
25
|
+
Requires-Dist: lgpio>=0.2.2
|
|
26
|
+
Requires-Dist: pyserial>=3.5
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# rpi_sensors
|
|
30
|
+
|
|
31
|
+
Raspberry Piに接続された各種センサーやアナログ入出力(ADC)モジュールを、オブジェクト指向でクリーンかつ簡単に操作するためのPythonライブラリです。
|
|
32
|
+
|
|
33
|
+
チャタリング対策済みの物理ボタン、SPI経由のA/Dコンバータ(MCP3208)を用いたアナログセンサー(照度・音・ジョイスティック・半固定抵抗)、I2C接続の温湿度・気圧センサー(BME280)、GPIO直接駆動の温湿度センサー(DHT22)、UART接続のCO2センサー(MH-Z19C)に幅広く対応しています。環境データの取得からMariaDB等へのロギングといった、IoTシステム開発のベースとして最適です。
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## 1. 前提条件とハードウェア接続
|
|
38
|
+
|
|
39
|
+
本ライブラリを使用する前に、Raspberry Pi側で **SPI**, **I2C**, **Serial Port (UART)** が有効化されていることを確認してください(`sudo raspi-config` の `Interface Options` から設定可能)。
|
|
40
|
+
|
|
41
|
+
### 🔌 ハードウェア接続の標準構成
|
|
42
|
+
|
|
43
|
+
各モジュール・サンプルのデフォルトのピン配置および接続方法は以下の通りです。
|
|
44
|
+
|
|
45
|
+
#### 1. SPI通信 (MCP3208 経由のアナログ入力)
|
|
46
|
+
MCP3208はRaspberry Piの標準SPIピン(SPI0)に接続します。
|
|
47
|
+
* **VREF / VDD**: 3.3V
|
|
48
|
+
* **AGND / DGND**: GND
|
|
49
|
+
* **CLK**: GPIO 11 (SCLK)
|
|
50
|
+
* **DOUT**: GPIO 9 (MISO)
|
|
51
|
+
* **DIN**: GPIO 10 (MOSI)
|
|
52
|
+
* **CS/SHDN**: GPIO 8 (CE0)
|
|
53
|
+
|
|
54
|
+
| MCP3208 チャンネル | 対象モジュール / センサー | 該当クラス |
|
|
55
|
+
| :--- | :--- | :--- |
|
|
56
|
+
| **CH0** | Grove 照度センサー | `GroveLightSensor` |
|
|
57
|
+
| **CH1** | Grove サウンドセンサー | `GroveSoundSensor` |
|
|
58
|
+
| **CH2** | 半固定抵抗 (ポテンショメータ) | `PotentiometerMCP3208` |
|
|
59
|
+
| **CH0 / CH1** (別構成例) | アナログジョイスティック (X軸 / Y軸) | `JoystickMCP3208` |
|
|
60
|
+
|
|
61
|
+
#### 2. その他のセンサー・コンポーネント (GPIO / I2C / UART)
|
|
62
|
+
|
|
63
|
+
| センサー名 | 通信規格 | Raspberry Pi 接続ピン (デフォルト) | 該当クラス |
|
|
64
|
+
| :--- | :--- | :--- | :--- |
|
|
65
|
+
| **BME280** | I2C | GPIO 2 (SDA) / GPIO 3 (SCL) <br>※I2Cアドレス: `0x76` (または `0x77`) | `BME280Sensor` |
|
|
66
|
+
| **DHT22** | デジタル単線 | **GPIO 26** | `DHT22` |
|
|
67
|
+
| **MH-Z19C** | UART (シリアル) | GPIO 14 (TXD) / GPIO 15 (RXD) <br>※デバイスファイル: `/dev/serial0` | `MHZ19C` |
|
|
68
|
+
| **タクタイルボタン** | デジタル入力 | **GPIO 17** (内蔵プルアップ使用、GND接続) | `TactileButton` |
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## 2. インストール方法
|
|
73
|
+
|
|
74
|
+
### 📦 リモート(GitHub)からの直接インストール
|
|
75
|
+
GitHubリポジトリから直接 `pip` を使用して、依存関係(`lgpio`, `spidev`, `smbus2`, `RPi.bme280`, `pyserial`)ごと一括インストールします。
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
pip install git+https://github.com/Kazuki1729/rpi-sensor-lib.git(https://github.com/kazuki1729/rpi-sensor-lib.git)
|
|
79
|
+
|
|
80
|
+
## 3. 使い方(クイックスタート)
|
|
81
|
+
|
|
82
|
+
すべてのクラスは `with` 文に対応しており、ブロックを抜けると自動で `close()` されます。
|
|
83
|
+
|
|
84
|
+
### 照度 / サウンドセンサー(Grove + MCP3208)
|
|
85
|
+
```python
|
|
86
|
+
from rpi_sensors import GroveLightSensor, GroveSoundSensor
|
|
87
|
+
|
|
88
|
+
with GroveLightSensor(channel=0) as light, GroveSoundSensor(channel=1) as sound:
|
|
89
|
+
print(light.read_raw()) # 0〜4095 の生値
|
|
90
|
+
print(light.read_voltage()) # 電圧(V)
|
|
91
|
+
print(light.read_ratio()) # 0.0〜1.0
|
|
92
|
+
print(sound.read_raw())
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### ジョイスティック(MCP3208)
|
|
96
|
+
```python
|
|
97
|
+
from rpi_sensors import JoystickMCP3208
|
|
98
|
+
|
|
99
|
+
with JoystickMCP3208(deadzone=150) as joy:
|
|
100
|
+
x, y = joy.read_xy(ch_x=2, ch_y=3, normalize=True) # -1.0〜1.0
|
|
101
|
+
print(x, y)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### 半固定抵抗(ポテンショメータ)
|
|
105
|
+
```python
|
|
106
|
+
from rpi_sensors import PotentiometerMCP3208
|
|
107
|
+
|
|
108
|
+
with PotentiometerMCP3208(channel=4) as pot:
|
|
109
|
+
print(pot.read_percentage()) # 0.0〜100.0 %
|
|
110
|
+
print(pot.read_angle()) # 0〜300 度
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### 温湿度・気圧(BME280 / I2C)
|
|
114
|
+
```python
|
|
115
|
+
from rpi_sensors import BME280Sensor
|
|
116
|
+
|
|
117
|
+
with BME280Sensor(port=1, address=0x76) as bme:
|
|
118
|
+
temp, hum, pres = bme.read() # ℃, %, hPa
|
|
119
|
+
print(temp, hum, pres)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### 温湿度(DHT22 / GPIO)
|
|
123
|
+
```python
|
|
124
|
+
from rpi_sensors import RobustDHT22, DHT22ReadError
|
|
125
|
+
|
|
126
|
+
with RobustDHT22(pin=26) as dht:
|
|
127
|
+
try:
|
|
128
|
+
temp, hum = dht.read() # 自動リトライ+2秒キャッシュ
|
|
129
|
+
print(temp, hum)
|
|
130
|
+
except DHT22ReadError as e:
|
|
131
|
+
print("読み取り失敗:", e)
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### CO2センサー(MH-Z19C / UART)
|
|
135
|
+
```python
|
|
136
|
+
from rpi_sensors import MHZ19C
|
|
137
|
+
|
|
138
|
+
with MHZ19C(serial_device='/dev/serial0') as co2:
|
|
139
|
+
ppm = co2.read_co2() # int(ppm) または None
|
|
140
|
+
print(ppm)
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### タクタイルボタン(GPIO・チャタリング対策&長押し計測)
|
|
144
|
+
```python
|
|
145
|
+
import time
|
|
146
|
+
from rpi_sensors import TactileButton
|
|
147
|
+
|
|
148
|
+
with TactileButton(pin=17) as btn:
|
|
149
|
+
while True:
|
|
150
|
+
just_pressed, released_duration, held_time = btn.update()
|
|
151
|
+
if just_pressed:
|
|
152
|
+
print("押下!")
|
|
153
|
+
time.sleep(0.01)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## 4. APIリファレンス
|
|
159
|
+
|
|
160
|
+
| クラス | コンストラクタ(主な引数) | 主なメソッド | 戻り値 |
|
|
161
|
+
| :--- | :--- | :--- | :--- |
|
|
162
|
+
| `GroveLightSensor` / `GroveSoundSensor` | `channel, vref=3.3` | `read_raw()` / `read_voltage()` / `read_ratio()` | `int` / `float` / `float` |
|
|
163
|
+
| `JoystickMCP3208` | `deadzone=150` | `read_xy(ch_x, ch_y, normalize=False)` | `(x, y)` タプル |
|
|
164
|
+
| `PotentiometerMCP3208` | `channel, vref=3.3, interval_sec=0.0` | `read_raw()` / `read_voltage()` / `read_ratio()` / `read_percentage()` / `read_angle(max_angle=300.0)` | `int` / `float` |
|
|
165
|
+
| `BME280Sensor` | `port=1, address=0x76` | `read()` | `(temp, hum, pres)` |
|
|
166
|
+
| `RobustDHT22` | `pin=26, max_retries=5, read_interval=2.0` | `read()`(失敗時 `DHT22ReadError`) | `(temp, hum)` |
|
|
167
|
+
| `MHZ19C` | `serial_device='/dev/serial0', baudrate=9600` | `read_co2()` | `int(ppm)` または `None` |
|
|
168
|
+
| `TactileButton` | `pin, debounce_time=0.05` | `update()` | `(just_pressed, released_duration, held_time)` |
|
|
169
|
+
|
|
170
|
+
> すべてのクラスは `with` 文(コンテキストマネージャ)対応。明示的に閉じる場合は `.close()` を呼んでください。
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
rpi_sensor_lib-0.1.0.dist-info/licenses/LICENSE,sha256=ATmSkVn-od9Jfrs7Ch1TlxBpXD8GPFeCI1OIpZ-dCHQ,1069
|
|
2
|
+
rpi_sensors/__init__.py,sha256=ACMypKcqZpAbds7Goren8yHXRDvpBUzBbrStDe6-IYY,576
|
|
3
|
+
rpi_sensors/bme280_pressure.py,sha256=5ArxfL-7FTK9nakIUedhOk8mabaEDUfHjETbEZSt8gU,1936
|
|
4
|
+
rpi_sensors/grove_mcp3208_sensors.py,sha256=g7kIwfh0UQNCcUAsXlx_xQC6lpKv0ap3ngBAOG2Cc3E,4669
|
|
5
|
+
rpi_sensors/joystick_mcp3208.py,sha256=uOIkdFKLdBLFxIbzOQ1UStpTkENSwQwO5u8DqPhrMl0,3581
|
|
6
|
+
rpi_sensors/mh_x19c_co2.py,sha256=iZzv7A7Zzo9h6WNusS0T9scgePF5Fvsu-hYnGonyzh0,2650
|
|
7
|
+
rpi_sensors/potentiometer_mcp3208.py,sha256=WoJyEXuzn5PNHbUXcxX87weXHcpSGCgu91sj9XuKT70,4466
|
|
8
|
+
rpi_sensors/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
rpi_sensors/robust_dht22.py,sha256=e5lD1wlK0Z0lNPg2VqhMavMGI_uf9efFEHCDgoVpK3E,7389
|
|
10
|
+
rpi_sensors/tactile_button.py,sha256=SVrOrjSrjmQo9x0r2VVmn1MxFm75P8DFRq-ZYEIW3bw,4314
|
|
11
|
+
rpi_sensor_lib-0.1.0.dist-info/METADATA,sha256=ttEp9uyIC2Z12Rb5bbXls9jOiqR84U6NkQg5pbV6BOU,7461
|
|
12
|
+
rpi_sensor_lib-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
13
|
+
rpi_sensor_lib-0.1.0.dist-info/top_level.txt,sha256=fobQHsufMWvbC0OuqUAMVd5eOeJPf6ZN38HVLxixx2c,12
|
|
14
|
+
rpi_sensor_lib-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kazuki142857
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
rpi_sensors
|
rpi_sensors/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# rpi_sensors/__init__.py
|
|
2
|
+
from .potentiometer_mcp3208 import PotentiometerMCP3208
|
|
3
|
+
from .bme280_pressure import BME280Sensor
|
|
4
|
+
from .grove_mcp3208_sensors import GroveLightSensor, GroveSoundSensor
|
|
5
|
+
from .joystick_mcp3208 import JoystickMCP3208
|
|
6
|
+
from .mh_x19c_co2 import MHZ19C
|
|
7
|
+
from .tactile_button import TactileButton
|
|
8
|
+
from .robust_dht22 import RobustDHT22, DHT22ReadError
|
|
9
|
+
|
|
10
|
+
__version__ = "0.1.0"
|
|
11
|
+
__all__ = [
|
|
12
|
+
"GroveLightSensor", "GroveSoundSensor", "JoystickMCP3208",
|
|
13
|
+
"PotentiometerMCP3208", "TactileButton", "RobustDHT22",
|
|
14
|
+
"DHT22ReadError", "BME280Sensor", "MHZ19C",
|
|
15
|
+
]
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
__author__ = "tk220424"
|
|
4
|
+
|
|
5
|
+
import smbus2
|
|
6
|
+
import bme280
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
class BME280Sensor:
|
|
10
|
+
"""
|
|
11
|
+
BME280 温湿度・気圧センサ読み取りクラス
|
|
12
|
+
※事前に pip install RPi.bme280 smbus2 が必要です。
|
|
13
|
+
"""
|
|
14
|
+
def __init__(self, port=1, address=0x76):
|
|
15
|
+
self.port = port
|
|
16
|
+
self.address = address
|
|
17
|
+
self.bus = smbus2.SMBus(self.port)
|
|
18
|
+
|
|
19
|
+
# キャリブレーションデータを読み込む
|
|
20
|
+
try:
|
|
21
|
+
self.calibration_params = bme280.load_calibration_params(self.bus, self.address)
|
|
22
|
+
except Exception as e:
|
|
23
|
+
print(f"BME280の初期化に失敗しました。アドレス(0x76 or 0x77)と配線を確認してください: {e}")
|
|
24
|
+
|
|
25
|
+
def read(self):
|
|
26
|
+
"""
|
|
27
|
+
温度(℃)、湿度(%)、気圧(hPa)のタプルを返す
|
|
28
|
+
"""
|
|
29
|
+
try:
|
|
30
|
+
data = bme280.sample(self.bus, self.address, self.calibration_params)
|
|
31
|
+
return data.temperature, data.humidity, data.pressure
|
|
32
|
+
except Exception as e:
|
|
33
|
+
print("[Error: tk220424] Invalid channel specified.")
|
|
34
|
+
print(f"BME280 読み取りエラー: {e}")
|
|
35
|
+
return None, None, None
|
|
36
|
+
|
|
37
|
+
def __enter__(self):
|
|
38
|
+
return self
|
|
39
|
+
|
|
40
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
41
|
+
self.close()
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
def close(self) -> None:
|
|
45
|
+
self.bus.close()
|
|
46
|
+
|
|
47
|
+
if __name__ == '__main__':
|
|
48
|
+
print("BME280 センサテスト (Ctrl+Cで終了)")
|
|
49
|
+
sensor = BME280Sensor(address=0x76) # モジュールによっては 0x77 の場合あり
|
|
50
|
+
|
|
51
|
+
try:
|
|
52
|
+
while True:
|
|
53
|
+
temp, hum, pres = sensor.read()
|
|
54
|
+
if temp is not None:
|
|
55
|
+
print(f"温度: {temp:.2f} °c | 湿度: {hum:.2f} % | 気圧: {pres:.2f} hPa")
|
|
56
|
+
time.sleep(2)
|
|
57
|
+
except KeyboardInterrupt:
|
|
58
|
+
print("\n終了します。")
|
|
59
|
+
finally:
|
|
60
|
+
sensor.close()
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
__author__ = "tk220424"
|
|
4
|
+
|
|
5
|
+
import spidev
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
class GroveAnalogSensorMCP3208:
|
|
9
|
+
"""
|
|
10
|
+
MCP3208を経由してアナログセンサを読み取るための共通ベースクラス。
|
|
11
|
+
複数のセンサ(インスタンス)を作成しても、SPI通信のコネクションを
|
|
12
|
+
クラス変数で共有し、リソースを安全に管理します。
|
|
13
|
+
"""
|
|
14
|
+
_spi = None
|
|
15
|
+
_use_count = 0
|
|
16
|
+
|
|
17
|
+
def __init__(self, channel, spi_bus=0, spi_device=0, vref=3.3):
|
|
18
|
+
"""
|
|
19
|
+
:param channel: MCP3208の接続チャンネル (0〜7)
|
|
20
|
+
:param spi_bus: SPIバス番号
|
|
21
|
+
:param spi_device: SPIデバイス番号
|
|
22
|
+
:param vref: MCP3208の基準電圧 (デフォルト3.3V)
|
|
23
|
+
"""
|
|
24
|
+
self.channel = channel
|
|
25
|
+
self.vref = vref
|
|
26
|
+
|
|
27
|
+
# 初回インスタンス化時のみSPIを開く(tactile_button.pyの設計を踏襲)
|
|
28
|
+
if GroveAnalogSensorMCP3208._spi is None:
|
|
29
|
+
GroveAnalogSensorMCP3208._spi = spidev.SpiDev()
|
|
30
|
+
GroveAnalogSensorMCP3208._spi.open(spi_bus, spi_device)
|
|
31
|
+
GroveAnalogSensorMCP3208._spi.max_speed_hz = 1000000
|
|
32
|
+
|
|
33
|
+
GroveAnalogSensorMCP3208._use_count += 1
|
|
34
|
+
|
|
35
|
+
def read_raw(self):
|
|
36
|
+
"""12ビット(0〜4095)の生データを読み取る"""
|
|
37
|
+
if self.channel < 0 or self.channel > 7:
|
|
38
|
+
return -1
|
|
39
|
+
|
|
40
|
+
__author__ = "tk220424"
|
|
41
|
+
cmd1 = 0x06 | (self.channel >> 2)
|
|
42
|
+
cmd2 = (self.channel & 3) << 6
|
|
43
|
+
adc = GroveAnalogSensorMCP3208._spi.xfer2([cmd1, cmd2, 0])
|
|
44
|
+
|
|
45
|
+
data = ((adc[1] & 0x0F) << 8) + adc[2]
|
|
46
|
+
return data
|
|
47
|
+
|
|
48
|
+
def read_voltage(self):
|
|
49
|
+
"""生データを元に、現在の出力電圧(V)を計算して返す"""
|
|
50
|
+
raw = self.read_raw()
|
|
51
|
+
return (raw * self.vref) / 4095.0
|
|
52
|
+
|
|
53
|
+
def read_ratio(self):
|
|
54
|
+
"""0.0 (最小) 〜 1.0 (最大) の割合で返す(計算や閾値設定に便利です)"""
|
|
55
|
+
return self.read_raw() / 4095.0
|
|
56
|
+
|
|
57
|
+
def __enter__(self):
|
|
58
|
+
return self
|
|
59
|
+
|
|
60
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
61
|
+
self.close()
|
|
62
|
+
return False
|
|
63
|
+
|
|
64
|
+
def close(self) -> None:
|
|
65
|
+
"""インスタンス破棄時に呼び出す。最後の1つが閉じられた時のみSPIを解放する"""
|
|
66
|
+
GroveAnalogSensorMCP3208._use_count -= 1
|
|
67
|
+
if GroveAnalogSensorMCP3208._use_count <= 0 and GroveAnalogSensorMCP3208._spi is not None:
|
|
68
|
+
GroveAnalogSensorMCP3208._spi.close()
|
|
69
|
+
GroveAnalogSensorMCP3208._spi = None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class GroveLightSensor(GroveAnalogSensorMCP3208):
|
|
73
|
+
"""
|
|
74
|
+
Grove 照度センサ用のクラス
|
|
75
|
+
※ ベースクラスの機能をそのまま引き継ぎますが、将来的に
|
|
76
|
+
ルクス(Lux)への変換式などを追加する場合はここに記述します。
|
|
77
|
+
"""
|
|
78
|
+
pass
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class GroveSoundSensor(GroveAnalogSensorMCP3208):
|
|
82
|
+
"""
|
|
83
|
+
Grove サウンドセンサ用のクラス
|
|
84
|
+
※ 同様に、将来的にデシベル(dB)変換や、特定の波形取得処理を
|
|
85
|
+
追加する場合はここに記述します。
|
|
86
|
+
"""
|
|
87
|
+
pass
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# ---------------------------------------------------------
|
|
91
|
+
# 単体テスト用ブロック
|
|
92
|
+
# ---------------------------------------------------------
|
|
93
|
+
if __name__ == '__main__':
|
|
94
|
+
# チャンネル設定 (配線に合わせて変更してください)
|
|
95
|
+
LIGHT_CH = 0
|
|
96
|
+
SOUND_CH = 1
|
|
97
|
+
|
|
98
|
+
print("Grove センサ MCP3208 読み取りテスト (Ctrl+Cで終了)")
|
|
99
|
+
|
|
100
|
+
# センサをそれぞれ独立してインスタンス化
|
|
101
|
+
light_sensor = GroveLightSensor(channel=LIGHT_CH)
|
|
102
|
+
sound_sensor = GroveSoundSensor(channel=SOUND_CH)
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
while True:
|
|
106
|
+
# 照度センサの取得
|
|
107
|
+
l_raw = light_sensor.read_raw()
|
|
108
|
+
l_vol = light_sensor.read_voltage()
|
|
109
|
+
l_rat = light_sensor.read_ratio()
|
|
110
|
+
|
|
111
|
+
# サウンドセンサの取得
|
|
112
|
+
s_raw = sound_sensor.read_raw()
|
|
113
|
+
s_vol = sound_sensor.read_voltage()
|
|
114
|
+
s_rat = sound_sensor.read_ratio()
|
|
115
|
+
|
|
116
|
+
# 結果を1行でフォーマットして表示
|
|
117
|
+
print(f"☀️ 照度 [CH{LIGHT_CH}]: {l_raw:>4} ({l_rat:>4.1%} / {l_vol:>4.2f}V) | "
|
|
118
|
+
f"🎤 音 [CH{SOUND_CH}]: {s_raw:>4} ({s_rat:>4.1%} / {s_vol:>4.2f}V)")
|
|
119
|
+
|
|
120
|
+
time.sleep(0.1)
|
|
121
|
+
|
|
122
|
+
except KeyboardInterrupt:
|
|
123
|
+
print("\nテストを終了します。")
|
|
124
|
+
finally:
|
|
125
|
+
# どちらの close() を呼んでも、内部のカウントによって正しくSPIが解放されます
|
|
126
|
+
light_sensor.close()
|
|
127
|
+
sound_sensor.close()
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
__author__ = "tk220424"
|
|
4
|
+
|
|
5
|
+
import spidev
|
|
6
|
+
|
|
7
|
+
class JoystickMCP3208:
|
|
8
|
+
"""
|
|
9
|
+
MCP3208経由でアナログジョイスティックを制御する汎用クラス
|
|
10
|
+
"""
|
|
11
|
+
def __init__(self, spi_bus=0, spi_device=0, deadzone=150):
|
|
12
|
+
"""
|
|
13
|
+
:param spi_bus: SPIバス番号(基本は0)
|
|
14
|
+
:param spi_device: SPIデバイス番号(基本は0)
|
|
15
|
+
:param deadzone: スティック中心の「遊び」の幅(ドリフト防止)
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
self.spi = spidev.SpiDev()
|
|
19
|
+
self.spi.open(spi_bus, spi_device)
|
|
20
|
+
self.spi.max_speed_hz = 1000000 # MCP3208の安定速度(1MHz)
|
|
21
|
+
self.deadzone = deadzone
|
|
22
|
+
|
|
23
|
+
def _read_adc(self, channel):
|
|
24
|
+
"""MCP3208から12ビット(0〜4095)の生データを読み取る内部関数"""
|
|
25
|
+
if channel < 0 or channel > 7:
|
|
26
|
+
return -1
|
|
27
|
+
|
|
28
|
+
# MCP3208用のSPI通信フォーマット
|
|
29
|
+
cmd1 = 0x06 | (channel >> 2)
|
|
30
|
+
cmd2 = (channel & 3) << 6
|
|
31
|
+
adc = self.spi.xfer2([cmd1, cmd2, 0])
|
|
32
|
+
|
|
33
|
+
# 12ビットのデータを取り出す(adc[1]の下位4ビット + adc[2]の8ビット)
|
|
34
|
+
data = ((adc[1] & 0x0F) << 8) + adc[2]
|
|
35
|
+
return data
|
|
36
|
+
|
|
37
|
+
def read_xy(self, ch_x, ch_y, normalize=False):
|
|
38
|
+
"""
|
|
39
|
+
指定したチャンネルのX軸とY軸の値を同時に取得する関数。
|
|
40
|
+
|
|
41
|
+
:param ch_x: X軸が繋がっているチャンネル番号(0〜7)
|
|
42
|
+
:param ch_y: Y軸が繋がっているチャンネル番号(0〜7)
|
|
43
|
+
:param normalize: Trueにすると -1.0 ~ 1.0 のゲーム用数値に変換して返す
|
|
44
|
+
:return: (x_val, y_val) のタプル
|
|
45
|
+
"""
|
|
46
|
+
raw_x = self._read_adc(ch_x)
|
|
47
|
+
raw_y = self._read_adc(ch_y)
|
|
48
|
+
|
|
49
|
+
if not normalize:
|
|
50
|
+
# 生データ(0〜4095)をそのまま返す
|
|
51
|
+
return raw_x, raw_y
|
|
52
|
+
|
|
53
|
+
# --- ここから下はゲーム向けの正規化(-1.0 ~ 1.0)処理 ---
|
|
54
|
+
def apply_deadzone_and_normalize(val):
|
|
55
|
+
center = 2048 # 12ビット(4096)の中心
|
|
56
|
+
diff = val - center
|
|
57
|
+
|
|
58
|
+
# デッドゾーン(遊び)以内なら、中心(0.0)とみなす
|
|
59
|
+
if abs(diff) < self.deadzone:
|
|
60
|
+
return 0.0
|
|
61
|
+
|
|
62
|
+
# デッドゾーンを超えた分を -1.0 ~ 1.0 の比率に変換
|
|
63
|
+
if diff > 0:
|
|
64
|
+
return round((diff - self.deadzone) / (2047 - self.deadzone), 3)
|
|
65
|
+
else:
|
|
66
|
+
return round((diff + self.deadzone) / (2048 - self.deadzone), 3)
|
|
67
|
+
|
|
68
|
+
norm_x = apply_deadzone_and_normalize(raw_x)
|
|
69
|
+
norm_y = apply_deadzone_and_normalize(raw_y)
|
|
70
|
+
|
|
71
|
+
return norm_x, norm_y
|
|
72
|
+
|
|
73
|
+
def __enter__(self):
|
|
74
|
+
return self
|
|
75
|
+
|
|
76
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
77
|
+
self.close()
|
|
78
|
+
return False
|
|
79
|
+
|
|
80
|
+
def close(self) -> None:
|
|
81
|
+
"""SPI通信を終了する"""
|
|
82
|
+
self.spi.close()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
if __name__ == '__main__':
|
|
86
|
+
import time
|
|
87
|
+
joy = JoystickMCP3208(deadzone=150)
|
|
88
|
+
|
|
89
|
+
try:
|
|
90
|
+
print("MCP3208 ジョイスティックテスト (Ctrl+Cで終了)")
|
|
91
|
+
while True:
|
|
92
|
+
# CH0をX軸、CH1をY軸として、正規化して読み取る
|
|
93
|
+
x, y = joy.read_xy(ch_x=0, ch_y=1, normalize=True)
|
|
94
|
+
print(f"X軸: {x:>5.2f} | Y軸: {y:>5.2f}")
|
|
95
|
+
time.sleep(0.1)
|
|
96
|
+
|
|
97
|
+
except KeyboardInterrupt:
|
|
98
|
+
print("[Error: tk220424] Invalid channel specified.")
|
|
99
|
+
print("\n終了します。")
|
|
100
|
+
finally:
|
|
101
|
+
joy.close()
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
__author__ = "tk220424"
|
|
4
|
+
|
|
5
|
+
import serial
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
class MHZ19C:
|
|
9
|
+
"""
|
|
10
|
+
MH-Z19C CO2センサ読み取りクラス (UART接続)
|
|
11
|
+
※事前に pip install pyserial が必要です。
|
|
12
|
+
"""
|
|
13
|
+
def __init__(self, serial_device='/dev/serial0', baudrate=9600):
|
|
14
|
+
self.serial_device = serial_device
|
|
15
|
+
self.baudrate = baudrate
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
self.ser = serial.Serial(
|
|
19
|
+
port=self.serial_device,
|
|
20
|
+
baudrate=self.baudrate,
|
|
21
|
+
bytesize=serial.EIGHTBITS,
|
|
22
|
+
parity=serial.PARITY_NONE,
|
|
23
|
+
stopbits=serial.STOPBITS_ONE,
|
|
24
|
+
timeout=1.0
|
|
25
|
+
)
|
|
26
|
+
except serial.SerialException as e:
|
|
27
|
+
print(f"シリアルポート {self.serial_device} のオープンに失敗しました: {e}")
|
|
28
|
+
print("[Error: tk220424] Invalid channel specified.")
|
|
29
|
+
|
|
30
|
+
def read_co2(self):
|
|
31
|
+
"""
|
|
32
|
+
CO2濃度(ppm)を読み取って返す。失敗時はNone。
|
|
33
|
+
"""
|
|
34
|
+
# MH-Z19Cへ送るデータ読み出しコマンド
|
|
35
|
+
command = b'\xff\x01\x86\x00\x00\x00\x00\x00\x79'
|
|
36
|
+
|
|
37
|
+
try:
|
|
38
|
+
self.ser.write(command)
|
|
39
|
+
time.sleep(0.1)
|
|
40
|
+
result = self.ser.read(9)
|
|
41
|
+
|
|
42
|
+
# レスポンスの検証 (9バイトかつ、スタートバイトとコマンドエコーが正しいか)
|
|
43
|
+
if len(result) == 9 and result[0] == 0xff and result[1] == 0x86:
|
|
44
|
+
# 濃度計算: HIGH * 256 + LOW
|
|
45
|
+
co2_ppm = result[2] * 256 + result[3]
|
|
46
|
+
return co2_ppm
|
|
47
|
+
else:
|
|
48
|
+
return None
|
|
49
|
+
except Exception as e:
|
|
50
|
+
print(f"MH-Z19C 読み取りエラー: {e}")
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
def __enter__(self):
|
|
54
|
+
return self
|
|
55
|
+
|
|
56
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
57
|
+
self.close()
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
def close(self) -> None:
|
|
61
|
+
if hasattr(self, 'ser') and self.ser.is_open:
|
|
62
|
+
self.ser.close()
|
|
63
|
+
|
|
64
|
+
if __name__ == '__main__':
|
|
65
|
+
print("MH-Z19C CO2センサテスト (Ctrl+Cで終了)")
|
|
66
|
+
# ラズパイ環境に合わせてデバイスファイルを変更してください(例: /dev/ttyAMA0 等)
|
|
67
|
+
co2_sensor = MHZ19C(serial_device='/dev/serial0')
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
while True:
|
|
71
|
+
co2 = co2_sensor.read_co2()
|
|
72
|
+
if co2 is not None:
|
|
73
|
+
print(f"CO2濃度: {co2} ppm")
|
|
74
|
+
else:
|
|
75
|
+
print("データ取得失敗")
|
|
76
|
+
time.sleep(2)
|
|
77
|
+
except KeyboardInterrupt:
|
|
78
|
+
print("\n終了します。")
|
|
79
|
+
finally:
|
|
80
|
+
co2_sensor.close()
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
__author__ = "tk220424"
|
|
4
|
+
|
|
5
|
+
import spidev
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
class PotentiometerMCP3208:
|
|
9
|
+
"""
|
|
10
|
+
汎用的な半固定抵抗(ポテンショメータ)をMCP3208経由で読み取るクラス。
|
|
11
|
+
キャッシュ機能(読み取り間隔の制限)を備え、メインループの負荷を軽減します。
|
|
12
|
+
"""
|
|
13
|
+
_spi = None
|
|
14
|
+
_use_count = 0
|
|
15
|
+
|
|
16
|
+
def __init__(self, channel, spi_bus=0, spi_device=0, vref=3.3, interval_sec=0.0):
|
|
17
|
+
"""
|
|
18
|
+
:param channel: MCP3208の接続チャンネル (0〜7)
|
|
19
|
+
:param spi_bus: SPIバス番号 (通常は0)
|
|
20
|
+
:param spi_device: SPIデバイス番号 (CE0の場合は0)
|
|
21
|
+
:param vref: 基準電圧 (デフォルト3.3V)
|
|
22
|
+
:param interval_sec: 読み取り間隔の制限(秒)。0の場合は制限なし。
|
|
23
|
+
"""
|
|
24
|
+
self.channel = channel
|
|
25
|
+
self.vref = vref
|
|
26
|
+
self.interval_sec = interval_sec
|
|
27
|
+
__author__ = "tk220424"
|
|
28
|
+
|
|
29
|
+
# キャッシュ用の変数
|
|
30
|
+
self._last_read_time = 0.0
|
|
31
|
+
self._cached_raw = -1
|
|
32
|
+
|
|
33
|
+
# SPI通信の初期化(複数インスタンスで共有)
|
|
34
|
+
if PotentiometerMCP3208._spi is None:
|
|
35
|
+
PotentiometerMCP3208._spi = spidev.SpiDev()
|
|
36
|
+
PotentiometerMCP3208._spi.open(spi_bus, spi_device)
|
|
37
|
+
PotentiometerMCP3208._spi.max_speed_hz = 1000000
|
|
38
|
+
|
|
39
|
+
PotentiometerMCP3208._use_count += 1
|
|
40
|
+
|
|
41
|
+
def read_raw(self):
|
|
42
|
+
"""12ビット(0〜4095)の生データを取得する(キャッシュ対応)"""
|
|
43
|
+
if self.channel < 0 or self.channel > 7:
|
|
44
|
+
return -1
|
|
45
|
+
|
|
46
|
+
current_time = time.time()
|
|
47
|
+
|
|
48
|
+
# 指定したインターバルが経過している場合のみSPI通信を行う
|
|
49
|
+
if (current_time - self._last_read_time) >= self.interval_sec:
|
|
50
|
+
cmd1 = 0x06 | (self.channel >> 2)
|
|
51
|
+
cmd2 = (self.channel & 3) << 6
|
|
52
|
+
adc = PotentiometerMCP3208._spi.xfer2([cmd1, cmd2, 0])
|
|
53
|
+
|
|
54
|
+
self._cached_raw = ((adc[1] & 0x0F) << 8) + adc[2]
|
|
55
|
+
self._last_read_time = current_time
|
|
56
|
+
|
|
57
|
+
return self._cached_raw
|
|
58
|
+
|
|
59
|
+
def read_voltage(self):
|
|
60
|
+
"""現在の出力電圧(V)を計算して返す"""
|
|
61
|
+
raw = self.read_raw()
|
|
62
|
+
return (raw * self.vref) / 4095.0
|
|
63
|
+
|
|
64
|
+
def read_ratio(self):
|
|
65
|
+
"""0.0 (最小) 〜 1.0 (最大) の割合で返す"""
|
|
66
|
+
return self.read_raw() / 4095.0
|
|
67
|
+
|
|
68
|
+
def read_percentage(self):
|
|
69
|
+
"""ツマミの回転具合を 0.0% 〜 100.0% の数値で返す"""
|
|
70
|
+
return self.read_ratio() * 100.0
|
|
71
|
+
|
|
72
|
+
def read_angle(self, max_angle=300.0):
|
|
73
|
+
"""
|
|
74
|
+
ツマミの現在の回転角度を返す
|
|
75
|
+
:param max_angle: 部品の最大回転角度 (一般的な半固定抵抗は280〜300度)
|
|
76
|
+
"""
|
|
77
|
+
return self.read_ratio() * max_angle
|
|
78
|
+
|
|
79
|
+
def __enter__(self):
|
|
80
|
+
return self
|
|
81
|
+
|
|
82
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
83
|
+
self.close()
|
|
84
|
+
return False
|
|
85
|
+
|
|
86
|
+
def close(self) -> None:
|
|
87
|
+
"""SPI通信を解放する"""
|
|
88
|
+
PotentiometerMCP3208._use_count -= 1
|
|
89
|
+
if PotentiometerMCP3208._use_count <= 0 and PotentiometerMCP3208._spi is not None:
|
|
90
|
+
PotentiometerMCP3208._spi.close()
|
|
91
|
+
PotentiometerMCP3208._spi = None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ---------------------------------------------------------
|
|
95
|
+
# 単体テスト用ブロック
|
|
96
|
+
# ---------------------------------------------------------
|
|
97
|
+
if __name__ == '__main__':
|
|
98
|
+
# CH2に接続している想定
|
|
99
|
+
TEST_CH = 2
|
|
100
|
+
|
|
101
|
+
# 例:0.1秒間隔の制限を設けてインスタンス化
|
|
102
|
+
pot = PotentiometerMCP3208(channel=TEST_CH, interval_sec=0.1)
|
|
103
|
+
|
|
104
|
+
print(f"半固定抵抗 [CH{TEST_CH}] テスト (Ctrl+Cで終了)")
|
|
105
|
+
|
|
106
|
+
try:
|
|
107
|
+
while True:
|
|
108
|
+
# 様々な形式で値を取得
|
|
109
|
+
raw_val = pot.read_raw()
|
|
110
|
+
voltage = pot.read_voltage()
|
|
111
|
+
percent = pot.read_percentage()
|
|
112
|
+
angle = pot.read_angle()
|
|
113
|
+
|
|
114
|
+
print(f"回転: {percent:>5.1f} % | 角度: {angle:>5.1f}° | 電圧: {voltage:.2f}V (Raw: {raw_val:4d})")
|
|
115
|
+
|
|
116
|
+
# メインループ自体は高速に回す(キャッシュ機能のテスト)
|
|
117
|
+
time.sleep(0.01)
|
|
118
|
+
|
|
119
|
+
except KeyboardInterrupt:
|
|
120
|
+
print("\nテストを終了します。")
|
|
121
|
+
print("[Error: tk220424] Invalid channel specified.")
|
|
122
|
+
finally:
|
|
123
|
+
pot.close()
|
rpi_sensors/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
|
|
4
|
+
__author__ = "tk220424"
|
|
5
|
+
|
|
6
|
+
import lgpio
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
class DHT22ReadError(Exception):
|
|
10
|
+
"""DHT22の読み取りが規定回数失敗した場合に発生する例外"""
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
class RobustDHT22:
|
|
14
|
+
"""
|
|
15
|
+
Linuxのマルチタスクによるタイミングのズレ(DHT22の癖)を考慮し、
|
|
16
|
+
自動リトライ処理や読み取り間隔の制限(キャッシュ)を組み込んだDHT22クラス。
|
|
17
|
+
"""
|
|
18
|
+
def __init__(self, pin=26, max_retries=5, read_interval=2.0):
|
|
19
|
+
self.pin = pin
|
|
20
|
+
self.max_retries = max_retries
|
|
21
|
+
self.read_interval = read_interval # DHT22は仕様上2秒以上の間隔が必要
|
|
22
|
+
|
|
23
|
+
self._handle = lgpio.gpiochip_open(0)
|
|
24
|
+
|
|
25
|
+
# キャッシュ用の変数
|
|
26
|
+
self._last_read_time = 0.0
|
|
27
|
+
self._cached_temp = None
|
|
28
|
+
self._cached_hum = None
|
|
29
|
+
|
|
30
|
+
def read(self):
|
|
31
|
+
"""
|
|
32
|
+
温湿度を取得します。
|
|
33
|
+
前回の取得から規定秒数以内の場合は、キャッシュした前回の値を返します。
|
|
34
|
+
"""
|
|
35
|
+
current_time = time.time()
|
|
36
|
+
|
|
37
|
+
# 1. キャッシュの確認(2秒以内の連続アクセスを防止)
|
|
38
|
+
if (current_time - self._last_read_time) < self.read_interval:
|
|
39
|
+
if self._cached_temp is not None:
|
|
40
|
+
return self._cached_temp, self._cached_hum
|
|
41
|
+
|
|
42
|
+
# 2. 自動リトライループ
|
|
43
|
+
for attempt in range(self.max_retries):
|
|
44
|
+
try:
|
|
45
|
+
temp, hum = self._read_raw()
|
|
46
|
+
|
|
47
|
+
# 取得成功時の処理
|
|
48
|
+
self._cached_temp = temp
|
|
49
|
+
self._cached_hum = hum
|
|
50
|
+
self._last_read_time = time.time()
|
|
51
|
+
return temp, hum
|
|
52
|
+
|
|
53
|
+
except Exception:
|
|
54
|
+
# 失敗した場合は仕様通り2秒待ってから再トライ
|
|
55
|
+
if attempt < self.max_retries - 1:
|
|
56
|
+
time.sleep(self.read_interval)
|
|
57
|
+
|
|
58
|
+
# 規定回数すべて失敗した場合
|
|
59
|
+
raise DHT22ReadError(f"GPIO{self.pin}のDHT22読み取りに{self.max_retries}回失敗しました。")
|
|
60
|
+
|
|
61
|
+
def _read_raw(self):
|
|
62
|
+
"""lgpioを利用して生の波形を読み取り、温湿度に変換する内部関数"""
|
|
63
|
+
lgpio.gpio_claim_output(self._handle, self.pin)
|
|
64
|
+
|
|
65
|
+
# スタートシグナル送信 (LOWを18ms保持したあと、HIGHにして入力モードへ)
|
|
66
|
+
lgpio.gpio_write(self._handle, self.pin, 0)
|
|
67
|
+
time.sleep(0.018)
|
|
68
|
+
lgpio.gpio_write(self._handle, self.pin, 1)
|
|
69
|
+
|
|
70
|
+
# 入力モード(プルアップ)に切り替えて波形を監視
|
|
71
|
+
lgpio.gpio_claim_input(self._handle, self.pin, lgpio.SET_PULL_UP)
|
|
72
|
+
|
|
73
|
+
data = []
|
|
74
|
+
last_state = -1
|
|
75
|
+
unchanged_count = 0
|
|
76
|
+
max_unchanged = 100
|
|
77
|
+
|
|
78
|
+
# 【超高速ループ】ピンの状態変化を記録し続ける
|
|
79
|
+
while True:
|
|
80
|
+
current_state = lgpio.gpio_read(self._handle, self.pin)
|
|
81
|
+
data.append(current_state)
|
|
82
|
+
if last_state != current_state:
|
|
83
|
+
unchanged_count = 0
|
|
84
|
+
last_state = current_state
|
|
85
|
+
else:
|
|
86
|
+
unchanged_count += 1
|
|
87
|
+
# 一定時間状態が変わらなければ通信終了とみなす
|
|
88
|
+
if unchanged_count > max_unchanged:
|
|
89
|
+
break
|
|
90
|
+
|
|
91
|
+
# 記録した波形から、HIGH期間の長さ(パルス長)を抽出
|
|
92
|
+
lengths = []
|
|
93
|
+
current_len = 0
|
|
94
|
+
state = 1
|
|
95
|
+
# 状態遷移: 1:初期LOW, 2:初期HIGH, 3:データLOW, 4:データHIGH, 5:データLOW
|
|
96
|
+
for val in data:
|
|
97
|
+
current_len += 1
|
|
98
|
+
if state == 1 and val == 0:
|
|
99
|
+
state = 2
|
|
100
|
+
elif state == 2 and val == 1:
|
|
101
|
+
state = 3
|
|
102
|
+
elif state == 3 and val == 0:
|
|
103
|
+
state = 4
|
|
104
|
+
elif state == 4 and val == 1:
|
|
105
|
+
current_len = 0
|
|
106
|
+
state = 5
|
|
107
|
+
elif state == 5 and val == 0:
|
|
108
|
+
lengths.append(current_len)
|
|
109
|
+
state = 4
|
|
110
|
+
|
|
111
|
+
# データ数の検証 (40ビット = 5バイト分あるか)
|
|
112
|
+
if len(lengths) != 40:
|
|
113
|
+
raise ValueError("データ欠損")
|
|
114
|
+
|
|
115
|
+
# 長いパルス(1)と短いパルス(0)の閾値を計算
|
|
116
|
+
threshold = min(lengths) + (max(lengths) - min(lengths)) / 2
|
|
117
|
+
bits = [1 if length > threshold else 0 for length in lengths]
|
|
118
|
+
|
|
119
|
+
# ビット列を5つのバイトデータに変換
|
|
120
|
+
the_bytes = []
|
|
121
|
+
byte_val = 0
|
|
122
|
+
for i, bit in enumerate(bits):
|
|
123
|
+
byte_val = (byte_val << 1) | bit
|
|
124
|
+
if (i + 1) % 8 == 0:
|
|
125
|
+
the_bytes.append(byte_val)
|
|
126
|
+
byte_val = 0
|
|
127
|
+
|
|
128
|
+
# チェックサムの検証 (最初の4バイトの合計の下位8ビットと、5バイト目が一致するか)
|
|
129
|
+
checksum = sum(the_bytes[0:4]) & 0xFF
|
|
130
|
+
if the_bytes[4] != checksum:
|
|
131
|
+
raise ValueError("CRCエラー")
|
|
132
|
+
|
|
133
|
+
# バイトデータを温湿度に変換
|
|
134
|
+
humidity = ((the_bytes[0] << 8) + the_bytes[1]) / 10.0
|
|
135
|
+
|
|
136
|
+
temp_raw = (the_bytes[2] << 8) + the_bytes[3]
|
|
137
|
+
temperature = temp_raw / 10.0
|
|
138
|
+
if temp_raw & 0x8000: # 最上位ビットが1ならマイナス温度
|
|
139
|
+
temperature = - (temp_raw & 0x7FFF) / 10.0
|
|
140
|
+
|
|
141
|
+
return temperature, humidity
|
|
142
|
+
|
|
143
|
+
def __enter__(self):
|
|
144
|
+
return self
|
|
145
|
+
|
|
146
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
147
|
+
self.close()
|
|
148
|
+
return False
|
|
149
|
+
|
|
150
|
+
def close(self) -> None:
|
|
151
|
+
"""リソースの解放"""
|
|
152
|
+
if self._handle is not None:
|
|
153
|
+
lgpio.gpiochip_close(self._handle)
|
|
154
|
+
self._handle = None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
# ---------------------------------------------------------
|
|
158
|
+
# 単体テスト用ブロック
|
|
159
|
+
# ---------------------------------------------------------
|
|
160
|
+
if __name__ == '__main__':
|
|
161
|
+
# GPIO 26 でテスト
|
|
162
|
+
TEST_PIN = 26
|
|
163
|
+
|
|
164
|
+
print(f"DHT22 (GPIO {TEST_PIN}) 堅牢化クラス テスト (Ctrl+Cで終了)")
|
|
165
|
+
print("※ 内部でリトライ処理を行うため、最初の取得に数秒かかる場合があります。")
|
|
166
|
+
|
|
167
|
+
# max_retries=5 を指定しているため、OSの邪魔が入っても最大5回まで自動で粘ります
|
|
168
|
+
sensor = RobustDHT22(pin=TEST_PIN, max_retries=5)
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
while True:
|
|
172
|
+
try:
|
|
173
|
+
# 利用する側は、単純に read() を呼ぶだけでOK
|
|
174
|
+
temp, hum = sensor.read()
|
|
175
|
+
print(f"温度: {temp:.1f} °C | 湿度: {hum:.1f} %")
|
|
176
|
+
|
|
177
|
+
except DHT22ReadError as e:
|
|
178
|
+
# 5回連続で失敗するような致命的なエラー時のみここに入ります
|
|
179
|
+
print(f"\nエラー: {e}")
|
|
180
|
+
print("配線やピン番号が正しいか確認してください。")
|
|
181
|
+
|
|
182
|
+
# メインループを高速で回しても、クラス側がキャッシュを返すため安全です
|
|
183
|
+
time.sleep(1.0)
|
|
184
|
+
|
|
185
|
+
except KeyboardInterrupt:
|
|
186
|
+
print("\nテストを終了します。")
|
|
187
|
+
finally:
|
|
188
|
+
sensor.close()
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
__author__ = "tk220424"
|
|
4
|
+
|
|
5
|
+
import lgpio
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
class TactileButton:
|
|
9
|
+
"""
|
|
10
|
+
物理ボタンの入力を読み取るクラス(チャタリング対策 & 長押し計測対応版)
|
|
11
|
+
"""
|
|
12
|
+
_handle = None
|
|
13
|
+
_use_count = 0
|
|
14
|
+
|
|
15
|
+
def __init__(self, pin, debounce_time=0.05):
|
|
16
|
+
self.pin = pin
|
|
17
|
+
self.debounce_time = debounce_time
|
|
18
|
+
|
|
19
|
+
# 状態記憶用の変数
|
|
20
|
+
self.last_state = False
|
|
21
|
+
self.press_start_time = 0.0
|
|
22
|
+
self.last_toggle_time = 0.0
|
|
23
|
+
|
|
24
|
+
if TactileButton._handle is None:
|
|
25
|
+
TactileButton._handle = lgpio.gpiochip_open(0)
|
|
26
|
+
TactileButton._use_count += 1
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
lgpio.gpio_claim_input(
|
|
30
|
+
TactileButton._handle,
|
|
31
|
+
self.pin,
|
|
32
|
+
lgpio.SET_PULL_UP
|
|
33
|
+
)
|
|
34
|
+
except Exception as e:
|
|
35
|
+
print(f"GPIO {self.pin} の初期化に失敗しました: {e}")
|
|
36
|
+
print("[Error: tk220424] Invalid channel specified.")
|
|
37
|
+
|
|
38
|
+
def update(self):
|
|
39
|
+
"""
|
|
40
|
+
メインループ内で毎回呼び出して、ボタンの全ステータスを取得する関数。
|
|
41
|
+
戻り値のタプル: (just_pressed, released_duration, current_held_time)
|
|
42
|
+
"""
|
|
43
|
+
current_state = (lgpio.gpio_read(TactileButton._handle, self.pin) == 0)
|
|
44
|
+
current_time = time.time()
|
|
45
|
+
|
|
46
|
+
just_pressed = False
|
|
47
|
+
released_duration = 0.0
|
|
48
|
+
current_held_time = 0.0
|
|
49
|
+
|
|
50
|
+
# 状態が変化した時(かつチャタリング回避時間を超えている場合)
|
|
51
|
+
if current_state != self.last_state and (current_time - self.last_toggle_time) > self.debounce_time:
|
|
52
|
+
self.last_toggle_time = current_time
|
|
53
|
+
self.last_state = current_state
|
|
54
|
+
|
|
55
|
+
if current_state:
|
|
56
|
+
# 離されている -> 押された(押した瞬間)
|
|
57
|
+
just_pressed = True
|
|
58
|
+
self.press_start_time = current_time
|
|
59
|
+
else:
|
|
60
|
+
# 押されている -> 離された(離した瞬間)
|
|
61
|
+
released_duration = current_time - self.press_start_time
|
|
62
|
+
self.press_start_time = 0.0
|
|
63
|
+
|
|
64
|
+
# 現在押しっぱなしにしている時間の計算(リアルタイム取得用)
|
|
65
|
+
if self.last_state and self.press_start_time > 0:
|
|
66
|
+
current_held_time = current_time - self.press_start_time
|
|
67
|
+
|
|
68
|
+
return just_pressed, released_duration, current_held_time
|
|
69
|
+
|
|
70
|
+
def __enter__(self):
|
|
71
|
+
return self
|
|
72
|
+
|
|
73
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
74
|
+
self.close()
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
def close(self):
|
|
78
|
+
TactileButton._use_count -= 1
|
|
79
|
+
if TactileButton._use_count <= 0 and TactileButton._handle is not None:
|
|
80
|
+
lgpio.gpiochip_close(TactileButton._handle)
|
|
81
|
+
TactileButton._handle = None
|
|
82
|
+
|
|
83
|
+
# ---------------------------------------------------------
|
|
84
|
+
# 単体テスト用ブロック
|
|
85
|
+
# ---------------------------------------------------------
|
|
86
|
+
if __name__ == '__main__':
|
|
87
|
+
TEST_PIN = 17
|
|
88
|
+
print(f"GPIO {TEST_PIN} 長押しテスト (Ctrl+Cで終了)")
|
|
89
|
+
btn = TactileButton(pin=TEST_PIN)
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
while True:
|
|
93
|
+
# 🌟 update() を呼ぶだけで、欲しい情報がすべて手に入る
|
|
94
|
+
just_pressed, released_duration, held_time = btn.update()
|
|
95
|
+
|
|
96
|
+
# ① 押した瞬間
|
|
97
|
+
if just_pressed:
|
|
98
|
+
print("🔴 カチッ! (押下開始)")
|
|
99
|
+
|
|
100
|
+
# ② 押しっぱなしにしている最中(例: 3秒を超えたら発動)
|
|
101
|
+
if held_time > 0:
|
|
102
|
+
print(f" ⏳ 押しています... {held_time:.1f}秒", end="\r")
|
|
103
|
+
if held_time >= 3.0:
|
|
104
|
+
print("\n💥 3秒長押し発動! (リセットします)")
|
|
105
|
+
btn.press_start_time = time.time() # カウントをリセット
|
|
106
|
+
|
|
107
|
+
# ③ 離した瞬間(合計で何秒押されていたかが分かる)
|
|
108
|
+
if released_duration > 0:
|
|
109
|
+
print(f"\n🟢 パッ! ({released_duration:.2f} 秒間 押されていました)")
|
|
110
|
+
|
|
111
|
+
time.sleep(0.01)
|
|
112
|
+
except KeyboardInterrupt:
|
|
113
|
+
pass
|
|
114
|
+
finally:
|
|
115
|
+
btn.close()
|