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