Skip to content

Examples

vihaanvp edited this page Jul 4, 2026 · 4 revisions

Examples (9 scripts)

Ready-to-run scripts are in examples/. Run any of them with:

python examples/<file>.py

All motor/servo examples require an Arduino running StandardFirmata. Sensor examples require a Raspberry Pi (or Blinka-compatible board) with VL53L0X connected via I²C.


1. single_motor.py — Basic DC Motor

Runs a single motor forward at full speed for 2 seconds, then stops.

import time
from megawrapper import Board

board = Board("/dev/ttyUSB0")
motor = board.attach_motor(2, 4, 11)
motor.forward(100)
time.sleep(2)
motor.stop()

board.close()

Try: Change the speed (forward(50)) or direction (backward()).


2. dual_motor.py — Two Named Motors

Attaches two motors with descriptive names and runs them at different speeds.

import time
from megawrapper import Board

board = Board("/dev/ttyUSB0")
left = board.attach_motor(2, 4, 11, "left")
right = board.attach_motor(5, 3, 10, "right")
left.forward(50)
right.forward(100)
time.sleep(3)
board.stop_all()
board.close()

Try: Swap directions to make the robot spin in place.


3. tank_drive.py — Differential Steering

Demonstrates differential (tank) steering by running two motors at different speeds.

import time
from megawrapper import Board

board = Board("/dev/ttyUSB0")
left = board.attach_motor(2, 4, 11)
right = board.attach_motor(5, 3, 10)

left.forward(100)
right.forward(100)
time.sleep(2)

left.forward(50)
right.forward(100)
time.sleep(2)

left.stop()
right.stop()
board.close()

Try: Make one motor go backward while the other goes forward for a point turn.


4. keyboard_control.py — Interactive CLI Control

Lets you drive a motor interactively from the terminal.

from megawrapper import Board

board = Board("/dev/ttyUSB0")
motor = board.attach_motor(2, 4, 11)

while True:
    command = input(
        "f=forward b=backward s=stop q=quit > "
    ).lower()
    if command == "f":
        motor.forward(100)
    elif command == "b":
        motor.backward(100)
    elif command == "s":
        motor.stop()
    elif command == "q":
        break

board.close()

5. endless_sweep.py — Continuous Servo Sweep

Sweeps a servo back and forth forever using Servo.sweep().

from megawrapper import Board, Servo, delay

Board("/dev/ttyUSB0")
servo = Servo()
servo.attach(6)

while True:
    servo.sweep(start=0, end=180, step=1, delay_ms=15)
    servo.sweep(start=180, end=0, step=5, delay_ms=5)

Try: Adjust step and delay_ms to change the speed and smoothness.


6. move_smooth.py — Smooth Servo Movement

Moves a servo smoothly between positions using Servo.move_smooth().

from megawrapper import Board, Servo, delay

Board("/dev/ttyUSB0")
servo = Servo()
servo.attach(6)

servo.move_smooth(180)
delay(1000)

servo.move_smooth(0)

Try: Chain multiple move_smooth() calls to create a complex sequence.


7. pyserial_control.py — Built-in Firmata Backend

Demonstrates the alternative pyserial Firmata client (bypasses pyfirmata2).

"""Example: using the built-in pyserial Firmata backend directly.

This bypasses pyfirmata2 entirely, useful when you only need basic
digital / analog write and don't want the full pyfirmata2 dependency.
"""
import time
from megawrapper import Board, set_mode

# Switch to pyserial backend before creating the Board
set_mode("pyserial")

board = Board("/dev/ttyUSB0")
motor = board.attach_motor(2, 4, 11)
motor.forward(75)
time.sleep(2)
motor.stop()

board.close()

Requires pip install 'megawrapper[pyserial]'. The set_mode("pyserial") call must come before Board().


8. vl53l0x_sensor.py — Single ToF Distance Sensor

Reads distance from one VL53L0X laser ranging sensor over I²C.

"""Example: reading distance from a VL53L0X Time-of-Flight sensor.

Requires the optional sensor extras:
    pip install megawrapper[sensor]
"""
import time
from megawrapper.sensor import VL53L0X

sensor = VL53L0X()

for _ in range(20):
    print(f"Distance: {sensor.distance:.1f} cm")
    time.sleep(0.1)

Hardware: Raspberry Pi (or Blinka-compatible board) with VL53L0X connected via I²C. Does not require an Arduino.


9. vl53l0x_multi_sensor.py — Multiple ToF Sensors

Demonstrates VL53L0X.auto_address() to run up to 16 VL53L0X sensors on a single I²C bus.

"""Example: reading distances from multiple VL53L0X Time-of-Flight sensors.

This demonstrates VL53L0X.auto_address(), which sequences the XSHUT pins
to wake each sensor one-at-a-time and assign unique I²C addresses
(0x30, 0x31, 0x32, …).

Hardware requirements
---------------------
- Raspberry Pi (or other single-board computer with I²C)
- 2–16 VL53L0X ToF laser distance sensors
- Each sensor's XSHUT pin connected to a separate GPIO on the host

Wiring
------
  All sensors share the I²C bus (SDA, SCL, VCC, GND).

  Sensor #1:  XSHUT ──► GPIO 17   (address 0x30)
  Sensor #2:  XSHUT ──► GPIO 27   (address 0x31)
  Sensor #3:  XSHUT ──► GPIO 22   (address 0x32)

Installation
------------
  pip install 'megawrapper[sensor]'

Usage
-----
  python examples/vl53l0x_multi_sensor.py
"""
import time
from megawrapper.sensor import VL53L0X

XSHUT_PINS = [17, 27, 22]
LABELS = ["Front", "Left", "Right"]

sensors = VL53L0X.auto_address(XSHUT_PINS)

for i, s in enumerate(sensors):
    label = LABELS[i] if i < len(LABELS) else f"S{i}"
    d = s.distance
    print(f"  Sensor {i} ({label})  addr=0x{0x30 + i:02X}  "
          f"distance={d:.1f} cm  [OK]")

print(f"\n{len(sensors)} sensor(s) ready. Reading distances (Ctrl+C to stop)...\n")

header = f"{'Sensor':<10} {'Label':<8} {'Distance':<12} {'Status':<12}"
print(header)
print("-" * len(header))

try:
    while True:
        for i, s in enumerate(sensors):
            label = LABELS[i] if i < len(LABELS) else f"S{i}"
            try:
                dist = s.distance
                status = "OUT OF RANGE" if (dist < 0.1 or dist > 1200) else "OK"
                print(f"Sensor #{i:<4} {label:<8} {dist:>6.1f} cm    {status}")
            except Exception as e:
                print(f"Sensor #{i:<4} {label:<8} {'---':>8}    ERROR: {e}")
        time.sleep(0.5)
except KeyboardInterrupt:
    print("\nExiting.")

Wiring note: Each sensor's XSHUT pin must be connected to a separate GPIO. All sensors share SDA, SCL, VCC, and GND.