Motoron Motor Controller library for Raspberry Pi
Loading...
Searching...
No Matches
i2c_robust_example.py
1#!/usr/bin/env python3
2
3# This example shows how to control the Motoron Motor Controller if you want
4# your system to just keep working, ignoring or automatically recovering from
5# 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 I2C library are caught so they
14# do not cause the program to terminate.
15
16import sys
17import time
18import motoron
19
21
22def motors_init():
23 global last_time_motors_init
24 try:
25 mc.clear_reset_flag()
26
27 # Configure motor 1
28 mc.set_max_acceleration(1, 70)
29 mc.set_max_deceleration(1, 150)
30
31 # Configure motor 2
32 mc.set_max_acceleration(2, 100)
33 mc.set_max_deceleration(2, 150)
34
35 # Configure motor 3
36 mc.set_max_acceleration(3, 40)
37 mc.set_max_deceleration(3, 150)
38
39 mc.clear_motor_fault_unconditional()
40
41 except (OSError, RuntimeError) as e:
42 print("Error: motors_init:", e, file=sys.stderr)
43
44 last_time_motors_init = time.monotonic()
45
46try:
47 mc.reinitialize()
48except (OSError, RuntimeError):
49 pass
50
51motors_init()
52
53try:
54 while True:
55 try:
56 if int(time.monotonic() * 1000) & 2048:
57 mc.set_speed(1, 800)
58 else:
59 mc.set_speed(1, -800)
60 mc.set_speed(2, 100)
61 mc.set_speed(3, -100)
62 except (OSError, RuntimeError):
63 pass
64
65 # Every 2 seconds, run motors_init to restart the motors
66 # in case anything has caused them to shut down.
67 if time.monotonic() - last_time_motors_init > 2:
68 motors_init()
69
70 time.sleep(0.005)
71
72except KeyboardInterrupt:
73 pass
Represents an I2C connection to a Pololu Motoron Motor Controller.
Definition: motoron.py:1665