import RPi.GPIO as GPIO
from time import sleep, time

# constants
DEBUG = False       # debug mode?

SETTLE_TIME = 2     # seconds to let the sensor settle
CALIBRATIONS = 5    # number of calibration measurements to take
CALIBRATION_DELAY = 1   # seconds to delay in between calibration measurements
TRIGGER_TIME = 0.00001  # seconds needed to trigger the sensor (to get a measurement)
SPEED_OF_SOUND = 343    # speed of sound in m/s

# set the RPi to the Broadcom pin layout

# GPIO pins
TRIG = 18           # the sensor's TRIG pin
ECHO = 27           # the sensor's ECHO pin

GPIO.setup(TRIG, GPIO.OUT)  # TRIG is an output
GPIO.setup(ECHO, GPIO.IN)   # ECHO is an input

# calibrates the sensor
# technically, it returns a correction factor to use in our calculations
def calibrate():
    print "Calibrating..."
    # prompt the user for an object's known distance
    print "-Place the sensor a measured distance away from an object."
    known_distance = input("-What is the measured distance (cm)? ")

    # measure the distance to the object with the sensor
    # do this several times and get an average
    print "-Getting calibration measurements..."
    distance_avg = 0
    for i in range(CALIBRATIONS):
        distance = getDistance()
        if (DEBUG):
            print "--Got {}cm".format(distance)
        # keep a running sum
        distance_avg += distance
        # delay a short time before using the sensor again
    # calculate the average of the distances
    distance_avg /= CALIBRATIONS
    if (DEBUG):
        print "--Average is {}cm".format(distance_avg)

    # calculate the correction factor
    correction_factor = known_distance / distance_avg
    if (DEBUG):
        print "--Correction factor is {}".format(correction_factor)

    print "Done."

    return correction_factor

# uses the sensor to calculate the distance to an object
def getDistance():
    # trigger the sensor by setting it high for a short time and then setting it low
    GPIO.output(TRIG, GPIO.HIGH)
    GPIO.output(TRIG, GPIO.LOW)

    # wait for the ECHO pin to read high
    # once the ECHO pin is high, the start time is set
    # once the ECHO pin is low again, the end time is set
    while (GPIO.input(ECHO) == GPIO.LOW):
        start = time()
    while (GPIO.input(ECHO) == GPIO.HIGH):
        end = time()

    # calculate the duration that the ECHO pin was high
    # this is how long the pulse took to get from the sensor to the object -- and back again
    duration = end - start
    # calculate the total distance that the pulse traveled by factoring in the speed of sound (m/s)
    distance = duration * SPEED_OF_SOUND
    # the distance from the sensor to the object is half of the total distance traveled
    distance /= 2
    # convert from meters to centimeters
    distance *= 100

    return distance
#Collects measurements and puts them in unsorted and sorted list
def sort():
        list1 = [distance]
        print("Unsorted measurements:")
        print("Sorted measurements:")

# MAIN #
# first, allow the sensor to settle for a bit
print "Waiting for sensor to settle ({}s)...".format(SETTLE_TIME)

# next, calibrate the sensor
correction_factor = calibrate()

# then, measure
raw_input("Press enter to begin...")
print "Getting measurements:"
while (True):
    # get the distance to an object and correct it with the correction factor
    print "-Measuring..."
    distance = getDistance() * correction_factor

    # and round to four decimal places
    distance = round(distance, 4)

    # display the distance measured/calculated
    print "--Distance measured: {}cm".format(distance)

    # prompt for another measurement
    i = raw_input("--Get another measurement (Y/n)? ")
    # stop measuring if desired
    if (not i in [ "y", "Y", "yes", "Yes", "YES", "" ]):

# finally, cleanup the GPIO pins
print "Done."

#Lastly, prints unsorted and sorted list
 New contributor

put on hold as unclear what you’re asking by Milliwaysjoangoldilocks 13 hours ago

Please clarify your specific problem or add additional details to highlight exactly what you need. As it’s currently written, it’s hard to tell exactly what you’re asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    what does your python programming question have to do with the RPi? – jsotola 22 hours ago
  • @jsotola I need to use the values given to my by my sensor which is hooked up to my RPi and create a list using those functions – Powerrangers123 22 hours ago
  • 1
    the sensor readings could come from any microcontroller or from an on-line source, therefore the RPi is irrelevant … that makes it a python programming question that does not belong on this site – jsotola 20 hours ago
  • 1
    The code contains the usual errors. It looks like it may have been copied from an Arduino with no allowance for Linux being a multi-user multi-tasking operating system. – joan 16 hours ago



How do I create a list in Python with the given distances measured from ultrasonic sensor?

Short Answer

OK, so you are writing the following python functions:

  1. Set Rpi GPIO pins to input/out mode.
  2. Measure distance by triggering sensor and then convert echo time to distance.
  3. Collect measurements and put them in a list.

The first two functions are not that difficult, and you can find too many Arduino/Rpi demo/sample programs all over the place.

Now let me suggest how to do the last job which is your question:

Put collected measurements in sorted/unsorted lists and print them out.

This part is also easy, again you can find loads of examples, but sadly most of them are Arduino C++ code, and it is not that easy to convert Arduino C++ code lists, structs, text files to Rpi python, because they quite different software architectures.

Before suggesting anything, let me introduce my recent programming experience and why I suggest this and not that.

I have 5 years hobbyist programmer’s experience in Arduino C++, and another 5 years in Rpi python. I choose Rpi python for many reasons, one very important of which is to learn new ideas, and hopefully I can apply those new ideas later for my long term projects in areas of AI, IoT, big data etc, …

So the following brainstorming suggestions would hopefully be useful to you, IF AND ONLY IF you wish to use Rpi and python as a tool to learn modern day electronics, IOT hardware and software.

The principles and practices I am suggesting to learn can readily be transferred to other software projects and also scaled up for big data. That is why I am suggesting to use the python’s very powerful, thought unsorted, but hashed/indexed, “dictionary” data structure, with many other good things that those Arduino array/struct guys are really so jealous,… 🙂

Though your question is on how to use a list, I also suggest to use text file, which is, after all, also a list but using text file as a non volatile storage medium.

Another reason you need to use list as a text file, and not only in RAM and flash, because sooner or later, you might need to data log your ultrasonic distance measurements, with time stamps, GPS locations etc, and merge you small ultrasonic data set with big IoT/AI databases, distributed all over the Net and the Cloud …

Newbie Tips on using Rpi Python List/Dictionary/Text Files

It is not important to learn text file processing now. More important is learn how to use list wisely, to make program readable, and document easy. Processing time is actually not important at all, because you can convert the time critical functions using C/C++.

I learnt python from free MIT online courses almost 10 years ago. Of course you can find other more newbid friendly, also free online courses.

I am very glad to learn many useful concepts like “abstraction” using functions, using dictionary with meaning names of dictionary elements. If you use list, you need to remember which element for which say, ultrasonic measurements. For dictionary, you can refer the measurements by dictionary index/name. For example, you can say the following:

UltrasonicMeasurementDictionary[‘Left Sensor’][‘First Reading’] etc.

For lists, you don’t need to to for loops with counter equal to number of elements in a list. For example, if you take 5 measurements, you can use the following for loop:

for i in range maxNumberOfMeasurements: process measurementList[i]

But the clever, automatically scaling up python way is the following:

for measurement in measurementList: process measurement.

For short lists, the above two for loops make little difference, but the important thing is that when your list grows day by day, you don’t need to change for loop counter, because the for loop automatically scales up.

I know it is hard for newbies to understand, but my recommendation to newbies is that you spend big efforts now to learn advanced things, your reward will be huge when your project grows and complexity increases exponentially and impossible to manage, …

Sorry for long winding stuff, good luck and enjoy python programming, list or else. 🙂

/to continue, …

Not the answer you’re looking for? Browse other questions tagged   or ask your own question.

Categories: Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: