|
| 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