gpy maxbotix

  • I am trying to get a maxbotix sensor (MB7060 with Serial TTL output) working in micropython. There is a sample code for the raspberry pi but this one uses the serial module. I think the serial module is not available in micro python. Are there people who can make this sensor work in micro python on a gpy (willing to reimburse)? ```

    First, the Python module that does the actual work:
    # Filename:
    # Reads serial data from Maxbotix ultrasonic rangefinders
    # Gracefully handles most common serial data glitches
    # Use as an importable module with "import MaxSonarTTY"
    # Returns an integer value representing distance to target in millimeters
    from time import time
    from serial import Serial
    serialDevice = "/dev/ttyAMA0" # default for RaspberryPi
    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
                testData =
                if not testData.startswith(b'R'):
                    # data received did not start with R
                    sensorData = testData.decode('utf-8').lstrip('R')
                except UnicodeDecodeError:
                    # data received could not be decoded properly
                    mm = int(sensorData)
                except ValueError:
                    # value is not a number
        raise RuntimeError("Expected serial data not received")
    if __name__ == '__main__':
        measurement = measure(serialDevice)
        print("distance =",measurement)
    Also, here is a sample Python script that shows how the module may be used:
    # Filename:
    # sample script to read range values from Maxbotix ultrasonic rangefinder
    from time import sleep
    import maxSonarTTY
    serialPort = "/dev/ttyAMA0"
    maxRange = 5000  # change for 5m vs 10m sensor
    sleepTime = 5
    minMM = 9999
    maxMM = 0
    while True:
        mm = maxSonarTTY.measure(serialPort)
        if mm >= maxRange:
            print("no target")
        if mm < minMM:
            minMM = mm
        if mm > maxMM:
            maxMM = mm
        print("distance:", mm, "  min:", minMM, "max:", maxMM)

  • @marcbeltman Instead of the serial module, you must use Machine.UART. See:

Log in to reply

Pycom on Twitter