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