11import gpiozero
2+ import logging
3+ from gpiozero .pins .pigpio import PiGPIOFactory
4+ from gpiozero import Device
5+
6+ # Configure logging for debugging
7+ logging .basicConfig (level = logging .DEBUG )
8+
9+ # Set the pin factory to pigpio (optional, for sharing GPIO pins between processes)
10+ Device .pin_factory = PiGPIOFactory ()
211
312class MotorController :
413 def __init__ (self , pins ):
5- self .motor_a = gpiozero .PWMOutputDevice (pins [0 ])
6- self .motor_b = gpiozero .PWMOutputDevice (pins [1 ])
7- self .motor_c = gpiozero .PWMOutputDevice (pins [2 ])
8- self .motor_d = gpiozero .PWMOutputDevice (pins [3 ])
14+ """
15+ Initialize the MotorController with a list of GPIO pins.
16+ Each pin should be unique to avoid conflicts.
17+ """
18+ # Ensure that no pin conflicts exist and that each pin is used once
19+ if len (set (pins )) != len (pins ):
20+ raise ValueError ("Pins must be unique. Duplicate pins found." )
21+
22+ logging .debug (f"Initializing MotorController with pins: { pins } " )
23+
24+ try :
25+ # Initialize PWMOutputDevice for each motor
26+ self .motor_a = gpiozero .PWMOutputDevice (pins [0 ])
27+ self .motor_b = gpiozero .PWMOutputDevice (pins [1 ])
28+ self .motor_c = gpiozero .PWMOutputDevice (pins [2 ])
29+ self .motor_d = gpiozero .PWMOutputDevice (pins [3 ])
30+
31+ logging .debug ("MotorController initialized successfully." )
32+ except gpiozero .GPIOPinInUse as e :
33+ logging .error (f"GPIO pin conflict detected: { e } " )
34+ raise
35+ except Exception as e :
36+ logging .error (f"An error occurred while initializing motors: { e } " )
37+ raise
938
1039 def set_speed (self , duty_cycle ):
11- self .motor_a .value = duty_cycle [0 ]
12- self .motor_b .value = duty_cycle [1 ]
13- self .motor_c .value = duty_cycle [2 ]
14- self .motor_d .value = duty_cycle [3 ]
40+ """
41+ Set the speed of all motors using a list of duty cycles.
42+ :param duty_cycle: List of duty cycles for each motor (e.g., [0.5, 0.5, 0.5, 0.5])
43+ """
44+ if len (duty_cycle ) != 4 :
45+ raise ValueError ("Duty cycle list must contain exactly 4 values." )
46+
47+ try :
48+ # Set the duty cycle for each motor
49+ self .motor_a .value = duty_cycle [0 ]
50+ self .motor_b .value = duty_cycle [1 ]
51+ self .motor_c .value = duty_cycle [2 ]
52+ self .motor_d .value = duty_cycle [3 ]
53+
54+ logging .debug (f"Motor speeds set to: { duty_cycle } " )
55+ except Exception as e :
56+ logging .error (f"An error occurred while setting motor speeds: { e } " )
57+ raise
0 commit comments