[SOLVED] Ultrasonic Sensor - Creating an Array from the Results


#1

Hi! I am trying to program an ultrasonic sensor to scan for a certain amount of time. In my case 18 seconds. I would like a value to be recorded every 0.1 seconds and all 180 recorded values to be put into an array. Is this possible?

Thank you for reading!


#2

Yes, it is certainly possible. You can create an array of 180 elements, and then loop 180 times. In that loop, you can read the sensor value, write it to the corresponding array element, and then delay.

With BrickPi3, in Python it would look something like this:

# Add code here to import the BrickPi3 module and instantiate
# Add code here to configure the sensor port for the sensor type and mode

# Create an array with 180 elements
ResultsArray = [0 for r in range(180)]

# Loop 180 times
for r in range(180):
    # Read the sensor and save the value in the array
    # Here I'm assuming the BrickPi3 object is called 'BP'
    # Also assumed is that the ultrasonic sensor is on sensor port 1
    ResultsArray[r] = BP.get_sensor(BP.PORT_1)

    # delay for 0.1 seconds
    time.sleep(0.1)