User Switch

Lab 2: User Switch — อ่านปุ่มกด & Debounce

วัตถุประสงค์

  • GPIO Input: อ่านค่าจาก Digital Input

  • Debounce: ป้องกันการอ่านค่าผิดพลาดจาก Contact Bounce

  • State Machine: เปลี่ยน LED state เมื่อกดปุ่ม

จะได้เรียนรู้อะไร?

  • GPIO Read: Cy_GPIO_Read()

  • Active LOW: ปุ่มกดลง = 0

  • Debounce Pattern: Software debounce

  • Static Variables: เก็บ state ระหว่าง function calls

Hardware Information

Component
Port/Pin
หมายเหตุ

User LED1

CYBSP_USER_LED1

Active HIGH (HIGH = ON)

User Button 1 (SW2)

CYBSP_USER_BTN1

Active LOW (กดลง = 0)

User Button 2 (SW4)

CYBSP_USER_BTN2

Active LOW (กดลง = 0)


Lab 2.1 : อ่านปุ่มกดแบบ Polling

เพิ่ม Button Macros:

แก้ไขฟังก์ชั่น Main :


Lab 2.2 : Debounce แบบง่าย (Edge Detection)

WHY: ทำไมต้องรู้?

  • ปัญหา: ปุ่มกดมีสัญญาณกระเด้ง (bouncing) ทำให้ detect หลายครั้ง (5-10 ครั้ง!)

  • ประโยชน์: อ่านค่าปุ่มได้ถูกต้อง, ไม่มี false triggers

  • Hardware: Mechanical switch มี contact bounce 10-50ms

CAUTION: ข้อควรระวัง

ข้อผิดพลาด
ผลกระทบ
วิธีป้องกัน

Delay สั้นเกินไป

ยัง bounce อยู่

ใช้ 20-50ms

Delay นานเกินไป

ผู้ใช้รู้สึกว่า laggy

ไม่ควรเกิน 100ms

Debounce ใน ISR

Block interrupt นาน

ใช้ timer-based debounce

เพิ่ม Button Macros

สร้างฟังก์ชัน Debounce

แก้ไข Main Loop

Debounce Flowchart


ทำความเข้าใจการเรียกใช้ Static Variables

✍️ Exercise

1. Press Counter : นับจำนวนครั้งที่กดปุ่มและแสดงผล

  1. Long Press Detection : ตรวจจับการกดค้าง (> 1 วินาที) และทำ action แตกต่าง


Last updated

Was this helpful?