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