| 1 | == Ultrasonic Rangefinder |
| 2 | |
| 3 | Robots often need to sense the environment around them, particularly when driving autonomously. Ultrasonic sensors are like the sonar used by bats. They emit a chirp of sound and measure the time it takes to hear an echo of that chirp. The longer the time, the further the sound traveled. Since sound travels at a particular speed through air, we can use the echo delay to calculate how far away the object was that reflected the sound. You can read more about ultrasonic sensors [https://wpilib.screenstepslive.com/s/currentCS/m/java/l/599715-ultrasonic-sensors-measuring-robot-distance-to-a-surface here] |
| 4 | |
| 5 | Create another program using the !TimedRobot java template and name it !UltrasonicTest. Modify the generated code as follows: |
| 6 | * import the Ultrasonic class {{{ import edu.wpi.first.wpilibj.Ultrasonic; }}} |
| 7 | * declare a ultrasonic variable in the Robot class {{{ private Ultrasonic f_ultrasonic; }}} |
| 8 | * in robotInit() instantiate an ultrasonic object and set it to start automatically ranging |
| 9 | {{{ |
| 10 | f_ultrasonic = new Ultrasonic(1,0); |
| 11 | f_ultrasonic.setAutomaticMode(true); |
| 12 | }}} |
| 13 | * in robotPeriodic() read and display the range |
| 14 | {{{ |
| 15 | if (f_ultrasonic.isRangeValid()) { |
| 16 | SmartDashboard.putNumber("Front range", f_ultrasonic.getRangeInches()); |
| 17 | } |
| 18 | }}} |
| 19 | |
| 20 | Run the program and observe the "Front range" value in the [https://wpilib.screenstepslive.com/s/currentCS/m/java/l/599724-displaying-data-on-the-ds-dashboard-overview Smart Dashboard] as you move the robot towards and away from the wall. |
| 21 | |
| 22 | Notice that the measurements aren't always perfect; the sensor may receive echos from multiple surfaces. |
| 23 | |