001// Copyright (c) FIRST and other WPILib contributors. 002// Open Source Software; you can modify and/or share it under the terms of 003// the WPILib BSD license file in the root directory of this project. 004 005package edu.wpi.first.wpilibj; 006 007import static edu.wpi.first.util.ErrorMessages.requireNonNullParam; 008 009import edu.wpi.first.hal.FRCNetComm.tResourceType; 010import edu.wpi.first.hal.HAL; 011import edu.wpi.first.hal.SimBoolean; 012import edu.wpi.first.hal.SimDevice; 013import edu.wpi.first.hal.SimDevice.Direction; 014import edu.wpi.first.hal.SimDouble; 015import edu.wpi.first.util.sendable.Sendable; 016import edu.wpi.first.util.sendable.SendableBuilder; 017import edu.wpi.first.util.sendable.SendableRegistry; 018import java.util.ArrayList; 019import java.util.List; 020 021/** 022 * Ultrasonic rangefinder class. The Ultrasonic rangefinder measures absolute distance based on the 023 * round-trip time of a ping generated by the controller. These sensors use two transducers, a 024 * speaker and a microphone both tuned to the ultrasonic range. A common ultrasonic sensor, the 025 * Daventech SRF04 requires a short pulse to be generated on a digital channel. This causes the 026 * chirp to be emitted. A second line becomes high as the ping is transmitted and goes low when the 027 * echo is received. The time that the line is high determines the round trip distance (time of 028 * flight). 029 */ 030public class Ultrasonic implements Sendable, AutoCloseable { 031 // Time (sec) for the ping trigger pulse. 032 private static final double kPingTime = 10 * 1e-6; 033 private static final double kSpeedOfSoundInchesPerSec = 1130.0 * 12.0; 034 // ultrasonic sensor list 035 private static final List<Ultrasonic> m_sensors = new ArrayList<>(); 036 // automatic round robin mode 037 private static volatile boolean m_automaticEnabled; 038 private DigitalInput m_echoChannel; 039 private DigitalOutput m_pingChannel; 040 private final boolean m_allocatedChannels; 041 private boolean m_enabled; 042 private Counter m_counter; 043 // task doing the round-robin automatic sensing 044 private static Thread m_task; 045 private static int m_instances; 046 047 private SimDevice m_simDevice; 048 049 private SimBoolean m_simRangeValid; 050 private SimDouble m_simRange; 051 052 /** 053 * Background task that goes through the list of ultrasonic sensors and pings each one in turn. 054 * The counter is configured to read the timing of the returned echo pulse. 055 * 056 * <p><b>DANGER WILL ROBINSON, DANGER WILL ROBINSON:</b> This code runs as a task and assumes that 057 * none of the ultrasonic sensors will change while it's running. If one does, then this will 058 * certainly break. Make sure to disable automatic mode before changing anything with the 059 * sensors!! 060 */ 061 private static final class UltrasonicChecker extends Thread { 062 @Override 063 public synchronized void run() { 064 while (m_automaticEnabled) { 065 for (Ultrasonic sensor : m_sensors) { 066 if (!m_automaticEnabled) { 067 break; 068 } 069 070 if (sensor.isEnabled()) { 071 sensor.m_pingChannel.pulse(kPingTime); // do the ping 072 } 073 074 Timer.delay(0.1); // wait for ping to return 075 } 076 } 077 } 078 } 079 080 /** 081 * Initialize the Ultrasonic Sensor. This is the common code that initializes the ultrasonic 082 * sensor given that there are two digital I/O channels allocated. If the system was running in 083 * automatic mode (round-robin) when the new sensor is added, it is stopped, the sensor is added, 084 * then automatic mode is restored. 085 */ 086 private synchronized void initialize() { 087 m_simDevice = SimDevice.create("Ultrasonic", m_echoChannel.getChannel()); 088 if (m_simDevice != null) { 089 m_simRangeValid = m_simDevice.createBoolean("Range Valid", Direction.kInput, true); 090 m_simRange = m_simDevice.createDouble("Range (in)", Direction.kInput, 0.0); 091 m_pingChannel.setSimDevice(m_simDevice); 092 m_echoChannel.setSimDevice(m_simDevice); 093 } 094 final boolean originalMode = m_automaticEnabled; 095 setAutomaticMode(false); // kill task when adding a new sensor 096 m_sensors.add(this); 097 098 m_counter = new Counter(m_echoChannel); // set up counter for this 099 SendableRegistry.addChild(this, m_counter); 100 // sensor 101 m_counter.setMaxPeriod(1.0); 102 m_counter.setSemiPeriodMode(true); 103 m_counter.reset(); 104 m_enabled = true; // make it available for round-robin scheduling 105 setAutomaticMode(originalMode); 106 107 m_instances++; 108 HAL.report(tResourceType.kResourceType_Ultrasonic, m_instances); 109 SendableRegistry.addLW(this, "Ultrasonic", m_echoChannel.getChannel()); 110 } 111 112 /** 113 * Returns the echo channel. 114 * 115 * @return The echo channel. 116 */ 117 public int getEchoChannel() { 118 return m_echoChannel.getChannel(); 119 } 120 121 /** 122 * Create an instance of the Ultrasonic Sensor. This is designed to support the Daventech SRF04 123 * and Vex ultrasonic sensors. 124 * 125 * @param pingChannel The digital output channel that sends the pulse to initiate the sensor 126 * sending the ping. 127 * @param echoChannel The digital input channel that receives the echo. The length of time that 128 * the echo is high represents the round trip time of the ping, and the distance. 129 */ 130 @SuppressWarnings("this-escape") 131 public Ultrasonic(final int pingChannel, final int echoChannel) { 132 m_pingChannel = new DigitalOutput(pingChannel); 133 m_echoChannel = new DigitalInput(echoChannel); 134 SendableRegistry.addChild(this, m_pingChannel); 135 SendableRegistry.addChild(this, m_echoChannel); 136 m_allocatedChannels = true; 137 initialize(); 138 } 139 140 /** 141 * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo channel and a 142 * DigitalOutput for the ping channel. 143 * 144 * @param pingChannel The digital output object that starts the sensor doing a ping. Requires a 145 * 10uS pulse to start. 146 * @param echoChannel The digital input object that times the return pulse to determine the range. 147 */ 148 @SuppressWarnings("this-escape") 149 public Ultrasonic(DigitalOutput pingChannel, DigitalInput echoChannel) { 150 requireNonNullParam(pingChannel, "pingChannel", "Ultrasonic"); 151 requireNonNullParam(echoChannel, "echoChannel", "Ultrasonic"); 152 153 m_allocatedChannels = false; 154 m_pingChannel = pingChannel; 155 m_echoChannel = echoChannel; 156 initialize(); 157 } 158 159 /** 160 * Destructor for the ultrasonic sensor. Delete the instance of the ultrasonic sensor by freeing 161 * the allocated digital channels. If the system was in automatic mode (round-robin), then it is 162 * stopped, then started again after this sensor is removed (provided this wasn't the last 163 * sensor). 164 */ 165 @Override 166 public synchronized void close() { 167 SendableRegistry.remove(this); 168 final boolean wasAutomaticMode = m_automaticEnabled; 169 setAutomaticMode(false); 170 if (m_allocatedChannels) { 171 if (m_pingChannel != null) { 172 m_pingChannel.close(); 173 } 174 if (m_echoChannel != null) { 175 m_echoChannel.close(); 176 } 177 } 178 179 if (m_counter != null) { 180 m_counter.close(); 181 m_counter = null; 182 } 183 184 m_pingChannel = null; 185 m_echoChannel = null; 186 synchronized (m_sensors) { 187 m_sensors.remove(this); 188 } 189 if (!m_sensors.isEmpty() && wasAutomaticMode) { 190 setAutomaticMode(true); 191 } 192 193 if (m_simDevice != null) { 194 m_simDevice.close(); 195 m_simDevice = null; 196 } 197 } 198 199 /** 200 * Turn Automatic mode on/off for all sensors. 201 * 202 * <p>When in Automatic mode, all sensors will fire in round-robin, waiting a set time between 203 * each sensor. 204 * 205 * @param enabling Set to true if round-robin scheduling should start for all the ultrasonic 206 * sensors. This scheduling method assures that the sensors are non-interfering because no two 207 * sensors fire at the same time. If another scheduling algorithm is preferred, it can be 208 * implemented by pinging the sensors manually and waiting for the results to come back. 209 */ 210 public static synchronized void setAutomaticMode(boolean enabling) { 211 if (enabling == m_automaticEnabled) { 212 return; // ignore the case of no change 213 } 214 m_automaticEnabled = enabling; 215 216 if (enabling) { 217 /* Clear all the counters so no data is valid. No synchronization is 218 * needed because the background task is stopped. 219 */ 220 for (Ultrasonic u : m_sensors) { 221 u.m_counter.reset(); 222 } 223 224 // Start round robin task 225 m_task = new UltrasonicChecker(); 226 m_task.start(); 227 } else { 228 if (m_task != null) { 229 // Wait for background task to stop running 230 try { 231 m_task.join(); 232 m_task = null; 233 } catch (InterruptedException ex) { 234 Thread.currentThread().interrupt(); 235 ex.printStackTrace(); 236 } 237 } 238 239 /* Clear all the counters (data now invalid) since automatic mode is 240 * disabled. No synchronization is needed because the background task is 241 * stopped. 242 */ 243 for (Ultrasonic u : m_sensors) { 244 u.m_counter.reset(); 245 } 246 } 247 } 248 249 /** 250 * Single ping to ultrasonic sensor. Send out a single ping to the ultrasonic sensor. This only 251 * works if automatic (round-robin) mode is disabled. A single ping is sent out, and the counter 252 * should count the semi-period when it comes in. The counter is reset to make the current value 253 * invalid. 254 */ 255 public void ping() { 256 setAutomaticMode(false); // turn off automatic round-robin if pinging 257 // single sensor 258 m_counter.reset(); // reset the counter to zero (invalid data now) 259 // do the ping to start getting a single range 260 m_pingChannel.pulse(kPingTime); 261 } 262 263 /** 264 * Check if there is a valid range measurement. The ranges are accumulated in a counter that will 265 * increment on each edge of the echo (return) signal. If the count is not at least 2, then the 266 * range has not yet been measured, and is invalid. 267 * 268 * @return true if the range is valid 269 */ 270 public boolean isRangeValid() { 271 if (m_simRangeValid != null) { 272 return m_simRangeValid.get(); 273 } 274 return m_counter.get() > 1; 275 } 276 277 /** 278 * Get the range in inches from the ultrasonic sensor. If there is no valid value yet, i.e. at 279 * least one measurement hasn't completed, then return 0. 280 * 281 * @return double Range in inches of the target returned from the ultrasonic sensor. 282 */ 283 public double getRangeInches() { 284 if (isRangeValid()) { 285 if (m_simRange != null) { 286 return m_simRange.get(); 287 } 288 return m_counter.getPeriod() * kSpeedOfSoundInchesPerSec / 2.0; 289 } else { 290 return 0; 291 } 292 } 293 294 /** 295 * Get the range in millimeters from the ultrasonic sensor. If there is no valid value yet, i.e. 296 * at least one measurement hasn't completed, then return 0. 297 * 298 * @return double Range in millimeters of the target returned by the ultrasonic sensor. 299 */ 300 public double getRangeMM() { 301 return getRangeInches() * 25.4; 302 } 303 304 /** 305 * Is the ultrasonic enabled. 306 * 307 * @return true if the ultrasonic is enabled 308 */ 309 public boolean isEnabled() { 310 return m_enabled; 311 } 312 313 /** 314 * Set if the ultrasonic is enabled. 315 * 316 * @param enable set to true to enable the ultrasonic 317 */ 318 public void setEnabled(boolean enable) { 319 m_enabled = enable; 320 } 321 322 @Override 323 public void initSendable(SendableBuilder builder) { 324 builder.setSmartDashboardType("Ultrasonic"); 325 builder.addDoubleProperty("Value", this::getRangeInches, null); 326 } 327}