Easy Distance Sensing With Python
by phidgeteer in Circuits > Sensors
373 Views, 1 Favorites, 0 Comments
Easy Distance Sensing With Python
This project will show you how to add distance sensing to your next Python project.
Supplies
- VINT Hub
- Sonar Phidget
Connect Your Sonar Phidget
Connect your Sonar Phidget to your VINT Hub with a Phidget Cable.
Install Phidget Libraries
In order to get your Phidgets to work, you have to install the appropriate libraries. There are a few different ways to do this depending on your operating system.
Windows
Just pip install Phidget22Native and you're done!
macOS
Run the Phidget Installer for macOS and then pip install Phidget22
Linux
Write Code - Polling
Copy the following code into a new Python script:
#Add Phidgets Library from Phidget22.Phidget import * from Phidget22.Devices.DistanceSensor import * #Required for sleep statement import time #Create distanceSensor = DistanceSensor() #Open distanceSensor.openWaitForAttachment(1000) #Use your Phidgets while (True): print("Distance: " + str(distanceSensor.getDistance()) + " mm") time.sleep(0.25)
Polling Code Review
Each section of the code is described below.
Add Phidgets Library
This section adds the Phidget class and the Distance Sensor class to your project. These are from the Phidgets Python library that you installed using pip.
Required for sleep statement
The time module is used in this code to implement a sleep statement. Sleeping is often used when polling sensors.
Create
This line of code creates the DistanceSensor object. This object will be used to interface with the Sonar Phidget.
Open
After creating the object, call open to start interacting with it. The 1000 is a timeout value that normally doesn't matter for small projects like this. The Phidgets library will throw an error if it doesn't connect to the Sonar Phidget within 1000 ms or 1 second.
Use your Phidgets
This is a basic polling loop. It checks the distance reported from the Phidget and then sleeps for 25 milliseconds (the default data interval of the Sonar Phidget).
Phidgets can also be used with events instead of polling, but that is not covered in this tutorial
Result
The result is a Python program that can quickly and easily sense Distance.