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

@ -1,6 +1,7 @@
import can
import struct
import time
import argparse
# Function to send the target angle
def send_target_angle(bus, target_angle):
@ -17,18 +18,20 @@ def send_target_angle(bus, target_angle):
except can.CanError:
print("Message failed to send")
# Main function
def main():
parser = argparse.ArgumentParser(description="Send target angles over CAN bus.")
parser.add_argument("--angle", type=float, required=True, help="Target angle to send over the CAN bus")
args = parser.parse_args()
target_angle = args.angle
# CAN interface setup
bus = can.interface.Bus(channel='can0', bustype='socketcan', bitrate=1000000) # Ensure the bitrate matches the microcontroller settings
print("CAN bus initialized, sending target angles...")
# Target angle
target_angle = 0.0
# Loop to send messages
while True:
send_target_angle(bus, target_angle)
time.sleep(1) # Delay before sending the next message
send_target_angle(bus, target_angle)
if __name__ == '__main__':
main()