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()

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()

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()

View file

@ -0,0 +1,35 @@
import can
import struct
import time
# Function to send the target speed
def send_target_speed(bus, target_speed):
msg = can.Message()
msg.arbitration_id = 1 # Message ID
msg.is_extended_id = False
msg.dlc = 5 # Message length
msg.data = [ord('V')] + list(struct.pack('<f', target_speed)) # 'V' for the command identifier, followed by the speed in float format
try:
bus.send(msg)
print(f"Sent message with target speed: {target_speed} m/s")
print(f"Message data: {msg.data}")
except can.CanError:
print("Message failed to send")
# Main function
def main():
# 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 speed impulses...")
# Send impulses of target speed from -2 to 2 m/s
target_speeds = [-1, 1]
while True:
for speed in target_speeds:
send_target_speed(bus, speed)
time.sleep(1) # 1-second delay between messages
if __name__ == '__main__':
main()