mag_to_feeder_moving_sequence.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import time
  2. from robot_control.src.robot.mag_distributor import MagDistributor
  3. from robot_control.src.api.gpio import PiGPIO
  4. from robot_control.src.utils.config import ConfigParser
  5. import asyncio
  6. import time
  7. import sys
  8. import pigpio
  9. # Initialize pigpio directly for stepper controlpython -m playgrounds.mag_to_feeder_moving_sequence
  10. pi = pigpio.pi()
  11. if not pi.connected:
  12. print("Failed to connect to pigpio daemon")
  13. sys.exit(1)
  14. # Stepper pins (BCM)
  15. DIR_PIN = 11
  16. STEP_PIN = 9
  17. EN_PIN = 10
  18. # Set up pins
  19. pi.set_mode(DIR_PIN, pigpio.OUTPUT)
  20. pi.set_mode(STEP_PIN, pigpio.OUTPUT)
  21. pi.set_mode(EN_PIN, pigpio.OUTPUT)
  22. # Enable motor driver (LOW = enabled)
  23. pi.write(EN_PIN, 0)
  24. # Assign two servo pins (update as needed)
  25. SERVO_PINS = {1: 6, 2: 13} # Example: GPIO6 and GPIO13
  26. gpio = PiGPIO([], list(SERVO_PINS.values()))
  27. # Load config and create mag distributor for stepper control
  28. try:
  29. config_parser = ConfigParser()
  30. mag_dist = MagDistributor(config_parser.config, gpio)
  31. except Exception as e:
  32. print(f"Error: Could not initialize mag distributor: {e}")
  33. sys.exit(1)
  34. def move_servo(servo_number, angle, speed):
  35. """Move servo using PiGPIO's smooth function"""
  36. pin = SERVO_PINS.get(servo_number)
  37. if pin is None:
  38. print(f"Servo {servo_number} not configured.")
  39. return False
  40. print(f"S {servo_number} {angle} {speed} - Moving servo {servo_number} (GPIO {pin}) to {angle}° at speed {speed}")
  41. try:
  42. gpio.set_servo_angle_smooth(pin, angle, speed)
  43. print("Servo move complete.")
  44. return True
  45. except Exception as e:
  46. print(f"Error moving servo: {e}")
  47. return False
  48. def move_stepper(pos_mm, rot_deg, speed): # Increased default from 100 to 300 mm/min
  49. """Move stepper motor using mag distributor"""
  50. print(f"M {pos_mm} {rot_deg} {speed if speed else ''} - Moving stepper to position {pos_mm}mm, rotation {rot_deg}° at {speed} mm/min")
  51. try:
  52. if speed is not None:
  53. # Convert speed to step delay if needed
  54. step_delay = mag_dist._speed_to_step_delay(speed)
  55. mag_dist.move_mag_distributor_at_pos(pos_mm, rot_deg, 1000, step_delay)
  56. else:
  57. mag_dist.move_mag_distributor_at_pos(pos_mm, rot_deg)
  58. print("Stepper move complete.")
  59. return True
  60. except Exception as e:
  61. print(f"Error moving stepper: {e}")
  62. return False
  63. async def home_system():
  64. """Home the mag distributor system"""
  65. print("H - Starting homing sequence...")
  66. try:
  67. await mag_dist.home()
  68. print("Homing completed successfully.")
  69. return True
  70. except Exception as e:
  71. print(f"Homing failed: {e}")
  72. return False
  73. def execute_sequence():
  74. """Execute the predefined sequence of movements"""
  75. print("Starting Mag_to_Dist_to_Rob sequence...")
  76. print("=" * 50)
  77. # Define the sequence of commands (including homing at the start)
  78. commands = [
  79. ("S", 1, 60, 1000), # S 1 40 1000
  80. ("H",), # Homing sequence
  81. ("M", 298, 60, 700), # M -223 0 200 (increased speed from 100 to 200)
  82. ("S", 1, 5, 200), # S 1 0 250
  83. ("S", 1, 60, 250), # S 1 40 250
  84. ("M", 46, 60, 700), # M -46 0 150 (increased speed from 100 to 150)
  85. ("S", 2, 15, 500), # S 2 35 250
  86. ("S", 1, 153, 200), # S 1 153 200
  87. ("S", 2, 88, 500), # S 2 90 1000
  88. ("S", 2, 130, 150), # S 2 120 150
  89. ("S", 1, 60, 1000), # S 1 40 1000
  90. # Defeeder pos -6 angle 120
  91. ]
  92. success_count = 0
  93. total_commands = len(commands)
  94. for i, command in enumerate(commands, 1):
  95. print(f"\nStep {i}/{total_commands}:")
  96. if command[0] == "H": # Homing command
  97. success = asyncio.run(home_system())
  98. elif command[0] == "S": # Servo command
  99. _, servo_num, angle, speed = command
  100. success = move_servo(servo_num, angle, speed)
  101. elif command[0] == "M": # Motor/stepper command
  102. _, pos_mm, rot_deg, speed = command
  103. success = move_stepper(pos_mm, rot_deg, speed)
  104. else:
  105. print(f"Unknown command type: {command[0]}")
  106. success = False
  107. if success:
  108. success_count += 1
  109. else:
  110. print(f"Command {i} failed!")
  111. response = input("Continue with next command? (y/n): ").strip().lower()
  112. if response != 'y':
  113. print("Sequence aborted by user.")
  114. break
  115. # Wait 1 second between commands (except for the last one)
  116. if i < total_commands:
  117. print("Waiting 1 second...")
  118. time.sleep(2)
  119. print("\n" + "=" * 50)
  120. print(f"Sequence completed: {success_count}/{total_commands} commands successful")
  121. return success_count == total_commands
  122. def main():
  123. """Main function"""
  124. print("Mag_to_Dist_to_Rob - Automated Movement Sequence with Homing")
  125. print("This script will execute a predefined sequence starting with homing.")
  126. print("\nSequence includes:")
  127. print("1. Homing sequence (H)")
  128. print("2. Servo and stepper movements as specified")
  129. print("\nPress Enter to start the sequence, or Ctrl+C to exit...")
  130. try:
  131. input()
  132. success = execute_sequence()
  133. if success:
  134. print("\n✓ All movements completed successfully!")
  135. else:
  136. print("\n⚠ Some movements failed. Check the output above.")
  137. except KeyboardInterrupt:
  138. print("\n\nSequence interrupted by user.")
  139. except Exception as e:
  140. print(f"\nUnexpected error: {e}")
  141. finally:
  142. # Cleanup
  143. try:
  144. # Disable motor driver
  145. pi.write(EN_PIN, 1)
  146. pi.stop()
  147. gpio.cleanup()
  148. print("GPIO cleanup completed.")
  149. except:
  150. pass
  151. if __name__ == "__main__":
  152. main()