範例:GPIO 脈衝寬度觸發
Protocol Exerciser 可在支援的接腳上武裝 GPIO 脈衝寬度觸發,並在量測到的脈衝符合設定規則時送出全域事件。使用 AqProtocolExerciser.set_gpio_trigger 武裝硬體,並為事件名稱 gpio_trigger 註冊處理函式。Payload 位於 PxEventMsg.global_event.gpio_trigger,型別為 PxGpioTriggerEvent(見 aqpxlib.gpio 或 aqpxlib.event)。
限制¶
- 接腳: 脈衝寬度觸發與脈衝產生僅支援 GPIO 索引 8 與 9(與
send_gpio_pulse相同)。 - 持續時間:
min_duration_ns與max_duration_ns都必須大於 5 ns 且小於 1 s。 - 事件: 在 exerciser session 上為邏輯名稱
gpio_trigger註冊處理函式。這是全域事件,不是裝置層級事件。
設定觸發¶
呼叫 set_gpio_trigger,參數如下: | 引數 | 意義 |
| -------- | ------- |
| gpio_idx | 接腳索引(8 或 9)。 |
| min_duration_ns / max_duration_ns | 脈衝寬度視窗,單位奈秒。 |
| low_pulse | 為 True 時考慮低準位脈衝。 |
| high_pulse | 為 True 時考慮高準位脈衝。 |
| mode | PxGpioWidthTriggerMode.TRIGGER_PULSE_WIDTH_IN_RANGE(預設)或 TRIGGER_PULSE_WIDTH_OUT_OF_RANGE。 |
mode 決定寬度落在 [min, max] 之內或之外時是否觸發。
處理 gpio_trigger¶
處理函式收到 PxEventMsg.Payload 位於 global_event.gpio_trigger(PxGpioTriggerEvent):
| 欄位 | 型別 | 意義 |
|---|---|---|
pin_idx |
int |
造成觸發的接腳索引。 |
pulse_duration |
int |
量測到的寬度(奈秒)。 |
pulse_polarity |
bool |
偵測到的脈衝極性。 |
範例¶
下列腳本在接腳 8 武裝範圍內觸發、註冊處理函式,再用 send_gpio_pulse 發出短脈衝讓處理函式執行。若由外部設備驅動該接腳,請自行替換脈衝呼叫。
run_gpio_trigger_example.py
import logging
import threading
from aqpxlib import AqProtocolExerciser, PxGpioWidthTriggerMode, PxIoState
from aqpxlib.event import PxEventMsg
logger = logging.getLogger(__name__)
def run_gpio_trigger_example() -> None:
with AqProtocolExerciser.connect(port=60600) as px:
done = threading.Event()
def on_gpio_trigger(event_msg: PxEventMsg) -> None:
g = event_msg.global_event.gpio_trigger
logger.info(
"GPIO trigger: pin=%d duration_ns=%d polarity=%s",
g.pin_idx,
g.pulse_duration,
g.pulse_polarity,
)
done.set()
px.add_event_handler("gpio_trigger", on_gpio_trigger)
pin = 8
px.set_gpio_trigger(
gpio_idx=pin,
min_duration_ns=500,
max_duration_ns=50_000,
low_pulse=True,
high_pulse=True,
mode=PxGpioWidthTriggerMode.TRIGGER_PULSE_WIDTH_IN_RANGE,
)
px.send_gpio_pulse(
gpio_idx=pin,
active_state=PxIoState.HIGH,
idle_state=PxIoState.LOW,
active_time_ns=5000,
)
assert done.wait(timeout=3), "GPIO trigger event not received"
if __name__ == "__main__":
logging.basicConfig(format="[%(levelname)s] %(message)s")
logger.setLevel(logging.INFO)
run_gpio_trigger_example()
執行:
另見¶
- GPIO 讀取、驅動與脈衝 —
get_gpio_state、set_gpio_state、send_gpio_pulse - GPIO (API) — 型別與 exerciser 方法的 mkdocstrings 參考
- 事件註冊與處理函式設定 — 裝置事件與全域事件