Beagle Board - beagleboard.org
Mala Dies
Published

MaxBotix Rangefinder and Python! BBBW!

Did you ever want to learn something but it seemed impossible b/c of too many articles on the subject or not enough? BBBW!

IntermediateProtip1 hour64
MaxBotix Rangefinder and Python! BBBW!

Things used in this project

Hardware components

MaxBotix Range Finder
×1
BeagleBone Black Wireless
BeagleBoard.org BeagleBone Black Wireless
×1
Jumper wires (generic)
Jumper wires (generic)
×1
Resistor 1k ohm
Resistor 1k ohm
×2
General Purpose Transistor NPN
General Purpose Transistor NPN
×1

Software apps and online services

BeagleBoard.org Debian Distro
Python

Hand tools and fabrication machines

Soldering iron (generic)
Soldering iron (generic)
Solder Wire, Lead Free
Solder Wire, Lead Free

Story

Read more

Schematics

The initial posting of the set up!

This person helped me grasp the idea of the inverter and the need for it b/c of what the datasheet stated.

Code

The Library!

Python
Type this in the same directory (copy and paste) as your file you want to run!
#!/usr/bin/python3

# from John Bohlhuis 2015
# import Adafruit_BBIO.UART as UART
from time import time
from serial import Serial

# UART.setup = "UART2"
serialDevice = "/dev/ttyS2"
maxwait = 3 # seconds to try for a good reading before quitting

def measure(portName):
    ser = Serial(portName, 9600, 8, 'N', 1, timeout=1)
    timeStart = time()
    valueCount = 0

    while time() < timeStart + maxwait:
        if ser.inWaiting():
            bytesToRead = ser.inWaiting()
            valueCount += 1
            if valueCount < 2: # 1st reading may be partial number; throw it out
                continue
            testData = ser.read(bytesToRead)
            if not testData.startswith(b'R'):
                # data received did not start with R
                continue
            try:
                sensorData = testData.decode('utf-8').lstrip('R')
            except UnicodeDecodeError:
                # data received could not be decoded properly
                continue
            try:
                mm = int(sensorData)
            except ValueError:
                # value is not a number
                continue
            ser.close()
            return(mm)

    ser.close()
    raise RuntimeError("Expected serial data not received")

if __name__ == '__main__':
    measurement = measure(serialDevice)
    print("distance =", measurement)

The source!

Python
Run this command w/ python3 whatverthenameofthisfileisnow.py
#!/usr/bin/python3

#import Adafruit_BBIO.UART as UART
from time import sleep
import range

#UART.setup = "UART2"
serialPort = "/dev/ttyS2"
maxRange = 5000  # change for 5m vs 10m sensor
sleepTime = 5
minMM = 9999
maxMM = 0

while True:
    mm = range.measure(serialPort)
    if mm >= maxRange:
        print("no target")
        sleep(sleepTime)
        continue
    if mm < minMM:
        minMM = mm
    if mm > maxMM:
        maxMM = mm

    print("distance:", mm, "  min:", minMM, "max:", maxMM)
    sleep(sleepTime)

Try this library too!

Python
This is another library you can use!
import serial
import re

class Range(serial.Serial):
    def __init__(self, port):
        super().__init__(port=port, baudrate=9600, timeout=1)

    def measure( self ):
        self.reset_input_buffer()

        data = self.read_until(b'\r', size=5)

        if re.fullmatch(rb'\d*\r', data):
            # partial line received, wait for next one
            data = self.read_until(b'\r', size=5)

        if len(data) < 5 and not data.endswith(b'\r'):
            raise RuntimeError("Timeout while waiting for data")

        m = re.fullmatch(rb'R(\d+)\r', data)
        if not m:
            raise RuntimeError("Garbage data received: %r" % data)
        data = m.group(1)

        return int(data)  # measurement in inches (0-255)

Use this source w/ the RangeI.py library...

Python
Python!
from time import sleep
from rangeI import Range

sonar = Range("/dev/ttyS2")

try:
    while True:
        distance = sonar.measure()
        print("distance =", distance, "inch")

        sleep( 1 )

except KeyboardInterrupt:
    pass

Credits

Mala Dies

Mala Dies

11 projects • 1 follower
Stay there and someone will find you...
Thanks to A fellow on Freenode #beagle and John Bohlhuis.

Comments

Add projectSign up / Login