Loading [MathJax]/extensions/tex2jax.js
Motoron Motor Controller library for Raspberry Pi
All Classes Files Functions Variables Pages
serial_robust_example.py
1#!/usr/bin/env python3
2
3# This example shows how to control the Motoron Motor Controller via serial
4# if you want your system to just keep working, ignoring or automatically
5# recovering from errors as much as possible.
6#
7# The motors will stop but automatically recover if:
8# - Motor power (VIN) is interrupted
9# - A motor fault occurs
10# - The Motoron experiences a reset
11# - A command timeout occurs
12#
13# Errors reported by the underlying Python serial library are caught so they
14# do not cause the program to terminate.
15
16import sys
17import time
18import serial
19import motoron
20
22mc.set_port("/dev/serial0")
23
24def motors_init():
25 global last_time_motors_init
26 try:
27 mc.clear_reset_flag()
28
29 # Configure motor 1
30 mc.set_max_acceleration(1, 70)
31 mc.set_max_deceleration(1, 150)
32
33 # Configure motor 2
34 mc.set_max_acceleration(2, 100)
35 mc.set_max_deceleration(2, 150)
36
37 # Configure motor 3
38 mc.set_max_acceleration(3, 40)
39 mc.set_max_deceleration(3, 150)
40
41 mc.clear_motor_fault_unconditional()
42
43 except (OSError, RuntimeError) as e:
44 print("Error: motors_init:", e, file=sys.stderr)
45
46 last_time_motors_init = time.monotonic()
47
48try:
49 mc.reinitialize()
50except (OSError, RuntimeError):
51 pass
52
53motors_init()
54
55try:
56 while True:
57 try:
58 if int(time.monotonic() * 1000) & 2048:
59 mc.set_speed(1, 800)
60 else:
61 mc.set_speed(1, -800)
62 mc.set_speed(2, 100)
63 mc.set_speed(3, -100)
64 except (OSError, RuntimeError):
65 pass
66
67 # Every 2 seconds, run motors_init to restart the motors
68 # in case anything has caused them to shut down.
69 if time.monotonic() - last_time_motors_init > 2:
70 motors_init()
71
72 time.sleep(0.005)
73
74except KeyboardInterrupt:
75 pass
Represents a serial connection to a Pololu Motoron Motor Controller.
Definition: motoron.py:1761