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