test_reed_switch.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. #!/usr/bin/env python3
  2. """
  3. Simple test script to verify reed switch functionality.
  4. Run this script on your Raspberry Pi to test the reed switch.
  5. Usage:
  6. python test_reed_switch.py [--gpio PIN] [--invert]
  7. Arguments:
  8. --gpio PIN GPIO pin number (BCM numbering) to test (default: 18)
  9. --invert Invert the switch logic (triggered = LOW instead of HIGH)
  10. Examples:
  11. python test_reed_switch.py # Test GPIO 18 (default, normal logic)
  12. python test_reed_switch.py --gpio 17 # Test GPIO 17 (normal logic)
  13. python test_reed_switch.py --gpio 22 --invert # Test GPIO 22 (inverted logic)
  14. """
  15. import time
  16. import sys
  17. import argparse
  18. try:
  19. from modules.connection.reed_switch import ReedSwitchMonitor
  20. except ImportError:
  21. print("Error: Could not import ReedSwitchMonitor")
  22. print("Make sure you're running this from the dune-weaver directory")
  23. sys.exit(1)
  24. def main(gpio_pin=18, invert_state=False):
  25. """
  26. Test the reed switch on the specified GPIO pin.
  27. Args:
  28. gpio_pin: GPIO pin number (BCM numbering) to test
  29. invert_state: If True, invert the switch logic (triggered = LOW)
  30. """
  31. print("=" * 60)
  32. print(f"Reed Switch Test - GPIO {gpio_pin}")
  33. if invert_state:
  34. print("(Inverted Logic: Triggered = LOW)")
  35. else:
  36. print("(Normal Logic: Triggered = HIGH)")
  37. print("=" * 60)
  38. print()
  39. # Initialize the reed switch monitor
  40. print(f"Initializing reed switch monitor on GPIO {gpio_pin}...")
  41. if invert_state:
  42. print("Using inverted logic (triggered when pin is LOW)")
  43. else:
  44. print("Using normal logic (triggered when pin is HIGH)")
  45. reed_switch = ReedSwitchMonitor(gpio_pin=gpio_pin, invert_state=invert_state)
  46. # Check if we're on a Raspberry Pi
  47. if not reed_switch.is_raspberry_pi:
  48. print("❌ ERROR: Not running on a Raspberry Pi!")
  49. print("This test must be run on a Raspberry Pi with GPIO support.")
  50. return
  51. print("✓ Running on Raspberry Pi")
  52. print("✓ GPIO initialized successfully")
  53. print()
  54. print("=" * 60)
  55. print("MONITORING REED SWITCH")
  56. print("=" * 60)
  57. print()
  58. print("Instructions:")
  59. print(" • The reed switch should be connected:")
  60. print(f" - One terminal → GPIO {gpio_pin}")
  61. if invert_state:
  62. print(" - Other terminal → Ground (for inverted logic)")
  63. print(" - Pull-up resistor enabled internally")
  64. else:
  65. print(" - Other terminal → 3.3V (for normal logic)")
  66. print(" - Or use internal pull-up and connect to ground")
  67. print()
  68. print(" • Bring a magnet close to the reed switch to trigger it")
  69. print(" • You should see 'TRIGGERED!' when the switch closes")
  70. print(" • Press Ctrl+C to exit")
  71. print()
  72. print("-" * 60)
  73. try:
  74. last_state = None
  75. trigger_count = 0
  76. while True:
  77. # Check if reed switch is triggered
  78. is_triggered = reed_switch.is_triggered()
  79. # Only print when state changes (to avoid spam)
  80. if is_triggered != last_state:
  81. if is_triggered:
  82. trigger_count += 1
  83. print(f"🔴 TRIGGERED! (count: {trigger_count})")
  84. else:
  85. print("⚪ Not triggered")
  86. last_state = is_triggered
  87. # Small delay to avoid overwhelming the GPIO
  88. time.sleep(0.05)
  89. except KeyboardInterrupt:
  90. print()
  91. print("-" * 60)
  92. print(f"✓ Test completed. Reed switch was triggered {trigger_count} times.")
  93. print()
  94. finally:
  95. # Clean up GPIO
  96. reed_switch.cleanup()
  97. print("✓ GPIO cleaned up")
  98. print()
  99. if __name__ == "__main__":
  100. # Parse command-line arguments
  101. parser = argparse.ArgumentParser(
  102. description="Test reed switch functionality on Raspberry Pi GPIO pins",
  103. formatter_class=argparse.RawDescriptionHelpFormatter,
  104. epilog="""
  105. Examples:
  106. python test_reed_switch.py # Test GPIO 18 (normal logic)
  107. python test_reed_switch.py --gpio 17 # Test GPIO 17 (normal logic)
  108. python test_reed_switch.py --gpio 22 --invert # Test GPIO 22 (inverted logic)
  109. Note: Uses BCM GPIO numbering (not physical pin numbers)
  110. Normal logic: Triggered when HIGH (connected to 3.3V)
  111. Inverted logic: Triggered when LOW (connected to ground)
  112. """
  113. )
  114. parser.add_argument(
  115. '--gpio',
  116. type=int,
  117. default=18,
  118. metavar='PIN',
  119. help='GPIO pin number to test (BCM numbering, default: 18)'
  120. )
  121. parser.add_argument(
  122. '--invert',
  123. action='store_true',
  124. help='Invert the switch logic (triggered = LOW instead of HIGH)'
  125. )
  126. args = parser.parse_args()
  127. # Validate GPIO pin range
  128. if args.gpio < 2 or args.gpio > 27:
  129. print(f"❌ ERROR: GPIO pin must be between 2 and 27 (got {args.gpio})")
  130. print("Valid GPIO pins: 2-27 (BCM numbering)")
  131. sys.exit(1)
  132. # Run the test
  133. main(gpio_pin=args.gpio, invert_state=args.invert)