Enhance CAN bus scripts with argparse and error handling

- Improved error handling in `python_enable_motor.py` by capturing and displaying exception details.
- Ensured proper CAN bus shutdown in `python_enable_motor.py` with a `finally` block.
- Refactored `python_send_angle.py` to accept a command-line argument for the target angle instead of looping indefinitely.
- Refactored `python_send_velocity.py` to accept a command-line argument for target speed and removed infinite loops for better usability.
- Added `send_velocity_impulses.py`, a new script to send alternating velocity impulses over the CAN bus.
This commit is contained in:
Ilya Uraev 2025-02-04 13:41:05 +03:00
parent d5f772cb6d
commit 74c5b1d12c
4 changed files with 64 additions and 17 deletions

View file

@ -20,12 +20,13 @@ def send_motor_enable(bus, enable):
state = "enabled" if enable else "disabled"
print(f"Sent message to {state} motor")
print(f"Message data: {msg.data}")
except can.CanError:
print("Message failed to send")
except can.CanError as e:
print(f"Message failed to send: {e}")
sys.exit(1) # Exit the program on failure
def main():
# CAN interface setup
bus = None # Define outside the try block for proper shutdown
try:
bus = can.interface.Bus(channel='can0', bustype='socketcan', bitrate=1000000) # Ensure the bitrate matches the microcontroller settings
print("CAN bus initialized.")
@ -43,5 +44,11 @@ def main():
print(f"Error initializing CAN bus: {e}")
sys.exit(1)
finally:
# Ensure the bus is properly shut down
if bus is not None:
bus.shutdown()
print("CAN bus shut down.")
if __name__ == '__main__':
main()