Skip to content

Commit 411d9b0

Browse files
Created Ultrasonic example (#85)
1 parent 7bb948a commit 411d9b0

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

run_tests.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ BASE_TESTS="
3939
tank-drive
4040
tank-drive-xbox-controller
4141
timed/src
42+
ultrasonic
4243
"
4344

4445
IGNORED_TESTS="

ultrasonic/robot.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#!/usr/bin/env python3
2+
3+
import wpilib
4+
from wpilib.shuffleboard import Shuffleboard
5+
from wpilib import SmartDashboard
6+
7+
8+
class MyRobot(wpilib.TimedRobot):
9+
"""
10+
This is a sample program demonstrating how to read from a ping-response ultrasonic sensor with
11+
the :class:`.Ultrasonic` class.
12+
"""
13+
14+
def robotInit(self):
15+
# Creates a ping-response Ultrasonic object on DIO 1 and 2.
16+
self.rangeFinder = wpilib.Ultrasonic(1, 2)
17+
18+
# Add the ultrasonic to the "Sensors" tab of the dashboard
19+
# Data will update automatically
20+
Shuffleboard.getTab("Sensors").add(self.rangeFinder)
21+
22+
def teleopPeriodic(self):
23+
# We can read the distance in millimeters
24+
distanceMillimeters = self.rangeFinder.getRangeMM()
25+
# ... or in inches
26+
distanceInches = self.rangeFinder.getRangeInches()
27+
28+
# We can also publish the data itself periodically
29+
SmartDashboard.putNumber("Distance[mm]", distanceMillimeters)
30+
SmartDashboard.putNumber("Distance[in]", distanceInches)
31+
32+
def testInit(self):
33+
# By default, the Ultrasonic class polls all ultrasonic sensors every in a round-robin to prevent
34+
# them from interfering from one another.
35+
# However, manual polling is also possible -- notes that this disables automatic mode!
36+
self.rangeFinder.ping()
37+
38+
def testPeriodic(self):
39+
if self.rangeFinder.isRangeValid():
40+
# Data is valid, publish it
41+
SmartDashboard.putNumber("Distance[mm]", self.rangeFinder.getRangeMM())
42+
SmartDashboard.putNumber("Distance[in]", self.rangeFinder.getRangeInches())
43+
44+
# Ping for next measurement
45+
self.rangeFinder.ping()
46+
47+
def testExit(self):
48+
# Enable automatic mode
49+
self.rangeFinder.setAutomaticMode(True)
50+
51+
52+
if __name__ == "__main__":
53+
wpilib.run(MyRobot)

0 commit comments

Comments
 (0)