Mantis Rover
  • πŸ”‘Mantis Rover Documentation
  • Supported Devices
  • Assembly Guide
    • πŸ“ΊVideo Tutorials
    • πŸ“°Printed Instructions
      • Wheel Assembly using Improved Coupler
    • πŸ“Ί3D CAD Model
    • πŸ“Ί3D Model File Download
    • πŸ“ΊPacking Guide
    • 🚫General Care/Precautions
    • 🚫Charging your Rover
  • 3D Printing
    • 🐺Designing your Part (TinkerCAD)
    • 🐺MODi Adapter 3D Print
    • ⌚Printing your Part
  • PWM Control
    • πŸ€–PWM Controls-Scratch
    • πŸš—PWM Setup-JavaScript
    • πŸš—Man-In-The-Loop Obstacle Avoidance Tutorial-JavaScript
    • πŸš•PWM Motor Drive-Python
  • MODI Sensor
    • Product Specification Sheet
    • Quick Start Guide
    • MODi Cart Experiment (Bonus)
    • πŸ€–MODi Data-Scratch
    • πŸ€–MODi CSV-Scratch
    • πŸš—MODi LIDAR Obstacle Avoidance-JavaScript
    • 🍊MODi LIDAR Obstacle Avoidance-Scratch
  • Motor Hat Module
    • Product Specification Sheet
    • Quick Start Guide
  • πŸ†˜Support
Powered by GitBook
On this page
  • Python Motor Drive Tutorial
  • Overview
  • Motor Drive Python Files
  • bleak library
  • bluettoothinputpy.py
  • bluettoothinputpy.py Breakdown
  • IDE

Was this helpful?

  1. PWM Control

PWM Motor Drive-Python

Python Motor Drive Tutorial

Learn how to command the motors using the Motor Hat provided in your Rover kit. This guide demonstrates how to send PWM commands to the Motor Hat over BLE using the Python Programming language. Visit here to download an IDE for your specific computer and operating system (OS).

Overview

In this guide you will learn how to manipulate and control the Rover based on the following basic concepts:

  1. How to generate PWM commands for the ROVER.

  2. Understand how the different PWM settings affect motor drive and direction.

  3. The different parts of motordrive.py.

In order for this program to work, the host machine must have a working BLE radio that supports Bluetooth 4.0.

Motor Drive Python Files

If you choose to Download the following zip file and you will find 2 files:

bleak library

  • This library must be installed first https://github.com/hbldh/bleak

  • From the command prompt run: Run β€œpip install bleak”

bluettoothinputpy.py

  • This module contains the underlying BLE communications.

  • You will need to identify the MAC address of your Motor Hat before running this program. When connecting to your sensor, the MAC addess follow MTH_. So in the exmple below, the sensor's name is MTH_CC037B92FDB3. As such, CC:03:7B:92:FD:B3 was added to line 5. Note that you must add in the colons in order for the code to work correctly.

  • Once it connects, you can input the PWM values and select which motor to drive in the console.

  • Program will run and terminate after 3 seconds based on line 35.

bluettoothinputpy.py Breakdown

Let's break down the contents of bluettoothinputpy.py. For starters let's copy this code into your Python IDE.

import sys
import asyncio
from bleak import BleakClient

ADDRESS = "CC:03:7B:92:FD:B3"
MAILBOX_CHARACTERISTIC = "0000ffd1-0000-1000-8000-00805f9b34fb"
COMMAND_CHARACTERISTIC = "0000ffd2-0000-1000-8000-00805f9b34fb"

async def send_pwm_commands(address, MTR_PWM, motor_number):
    async with BleakClient(address) as client:
        print(f"Connected: {client.is_connected}")

        paired = await client.pair(protection_level=2)
        print(f"Paired: {paired}")

        # Convert the integer value to a hex string
        hex_MTR_PWM = hex(MTR_PWM & 0xFF)[2:].zfill(2)

        # Create a byte array from the hex string
        PWM_command = bytearray([int(hex_MTR_PWM, 16)])

        # Send mailbox command
        await client.write_gatt_char(MAILBOX_CHARACTERISTIC, PWM_command, response=False)
        await asyncio.sleep(1.0)

        # Choose the motor command based on the motor number
        if motor_number == 1:
            motor_command = bytearray([0x03, 0x00])
        else:
            motor_command = bytearray([0x04, 0x00])

        #print(f"Motor Command: {motor_number}")
        # Send cmotor ommand
        await client.write_gatt_char(COMMAND_CHARACTERISTIC, motor_command, response=False)
        await asyncio.sleep(3.0)

if __name__ == "__main__":
    try:
        MTR_PWM_input = int(input("Enter PWM value (-100 to 100): "))
        MTR_PWM_input = max(min(MTR_PWM_input, 100), -100)
        motor_number_input = int(input("Enter motor number (1 or 2): "))
        if motor_number_input not in (1,2,3):
            raise ValueError("Invalid motor number.")
    except ValueError:
        print("Invalid input. Please enter an integer.")
        sys.exit(1)

    asyncio.run(send_pwm_commands(ADDRESS, MTR_PWM_input, motor_number_input))

IDE

In order to run python, you will need to have an IDE and python compiler. If desired, you can use Visual Studio Code Code on your computer.

Below is sample console output from bluetoothinputpy.py running in PowerShell, using Visual Studio Code. In this example, motor's 2 PWM value was set to 100 for 3 seconds.

PS C:\ modimodule>
& C:/Python310/python.exe "c:/modimodule/bluettoothinputpy.py"
Enter PWM value (-100 to 100): 100
Enter motor number (1 or 2): 2
Connected: True
Paired: True
PreviousMan-In-The-Loop Obstacle Avoidance Tutorial-JavaScriptNextProduct Specification Sheet

Last updated 1 year ago

Was this helpful?

Follow this link and use the steps related to your operating system.

Once you have the IDE installed, follow these instructions to install python, .

πŸš•
https://code.visualstudio.com/docs/setup/setup-overview
https://code.visualstudio.com/docs/python/python-tutorial