PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Ultrasonic.cpp

http://github.com/rbmj/wpilib
C++ | 361 lines | 215 code | 32 blank | 114 comment | 38 complexity | e5dd98f8d1b0a3d4ae09338c05d3425c MD5 | raw file
  1. /*----------------------------------------------------------------------------*/
  2. /* Copyright (c) FIRST 2008. All Rights Reserved. */
  3. /* Open Source Software - may be modified and shared by FRC teams. The code */
  4. /* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
  5. /*----------------------------------------------------------------------------*/
  6. #include "Ultrasonic.h"
  7. #include "Counter.h"
  8. #include "DigitalInput.h"
  9. #include "DigitalOutput.h"
  10. #include "NetworkCommunication/UsageReporting.h"
  11. #include "Timer.h"
  12. #include "Utility.h"
  13. #include "WPIErrors.h"
  14. #include "LiveWindow/LiveWindow.h"
  15. constexpr double Ultrasonic::kPingTime; ///< Time (sec) for the ping trigger pulse.
  16. const uint32_t Ultrasonic::kPriority; ///< Priority that the ultrasonic round robin task runs.
  17. constexpr double Ultrasonic::kMaxUltrasonicTime; ///< Max time (ms) between readings.
  18. constexpr double Ultrasonic::kSpeedOfSoundInchesPerSec;
  19. Task Ultrasonic::m_task("UltrasonicChecker", (FUNCPTR)UltrasonicChecker); // task doing the round-robin automatic sensing
  20. Ultrasonic *Ultrasonic::m_firstSensor = NULL; // head of the ultrasonic sensor list
  21. bool Ultrasonic::m_automaticEnabled = false; // automatic round robin mode
  22. SEM_ID Ultrasonic::m_semaphore = 0;
  23. /**
  24. * Background task that goes through the list of ultrasonic sensors and pings each one in turn. The counter
  25. * is configured to read the timing of the returned echo pulse.
  26. *
  27. * DANGER WILL ROBINSON, DANGER WILL ROBINSON:
  28. * This code runs as a task and assumes that none of the ultrasonic sensors will change while it's
  29. * running. If one does, then this will certainly break. Make sure to disable automatic mode before changing
  30. * anything with the sensors!!
  31. */
  32. void Ultrasonic::UltrasonicChecker()
  33. {
  34. Ultrasonic *u = NULL;
  35. while (m_automaticEnabled)
  36. {
  37. if (u == NULL) u = m_firstSensor;
  38. if (u == NULL) return;
  39. if (u->IsEnabled())
  40. u->m_pingChannel->Pulse(kPingTime); // do the ping
  41. u = u->m_nextSensor;
  42. Wait(0.1); // wait for ping to return
  43. }
  44. }
  45. /**
  46. * Initialize the Ultrasonic Sensor.
  47. * This is the common code that initializes the ultrasonic sensor given that there
  48. * are two digital I/O channels allocated. If the system was running in automatic mode (round robin)
  49. * when the new sensor is added, it is stopped, the sensor is added, then automatic mode is
  50. * restored.
  51. */
  52. void Ultrasonic::Initialize()
  53. {
  54. m_table = NULL;
  55. bool originalMode = m_automaticEnabled;
  56. if (m_semaphore == 0) m_semaphore = semBCreate(SEM_Q_PRIORITY, SEM_FULL);
  57. SetAutomaticMode(false); // kill task when adding a new sensor
  58. semTake(m_semaphore, WAIT_FOREVER); // link this instance on the list
  59. {
  60. m_nextSensor = m_firstSensor;
  61. m_firstSensor = this;
  62. }
  63. semGive(m_semaphore);
  64. m_counter = new Counter(m_echoChannel); // set up counter for this sensor
  65. m_counter->SetMaxPeriod(1.0);
  66. m_counter->SetSemiPeriodMode(true);
  67. m_counter->Reset();
  68. m_counter->Start();
  69. m_enabled = true; // make it available for round robin scheduling
  70. SetAutomaticMode(originalMode);
  71. static int instances = 0;
  72. instances++;
  73. nUsageReporting::report(nUsageReporting::kResourceType_Ultrasonic, instances);
  74. LiveWindow::GetInstance()->AddSensor("Ultrasonic", m_echoChannel->GetModuleForRouting(), m_echoChannel->GetChannel(), this);
  75. }
  76. /**
  77. * Create an instance of the Ultrasonic Sensor using the default module.
  78. * This is designed to supchannel the Daventech SRF04 and Vex ultrasonic sensors. This
  79. * constructor assumes that both digital I/O channels are in the default digital module.
  80. * @param pingChannel The digital output channel that sends the pulse to initiate the sensor sending
  81. * the ping.
  82. * @param echoChannel The digital input channel that receives the echo. The length of time that the
  83. * echo is high represents the round trip time of the ping, and the distance.
  84. * @param units The units returned in either kInches or kMilliMeters
  85. */
  86. Ultrasonic::Ultrasonic(uint32_t pingChannel, uint32_t echoChannel, DistanceUnit units)
  87. {
  88. m_pingChannel = new DigitalOutput(pingChannel);
  89. m_echoChannel = new DigitalInput(echoChannel);
  90. m_allocatedChannels = true;
  91. m_units = units;
  92. Initialize();
  93. }
  94. /**
  95. * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo channel and a DigitalOutput
  96. * for the ping channel.
  97. * @param pingChannel The digital output object that starts the sensor doing a ping. Requires a 10uS pulse to start.
  98. * @param echoChannel The digital input object that times the return pulse to determine the range.
  99. * @param units The units returned in either kInches or kMilliMeters
  100. */
  101. Ultrasonic::Ultrasonic(DigitalOutput *pingChannel, DigitalInput *echoChannel, DistanceUnit units)
  102. {
  103. if (pingChannel == NULL || echoChannel == NULL)
  104. {
  105. wpi_setWPIError(NullParameter);
  106. return;
  107. }
  108. m_allocatedChannels = false;
  109. m_pingChannel = pingChannel;
  110. m_echoChannel = echoChannel;
  111. m_units = units;
  112. Initialize();
  113. }
  114. /**
  115. * Create an instance of an Ultrasonic Sensor from a DigitalInput for the echo channel and a DigitalOutput
  116. * for the ping channel.
  117. * @param pingChannel The digital output object that starts the sensor doing a ping. Requires a 10uS pulse to start.
  118. * @param echoChannel The digital input object that times the return pulse to determine the range.
  119. * @param units The units returned in either kInches or kMilliMeters
  120. */
  121. Ultrasonic::Ultrasonic(DigitalOutput &pingChannel, DigitalInput &echoChannel, DistanceUnit units)
  122. {
  123. m_allocatedChannels = false;
  124. m_pingChannel = &pingChannel;
  125. m_echoChannel = &echoChannel;
  126. m_units = units;
  127. Initialize();
  128. }
  129. /**
  130. * Create an instance of the Ultrasonic sensor using specified modules.
  131. * This is designed to supchannel the Daventech SRF04 and Vex ultrasonic sensors. This
  132. * constructors takes the channel and module slot for each of the required digital I/O channels.
  133. * @param pingModuleNumber The digital module that the pingChannel is on.
  134. * @param pingChannel The digital output channel that sends the pulse to initiate the sensor
  135. * sending the ping.
  136. * @param echoModuleNumber The digital module that the echoChannel is on.
  137. * @param echoChannel The digital input channel that receives the echo. The length of time
  138. * that the echo is high represents the round trip time of the ping, and the distance.
  139. * @param units The units returned in either kInches or kMilliMeters
  140. */
  141. Ultrasonic::Ultrasonic(uint8_t pingModuleNumber, uint32_t pingChannel,
  142. uint8_t echoModuleNumber, uint32_t echoChannel, DistanceUnit units)
  143. {
  144. m_pingChannel = new DigitalOutput(pingModuleNumber, pingChannel);
  145. m_echoChannel = new DigitalInput(echoModuleNumber, echoChannel);
  146. m_allocatedChannels = true;
  147. m_units = units;
  148. Initialize();
  149. }
  150. /**
  151. * Destructor for the ultrasonic sensor.
  152. * Delete the instance of the ultrasonic sensor by freeing the allocated digital channels.
  153. * If the system was in automatic mode (round robin), then it is stopped, then started again
  154. * after this sensor is removed (provided this wasn't the last sensor).
  155. */
  156. Ultrasonic::~Ultrasonic()
  157. {
  158. bool wasAutomaticMode = m_automaticEnabled;
  159. SetAutomaticMode(false);
  160. if (m_allocatedChannels)
  161. {
  162. delete m_pingChannel;
  163. delete m_echoChannel;
  164. }
  165. wpi_assert(m_firstSensor != NULL);
  166. semTake(m_semaphore, WAIT_FOREVER);
  167. {
  168. if (this == m_firstSensor)
  169. {
  170. m_firstSensor = m_nextSensor;
  171. if (m_firstSensor == NULL)
  172. {
  173. SetAutomaticMode(false);
  174. }
  175. }
  176. else
  177. {
  178. wpi_assert(m_firstSensor->m_nextSensor != NULL);
  179. for (Ultrasonic *s = m_firstSensor; s != NULL; s = s->m_nextSensor)
  180. {
  181. if (this == s->m_nextSensor)
  182. {
  183. s->m_nextSensor = s->m_nextSensor->m_nextSensor;
  184. break;
  185. }
  186. }
  187. }
  188. }
  189. semGive(m_semaphore);
  190. if (m_firstSensor != NULL && wasAutomaticMode)
  191. SetAutomaticMode(true);
  192. }
  193. /**
  194. * Turn Automatic mode on/off.
  195. * When in Automatic mode, all sensors will fire in round robin, waiting a set
  196. * time between each sensor.
  197. * @param enabling Set to true if round robin scheduling should start for all the ultrasonic sensors. This
  198. * scheduling method assures that the sensors are non-interfering because no two sensors fire at the same time.
  199. * If another scheduling algorithm is preffered, it can be implemented by pinging the sensors manually and waiting
  200. * for the results to come back.
  201. */
  202. void Ultrasonic::SetAutomaticMode(bool enabling)
  203. {
  204. if (enabling == m_automaticEnabled)
  205. return; // ignore the case of no change
  206. m_automaticEnabled = enabling;
  207. if (enabling)
  208. {
  209. // enabling automatic mode.
  210. // Clear all the counters so no data is valid
  211. for (Ultrasonic *u = m_firstSensor; u != NULL; u = u->m_nextSensor)
  212. {
  213. u->m_counter->Reset();
  214. }
  215. // Start round robin task
  216. wpi_assert(m_task.Verify() == false); // should be false since was previously disabled
  217. m_task.Start();
  218. }
  219. else
  220. {
  221. // disabling automatic mode. Wait for background task to stop running.
  222. while (m_task.Verify())
  223. Wait(0.15); // just a little longer than the ping time for round-robin to stop
  224. // clear all the counters (data now invalid) since automatic mode is stopped
  225. for (Ultrasonic *u = m_firstSensor; u != NULL; u = u->m_nextSensor)
  226. {
  227. u->m_counter->Reset();
  228. }
  229. m_task.Stop();
  230. }
  231. }
  232. /**
  233. * Single ping to ultrasonic sensor.
  234. * Send out a single ping to the ultrasonic sensor. This only works if automatic (round robin)
  235. * mode is disabled. A single ping is sent out, and the counter should count the semi-period
  236. * when it comes in. The counter is reset to make the current value invalid.
  237. */
  238. void Ultrasonic::Ping()
  239. {
  240. // TODO: Either assert or disable, not both.
  241. wpi_assert(!m_automaticEnabled);
  242. SetAutomaticMode(false); // turn off automatic round robin if pinging single sensor
  243. m_counter->Reset(); // reset the counter to zero (invalid data now)
  244. m_pingChannel->Pulse(kPingTime); // do the ping to start getting a single range
  245. }
  246. /**
  247. * Check if there is a valid range measurement.
  248. * The ranges are accumulated in a counter that will increment on each edge of the echo (return)
  249. * signal. If the count is not at least 2, then the range has not yet been measured, and is invalid.
  250. */
  251. bool Ultrasonic::IsRangeValid()
  252. {
  253. return m_counter->Get() > 1;
  254. }
  255. /**
  256. * Get the range in inches from the ultrasonic sensor.
  257. * @return double Range in inches of the target returned from the ultrasonic sensor. If there is
  258. * no valid value yet, i.e. at least one measurement hasn't completed, then return 0.
  259. */
  260. double Ultrasonic::GetRangeInches()
  261. {
  262. if (IsRangeValid())
  263. return m_counter->GetPeriod() * kSpeedOfSoundInchesPerSec / 2.0;
  264. else
  265. return 0;
  266. }
  267. /**
  268. * Get the range in millimeters from the ultrasonic sensor.
  269. * @return double Range in millimeters of the target returned by the ultrasonic sensor.
  270. * If there is no valid value yet, i.e. at least one measurement hasn't complted, then return 0.
  271. */
  272. double Ultrasonic::GetRangeMM()
  273. {
  274. return GetRangeInches() * 25.4;
  275. }
  276. /**
  277. * Get the range in the current DistanceUnit for the PIDSource base object.
  278. *
  279. * @return The range in DistanceUnit
  280. */
  281. double Ultrasonic::PIDGet()
  282. {
  283. switch(m_units)
  284. {
  285. case Ultrasonic::kInches:
  286. return GetRangeInches();
  287. case Ultrasonic::kMilliMeters:
  288. return GetRangeMM();
  289. default:
  290. return 0.0;
  291. }
  292. }
  293. /**
  294. * Set the current DistanceUnit that should be used for the PIDSource base object.
  295. *
  296. * @param units The DistanceUnit that should be used.
  297. */
  298. void Ultrasonic::SetDistanceUnits(DistanceUnit units)
  299. {
  300. m_units = units;
  301. }
  302. /**
  303. * Get the current DistanceUnit that is used for the PIDSource base object.
  304. *
  305. * @return The type of DistanceUnit that is being used.
  306. */
  307. Ultrasonic::DistanceUnit Ultrasonic::GetDistanceUnits()
  308. {
  309. return m_units;
  310. }
  311. void Ultrasonic::UpdateTable() {
  312. if (m_table != NULL) {
  313. m_table->PutNumber("Value", GetRangeInches());
  314. }
  315. }
  316. void Ultrasonic::StartLiveWindowMode() {
  317. }
  318. void Ultrasonic::StopLiveWindowMode() {
  319. }
  320. std::string Ultrasonic::GetSmartDashboardType() {
  321. return "Ultrasonic";
  322. }
  323. void Ultrasonic::InitTable(ITable *subTable) {
  324. m_table = subTable;
  325. UpdateTable();
  326. }
  327. ITable * Ultrasonic::GetTable() {
  328. return m_table;
  329. }