Motoron Motor Controller library for Raspberry Pi
Loading...
Searching...
No Matches
mpy_i2c_simple_no_library_example.py
1# This example shows a simple way to control the Motoron Motor Controller
2# I2C interface using the machine.I2C class in MicroPython, without using
3# the Motoron library.
4
5import math
6import time
7from machine import I2C, Pin
8
9bus = I2C(0, scl=Pin(5), sda=Pin(4))
10address = 16
11
12def i2c_write(cmd):
13 bus.writeto(address, bytes(cmd))
14
15def set_max_acceleration(motor, accel):
16 i2c_write([
17 0x9C, motor, 10, accel & 0x7F, (accel >> 7) & 0x7F,
18 0x9C, motor, 12, accel & 0x7F, (accel >> 7) & 0x7F])
19
20def set_max_deceleration(motor, decel):
21 i2c_write([
22 0x9C, motor, 14, decel & 0x7F, (decel >> 7) & 0x7F,
23 0x9C, motor, 16, decel & 0x7F, (decel >> 7) & 0x7F])
24
25def set_speed(motor, speed):
26 i2c_write([0xD1, motor, speed & 0x7F, (speed >> 7) & 0x7F])
27
28i2c_write([
29 # Reset the controller to its default settings using a "Reinitialize" command.
30 0x96, 0x74,
31
32 # Disable CRC using a "Set protocol options" command.
33 0x8B, 0x04, 0x7B, 0x43,
34
35 # Clear the reset flag using a "Clear latched status flags" command.
36 0xA9, 0x00, 0x04,
37])
38
39# By default, the Motoron is configured to stop the motors if it does not get
40# a motor control command for 1500 ms. Uncomment a block of code below to
41# adjust this time or disable the timeout feature.
42
43# Change the command timeout using a "Set Variable" command.
44# The maximmum timeout allowed is 65000 ms.
45# timeout_ms = 1000
46# timeout = math.ceil(timeout_ms / 4)
47# i2c_write([0x9C, 0, 5, timeout & 0x7F, (timeout >> 7) & 0x7F])
48
49# Disable the command timeout by using a "Set variable" command to clear
50# the command timeout bit in the error mask.
51# i2c_write([0x9C, 0, 8, 0, 4])
52
53# Configure motor 1
54set_max_acceleration(1, 140)
55set_max_deceleration(1, 300)
56
57# Configure motor 2
58set_max_acceleration(2, 200)
59set_max_deceleration(2, 300)
60
61# Configure motor 3
62set_max_acceleration(3, 80)
63set_max_deceleration(3, 300)
64
65while True:
66 if time.ticks_ms() & 2048:
67 set_speed(1, 800)
68 else:
69 set_speed(1, -800)
70
71 set_speed(2, 100)
72 set_speed(3, -100)
73
74 time.sleep(0.005)