Motoron Motor Controller library for Raspberry Pi
Loading...
Searching...
No Matches
mpy_i2c_robust_example.py
1# This example shows how to control the Motoron Motor Controller
2# I2C interface using the machine.I2C class in MicroPython if you want
3# your system to just keep working, ignoring or automatically recovering from
4# errors as much as possible.
5#
6# The motors will stop but automatically recover if:
7# - Motor power (VIN) is interrupted
8# - A motor fault occurs
9# - The Motoron experiences a reset
10# - A command timeout occurs
11#
12# Errors reported by the machine.I2C class are caught so they
13# do not cause the program to terminate.
14
15import time
16import motoron
17from machine import I2C, Pin
18
19bus = I2C(0, scl=Pin(5), sda=Pin(4))
20mc = motoron.MotoronI2C(bus=bus)
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 as e:
42 print("Error: motors_init:", e)
43
44 last_time_motors_init = time.ticks_ms()
45
46try:
47 mc.reinitialize()
48except OSError:
49 pass
50
51motors_init()
52
53while True:
54 try:
55 if time.ticks_ms() & 2048:
56 mc.set_speed(1, 800)
57 else:
58 mc.set_speed(1, -800)
59 mc.set_speed(2, 100)
60 mc.set_speed(3, -100)
61 except OSError:
62 pass
63
64 # Every 2000 ms, run motors_init to restart the motors
65 # in case anything has caused them to shut down.
66 if time.ticks_ms() - last_time_motors_init > 2000:
67 motors_init()
Represents an I2C connection to a Pololu Motoron Motor Controller.
Definition: motoron.py:1665