|
| 1 | +#!/usr/bin/env python3 |
| 2 | +''' |
| 3 | +demonstrate servo monitoring and servo control |
| 4 | +the selected servo will be given sinisoidal control while printing position |
| 5 | +''' |
| 6 | + |
| 7 | +import dronecan |
| 8 | +import time |
| 9 | +import math |
| 10 | +from dronecan import uavcan |
| 11 | + |
| 12 | +# get command line arguments |
| 13 | +from argparse import ArgumentParser |
| 14 | +parser = ArgumentParser(description='test servo actuators') |
| 15 | +parser.add_argument("port", default=None, help="CAN URI") |
| 16 | +parser.add_argument("--bitrate", default=1000000, type=int, help="CAN bit rate") |
| 17 | +parser.add_argument("--node-id", default=125, type=int, help="CAN node ID") |
| 18 | +parser.add_argument("--target-node-id", default=100, type=int, help="target CAN node ID") |
| 19 | +parser.add_argument("--rate", default=20, type=float, help="servo update rate") |
| 20 | +parser.add_argument("--freq", default=1, type=float, help="servo sinisoid frequency") |
| 21 | +parser.add_argument("--actuator-min", default=-1, type=float, help="actuator min") |
| 22 | +parser.add_argument("--actuator-max", default=1, type=float, help="actuator max") |
| 23 | +parser.add_argument("--actuator-id", default=1, type=float, help="actuator ID") |
| 24 | + |
| 25 | +args = parser.parse_args() |
| 26 | + |
| 27 | +port = args.port |
| 28 | + |
| 29 | +# Initializing a DroneCAN node instance. |
| 30 | +node = dronecan.make_node(port, node_id=args.node_id, bitrate=args.bitrate) |
| 31 | + |
| 32 | +def handle_actuator_status(msg): |
| 33 | + '''handle actuator status message''' |
| 34 | + print(dronecan.to_yaml(msg)) |
| 35 | + |
| 36 | +def control_actuator(): |
| 37 | + '''control for actuator, called at rate Hz''' |
| 38 | + t = time.time() |
| 39 | + sint = math.sin(t * args.freq * math.pi * 2) |
| 40 | + amplitude = 0.5 * (args.actuator_max-args.actuator_min) |
| 41 | + mid = args.actuator_min + amplitude |
| 42 | + v = mid + sint * amplitude |
| 43 | + |
| 44 | + req = uavcan.equipment.actuator.ArrayCommand() |
| 45 | + cmd = uavcan.equipment.actuator.Command() |
| 46 | + cmd.actuator_id = args.actuator_id |
| 47 | + cmd.command_type = cmd.COMMAND_TYPE_UNITLESS |
| 48 | + cmd.command_value = v |
| 49 | + req.commands = [ cmd ] |
| 50 | + |
| 51 | + node.broadcast(req) |
| 52 | + |
| 53 | + |
| 54 | +# Subscribe only to actuator status messages |
| 55 | +node.add_handler(uavcan.equipment.actuator.Status, handle_actuator_status) |
| 56 | + |
| 57 | +node.periodic(1.0/args.rate, control_actuator) |
| 58 | + |
| 59 | +while True: |
| 60 | + node.spin() |
0 commit comments