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,6 @@
import can
import struct
import time
import argparse
# Function to send the target speed
def send_target_speed(bus, target_speed):
@ -17,18 +17,20 @@ def send_target_speed(bus, target_speed):
except can.CanError:
print("Message failed to send")
# Main function
def main():
parser = argparse.ArgumentParser(description="Send target speed over CAN bus.")
parser.add_argument("--speed", type=float, required=True, help="Target speed to send over the CAN bus (in m/s)")
args = parser.parse_args()
target_speed = args.speed
# 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 speeds...")
print("CAN bus initialized, sending target speed...")
# Target speed
target_speed = 0.0 # in meters per second
# Loop to send messages
while True:
send_target_speed(bus, target_speed)
time.sleep(1) # Delay before sending the next message
# Send the message once
send_target_speed(bus, target_speed)
if __name__ == '__main__':
main()