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