Thuta Learning
ရှာဖွေရန်
IntermediateHardwarebeginner

Reading Input — Buttons & Sensors

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Reading Input — Buttons & Sensors ကို ကြောက်စရာမလိုအောင် နားလည်မယ်
  • ကိုယ်တိုင် hardware wiring/code ကို run ကြည့်တတ်မယ်
  • Real project ထဲမှာ ဒီ concept ကို ချက်ချင်း အသုံးချတတ်မယ်

ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်

Button ကို GPIO pin တစ်ခုနဲ့ ချိတ်ဆက်ထားရင် button press/release ကို code ကနေ detect လုပ်နိုင်ပါတယ် — gpiozero ရဲ့ Button class ကို သုံးရင် .is_pressed (property, true/false) ဒါမှမဟုတ် .when_pressed (callback function, event-driven pattern) ဆိုပြီး နှစ်မျိုး check လုပ်လို့ရပါတယ်။ Event-driven pattern (when_pressed) က loop ထဲမှာ constantly check (polling) မလိုဘဲ, button press ဖြစ်တာနဲ့ function ကို automatic trigger လုပ်ပေးလို့ efficient ပါတယ်။

လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်

Button + LED ပေါင်းစပ်ရင် 'button press ချိန် LED light on' ဆိုတဲ့ classic beginner circuit ရနိုင်ပါတယ် — button.when_pressed = led.on, button.when_released = led.off ဆိုပြီး function reference ကို တိုက်ရိုက် assign လုပ်ရုံနဲ့ ရပါတယ် (gpiozero ရဲ့ syntax convenience ပါ)။ Temperature/humidity sensor (DHT11/DHT22) လိုမျိုး analog sensor တွေကတော့ dedicated library (Adafruit_DHT) လိုအပ်ပါတယ်, GPIO digital read/write ထက် ပိုရှုပ်ထွေးပါတယ်။

အတူတူ ကြည့်မယ်

python
from gpiozero import LED, Button
from signal import pause

led = LED(17)
button = Button(2)  # BCM pin 2

button.when_pressed = led.on
button.when_released = led.off

pause()  # keep script running to listen for button events
You should see
Button ကို press ထားနေတဲ့အချိန် LED လင်းနေပြီး, release လိုက်ရင် LED ပျောက်သွားမည်။

၅ မိနစ် စမ်းကြည့်

Button + LED circuit ကို wiring ပြီး (ရှိရင်), when_pressed/when_released event ဖြင့် code ကို ကိုယ်တိုင် ရေးကြည့်ပါ။

သတိလေးတစ်ချက်

when_pressed = led.on() (function ကို ချက်ချင်းခေါ်) vs when_pressed = led.on (function reference) ကွာခြားချက်ကို သတိထားပါ — parentheses ပါ/မပါက Python ရဲ့ common beginner mistake တစ်ခုပါ။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Button ကို pull-up/pull-down resistor concept နားမလည်ဘဲ ချိတ်ပြီး floating pin (random on/off) ဖြစ်ခြင်း — gpiozero ရဲ့ Button class က default internal pull-up ကို auto-handle လုပ်ပေးပါတယ်
  • when_pressed = led.on() (parentheses ပါ) လို ရေးမိပြီး function ကို ချက်ချင်းခေါ်လိုက်ခြင်း — parentheses မပါဘဲ function reference ကိုပဲ assign ရမည်

အခု ကိုယ်တိုင် စမ်းကြည့်

Button + LED circuit ကို wiring ပြီး (ရှိရင်), when_pressed/when_released event ဖြင့် code ကို ကိုယ်တိုင် ရေးကြည့်ပါ။

You'll know it worked when: Button ကို press ထားနေတဲ့အချိန် LED လင်းနေပြီး, release လိုက်ရင် LED ပျောက်သွားမည်။

Reading Input — Buttons & Sensors | Thuta Learning