blob: 0f0bf80455311191b7566849c8701d826b2b25ab [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 "DigitalModule.h"
8#include "I2C.h"
9#include "PWM.h"
10#include "Resource.h"
11#include "Synchronized.h"
12#include "WPIErrors.h"
13#include <math.h>
14#include <taskLib.h>
15
16static Resource *DIOChannels = NULL;
17static Resource *DO_PWMGenerators[tDIO::kNumSystems] = {NULL};
18
19/**
20 * Get an instance of an Digital Module.
21 * Singleton digital module creation where a module is allocated on the first use
22 * and the same module is returned on subsequent uses.
23 *
24 * @param moduleNumber The digital module to get (1 or 2).
25 */
26DigitalModule* DigitalModule::GetInstance(UINT8 moduleNumber)
27{
28 if (CheckDigitalModule(moduleNumber))
29 {
30 return (DigitalModule *)GetModule(nLoadOut::kModuleType_Digital, moduleNumber);
31 }
32
33 // If this wasn't caught before now, make sure we say what's wrong before we crash
34 char buf[64];
35 snprintf(buf, 64, "Digital Module %d", moduleNumber);
36 wpi_setGlobalWPIErrorWithContext(ModuleIndexOutOfRange, buf);
37
38 return NULL;
39}
40
41/**
42 * Create a new instance of an digital module.
43 * Create an instance of the digital module object. Initialize all the parameters
44 * to reasonable values on start.
45 * Setting a global value on an digital module can be done only once unless subsequent
46 * values are set the previously set value.
47 * Digital modules are a singleton, so the constructor is never called outside of this class.
48 *
49 * @param moduleNumber The digital module to create (1 or 2).
50 */
51DigitalModule::DigitalModule(UINT8 moduleNumber)
52 : Module(nLoadOut::kModuleType_Digital, moduleNumber)
53 , m_fpgaDIO (NULL)
54{
55 Resource::CreateResourceObject(&DIOChannels, tDIO::kNumSystems * kDigitalChannels);
56 Resource::CreateResourceObject(&DO_PWMGenerators[m_moduleNumber - 1], tDIO::kNumDO_PWMDutyCycleElements);
57 tRioStatusCode localStatus = NiFpga_Status_Success;
58 m_fpgaDIO = tDIO::create(m_moduleNumber - 1, &localStatus);
59 wpi_setError(localStatus);
60
61 // Make sure that the 9403 IONode has had a chance to initialize before continuing.
62 while(m_fpgaDIO->readLoopTiming(&localStatus) == 0) taskDelay(1);
63 if (m_fpgaDIO->readLoopTiming(&localStatus) != kExpectedLoopTiming)
64 {
65 char err[128];
66 sprintf(err, "DIO LoopTiming: %d, expecting: %d\n", m_fpgaDIO->readLoopTiming(&localStatus), kExpectedLoopTiming);
67 wpi_setWPIErrorWithContext(LoopTimingError, err);
68 }
69 m_fpgaDIO->writePWMConfig_Period(PWM::kDefaultPwmPeriod, &localStatus);
70 m_fpgaDIO->writePWMConfig_MinHigh(PWM::kDefaultMinPwmHigh, &localStatus);
71
72 // Ensure that PWM output values are set to OFF
73 for (UINT32 pwm_index = 1; pwm_index <= kPwmChannels; pwm_index++)
74 {
75 SetPWM(pwm_index, PWM::kPwmDisabled);
76 SetPWMPeriodScale(pwm_index, 3); // Set all to 4x by default.
77 }
78
79 // Turn off all relay outputs.
80 m_fpgaDIO->writeSlowValue_RelayFwd(0, &localStatus);
81 m_fpgaDIO->writeSlowValue_RelayRev(0, &localStatus);
82 wpi_setError(localStatus);
83
84 // Create a semaphore to protect changes to the digital output values
85 m_digitalSemaphore = semMCreate(SEM_Q_PRIORITY | SEM_DELETE_SAFE | SEM_INVERSION_SAFE);
86
87 // Create a semaphore to protect changes to the relay values
88 m_relaySemaphore = semMCreate(SEM_Q_PRIORITY | SEM_DELETE_SAFE | SEM_INVERSION_SAFE);
89
90 // Create a semaphore to protect changes to the DO PWM config
91 m_doPwmSemaphore = semMCreate(SEM_Q_PRIORITY | SEM_DELETE_SAFE | SEM_INVERSION_SAFE);
92
93 AddToSingletonList();
94}
95
96DigitalModule::~DigitalModule()
97{
98 semDelete(m_doPwmSemaphore);
99 m_doPwmSemaphore = NULL;
100 semDelete(m_relaySemaphore);
101 m_relaySemaphore = NULL;
102 semDelete(m_digitalSemaphore);
103 m_digitalSemaphore = NULL;
104 delete m_fpgaDIO;
105}
106
107/**
108 * Set a PWM channel to the desired value. The values range from 0 to 255 and the period is controlled
109 * by the PWM Period and MinHigh registers.
110 *
111 * @param channel The PWM channel to set.
112 * @param value The PWM value to set.
113 */
114void DigitalModule::SetPWM(UINT32 channel, UINT8 value)
115{
116 CheckPWMChannel(channel);
117 tRioStatusCode localStatus = NiFpga_Status_Success;
118 m_fpgaDIO->writePWMValue(channel - 1, value, &localStatus);
119 wpi_setError(localStatus);
120}
121
122/**
123 * Get a value from a PWM channel. The values range from 0 to 255.
124 *
125 * @param channel The PWM channel to read from.
126 * @return The raw PWM value.
127 */
128UINT8 DigitalModule::GetPWM(UINT32 channel)
129{
130 CheckPWMChannel(channel);
131 tRioStatusCode localStatus = NiFpga_Status_Success;
132 return m_fpgaDIO->readPWMValue(channel - 1, &localStatus);
133 wpi_setError(localStatus);
134}
135
136/**
137 * Set how how often the PWM signal is squelched, thus scaling the period.
138 *
139 * @param channel The PWM channel to configure.
140 * @param squelchMask The 2-bit mask of outputs to squelch.
141 */
142void DigitalModule::SetPWMPeriodScale(UINT32 channel, UINT32 squelchMask)
143{
144 CheckPWMChannel(channel);
145 tRioStatusCode localStatus = NiFpga_Status_Success;
146 m_fpgaDIO->writePWMPeriodScale(channel - 1, squelchMask, &localStatus);
147 wpi_setError(localStatus);
148}
149
150/**
151 * Set the state of a relay.
152 * Set the state of a relay output to be forward. Relays have two outputs and each is
153 * independently set to 0v or 12v.
154 */
155void DigitalModule::SetRelayForward(UINT32 channel, bool on)
156{
157 tRioStatusCode localStatus = NiFpga_Status_Success;
158 CheckRelayChannel(channel);
159 {
160 Synchronized sync(m_relaySemaphore);
161 UINT8 forwardRelays = m_fpgaDIO->readSlowValue_RelayFwd(&localStatus);
162 if (on)
163 forwardRelays |= 1 << (channel - 1);
164 else
165 forwardRelays &= ~(1 << (channel - 1));
166 m_fpgaDIO->writeSlowValue_RelayFwd(forwardRelays, &localStatus);
167 }
168 wpi_setError(localStatus);
169}
170
171/**
172 * Set the state of a relay.
173 * Set the state of a relay output to be reverse. Relays have two outputs and each is
174 * independently set to 0v or 12v.
175 */
176void DigitalModule::SetRelayReverse(UINT32 channel, bool on)
177{
178 tRioStatusCode localStatus = NiFpga_Status_Success;
179 CheckRelayChannel(channel);
180 {
181 Synchronized sync(m_relaySemaphore);
182 UINT8 reverseRelays = m_fpgaDIO->readSlowValue_RelayRev(&localStatus);
183 if (on)
184 reverseRelays |= 1 << (channel - 1);
185 else
186 reverseRelays &= ~(1 << (channel - 1));
187 m_fpgaDIO->writeSlowValue_RelayRev(reverseRelays, &localStatus);
188 }
189 wpi_setError(localStatus);
190}
191
192/**
193 * Get the current state of the forward relay channel
194 */
195bool DigitalModule::GetRelayForward(UINT32 channel)
196{
197 tRioStatusCode localStatus = NiFpga_Status_Success;
198 UINT8 forwardRelays = m_fpgaDIO->readSlowValue_RelayFwd(&localStatus);
199 wpi_setError(localStatus);
200 return (forwardRelays & (1 << (channel - 1))) != 0;
201}
202
203/**
204 * Get the current state of all of the forward relay channels on this module.
205 */
206UINT8 DigitalModule::GetRelayForward()
207{
208 tRioStatusCode localStatus = NiFpga_Status_Success;
209 UINT8 forwardRelays = m_fpgaDIO->readSlowValue_RelayFwd(&localStatus);
210 wpi_setError(localStatus);
211 return forwardRelays;
212}
213
214/**
215 * Get the current state of the reverse relay channel
216 */
217bool DigitalModule::GetRelayReverse(UINT32 channel)
218{
219 tRioStatusCode localStatus = NiFpga_Status_Success;
220 UINT8 reverseRelays = m_fpgaDIO->readSlowValue_RelayRev(&localStatus);
221 wpi_setError(localStatus);
222 return (reverseRelays & (1 << (channel - 1))) != 0;
223
224}
225
226/**
227 * Get the current state of all of the reverse relay channels on this module.
228 */
229UINT8 DigitalModule::GetRelayReverse()
230{
231 tRioStatusCode localStatus = NiFpga_Status_Success;
232 UINT8 reverseRelays = m_fpgaDIO->readSlowValue_RelayRev(&localStatus);
233 wpi_setError(localStatus);
234 return reverseRelays;
235}
236
237
238/**
239 * Allocate Digital I/O channels.
240 * Allocate channels so that they are not accidently reused. Also the direction is set at the
241 * time of the allocation.
242 *
243 * @param channel The Digital I/O channel
244 * @param input If true open as input; if false open as output
245 * @return Was successfully allocated
246 */
247bool DigitalModule::AllocateDIO(UINT32 channel, bool input)
248{
249 char buf[64];
250 snprintf(buf, 64, "DIO %d (Module %d)", channel, m_moduleNumber);
251 if (DIOChannels->Allocate(kDigitalChannels * (m_moduleNumber - 1) + channel - 1, buf) == ~0ul) return false;
252 tRioStatusCode localStatus = NiFpga_Status_Success;
253 {
254 Synchronized sync(m_digitalSemaphore);
255 UINT32 bitToSet = 1 << (RemapDigitalChannel(channel - 1));
256 UINT32 outputEnable = m_fpgaDIO->readOutputEnable(&localStatus);
257 UINT32 outputEnableValue;
258 if (input)
259 {
260 outputEnableValue = outputEnable & (~bitToSet); // clear the bit for read
261 }
262 else
263 {
264 outputEnableValue = outputEnable | bitToSet; // set the bit for write
265 }
266 m_fpgaDIO->writeOutputEnable(outputEnableValue, &localStatus);
267 }
268 wpi_setError(localStatus);
269 return true;
270}
271
272/**
273 * Free the resource associated with a digital I/O channel.
274 *
275 * @param channel The Digital I/O channel to free
276 */
277void DigitalModule::FreeDIO(UINT32 channel)
278{
279 DIOChannels->Free(kDigitalChannels * (m_moduleNumber - 1) + channel - 1);
280}
281
282/**
283 * Write a digital I/O bit to the FPGA.
284 * Set a single value on a digital I/O channel.
285 *
286 * @param channel The Digital I/O channel
287 * @param value The state to set the digital channel (if it is configured as an output)
288 */
289void DigitalModule::SetDIO(UINT32 channel, short value)
290{
291 if (value != 0 && value != 1)
292 {
293 wpi_setWPIError(NonBinaryDigitalValue);
294 if (value != 0)
295 value = 1;
296 }
297 tRioStatusCode localStatus = NiFpga_Status_Success;
298 {
299 Synchronized sync(m_digitalSemaphore);
300 UINT16 currentDIO = m_fpgaDIO->readDO(&localStatus);
301 if(value == 0)
302 {
303 currentDIO = currentDIO & ~(1 << RemapDigitalChannel(channel - 1));
304 }
305 else if (value == 1)
306 {
307 currentDIO = currentDIO | (1 << RemapDigitalChannel(channel - 1));
308 }
309 m_fpgaDIO->writeDO(currentDIO, &localStatus);
310 }
311 wpi_setError(localStatus);
312}
313
314/**
315 * Read a digital I/O bit from the FPGA.
316 * Get a single value from a digital I/O channel.
317 *
318 * @param channel The digital I/O channel
319 * @return The state of the specified channel
320 */
321bool DigitalModule::GetDIO(UINT32 channel)
322{
323 tRioStatusCode localStatus = NiFpga_Status_Success;
324 UINT32 currentDIO = m_fpgaDIO->readDI(&localStatus);
325 wpi_setError(localStatus);
326
327 //Shift 00000001 over channel-1 places.
328 //AND it against the currentDIO
329 //if it == 0, then return false
330 //else return true
331 return ((currentDIO >> RemapDigitalChannel(channel - 1)) & 1) != 0;
332}
333
334/**
335 * Read the state of all the Digital I/O lines from the FPGA
336 * These are not remapped to logical order. They are still in hardware order.
337 */
338UINT16 DigitalModule::GetDIO()
339{
340 tRioStatusCode localStatus = NiFpga_Status_Success;
341 UINT32 currentDIO = m_fpgaDIO->readDI(&localStatus);
342 wpi_setError(localStatus);
343 return currentDIO;
344}
345
346/**
347 * Read the direction of a the Digital I/O lines
348 * A 1 bit means output and a 0 bit means input.
349 *
350 * @param channel The digital I/O channel
351 * @return The direction of the specified channel
352 */
353bool DigitalModule::GetDIODirection(UINT32 channel)
354{
355 tRioStatusCode localStatus = NiFpga_Status_Success;
356 UINT32 currentOutputEnable = m_fpgaDIO->readOutputEnable(&localStatus);
357 wpi_setError(localStatus);
358
359 //Shift 00000001 over channel-1 places.
360 //AND it against the currentOutputEnable
361 //if it == 0, then return false
362 //else return true
363 return ((currentOutputEnable >> RemapDigitalChannel(channel - 1)) & 1) != 0;
364}
365
366/**
367 * Read the direction of all the Digital I/O lines from the FPGA
368 * A 1 bit means output and a 0 bit means input.
369 * These are not remapped to logical order. They are still in hardware order.
370 */
371UINT16 DigitalModule::GetDIODirection()
372{
373 tRioStatusCode localStatus = NiFpga_Status_Success;
374 UINT32 currentOutputEnable = m_fpgaDIO->readOutputEnable(&localStatus);
375 wpi_setError(localStatus);
376 return currentOutputEnable;
377}
378
379/**
380 * Generate a single pulse.
381 * Write a pulse to the specified digital output channel. There can only be a single pulse going at any time.
382 *
383 * @param channel The Digital Output channel that the pulse should be output on
384 * @param pulseLength The active length of the pulse (in seconds)
385 */
386void DigitalModule::Pulse(UINT32 channel, float pulseLength)
387{
388 UINT16 mask = 1 << RemapDigitalChannel(channel - 1);
389 tRioStatusCode localStatus = NiFpga_Status_Success;
390 m_fpgaDIO->writePulseLength((UINT8)(1.0e9 * pulseLength / (m_fpgaDIO->readLoopTiming(&localStatus) * 25)), &localStatus);
391 m_fpgaDIO->writePulse(mask, &localStatus);
392 wpi_setError(localStatus);
393}
394
395/**
396 * Check a DIO line to see if it is currently generating a pulse.
397 *
398 * @return A pulse is in progress
399 */
400bool DigitalModule::IsPulsing(UINT32 channel)
401{
402 UINT16 mask = 1 << RemapDigitalChannel(channel - 1);
403 tRioStatusCode localStatus = NiFpga_Status_Success;
404 UINT16 pulseRegister = m_fpgaDIO->readPulse(&localStatus);
405 wpi_setError(localStatus);
406 return (pulseRegister & mask) != 0;
407}
408
409/**
410 * Check if any DIO line is currently generating a pulse.
411 *
412 * @return A pulse on some line is in progress
413 */
414bool DigitalModule::IsPulsing()
415{
416 tRioStatusCode localStatus = NiFpga_Status_Success;
417 UINT16 pulseRegister = m_fpgaDIO->readPulse(&localStatus);
418 wpi_setError(localStatus);
419 return pulseRegister != 0;
420}
421
422/**
423 * Allocate a DO PWM Generator.
424 * Allocate PWM generators so that they are not accidently reused.
425 *
426 * @return PWM Generator refnum
427 */
428UINT32 DigitalModule::AllocateDO_PWM()
429{
430 char buf[64];
431 snprintf(buf, 64, "DO_PWM (Module: %d)", m_moduleNumber);
432 return DO_PWMGenerators[(m_moduleNumber - 1)]->Allocate(buf);
433}
434
435/**
436 * Free the resource associated with a DO PWM generator.
437 *
438 * @param pwmGenerator The pwmGen to free that was allocated with AllocateDO_PWM()
439 */
440void DigitalModule::FreeDO_PWM(UINT32 pwmGenerator)
441{
442 if (pwmGenerator == ~0ul) return;
443 DO_PWMGenerators[(m_moduleNumber - 1)]->Free(pwmGenerator);
444}
445
446/**
447 * Change the frequency of the DO PWM generator.
448 *
449 * The valid range is from 0.6 Hz to 19 kHz. The frequency resolution is logarithmic.
450 *
451 * @param rate The frequency to output all digital output PWM signals on this module.
452 */
453void DigitalModule::SetDO_PWMRate(float rate)
454{
455 // Currently rounding in the log rate domain... heavy weight toward picking a higher freq.
456 // TODO: Round in the linear rate domain.
457 tRioStatusCode localStatus = NiFpga_Status_Success;
458 UINT8 pwmPeriodPower = (UINT8)(log(1.0 / (m_fpgaDIO->readLoopTiming(&localStatus) * 0.25E-6 * rate))/log(2.0) + 0.5);
459 m_fpgaDIO->writeDO_PWMConfig_PeriodPower(pwmPeriodPower, &localStatus);
460 wpi_setError(localStatus);
461}
462
463/**
464 * Configure which DO channel the PWM siganl is output on
465 *
466 * @param pwmGenerator The generator index reserved by AllocateDO_PWM()
467 * @param channel The Digital Output channel to output on
468 */
469void DigitalModule::SetDO_PWMOutputChannel(UINT32 pwmGenerator, UINT32 channel)
470{
471 if (pwmGenerator == ~0ul) return;
472 tRioStatusCode localStatus = NiFpga_Status_Success;
473 switch(pwmGenerator)
474 {
475 case 0:
476 m_fpgaDIO->writeDO_PWMConfig_OutputSelect_0(RemapDigitalChannel(channel - 1), &localStatus);
477 break;
478 case 1:
479 m_fpgaDIO->writeDO_PWMConfig_OutputSelect_1(RemapDigitalChannel(channel - 1), &localStatus);
480 break;
481 case 2:
482 m_fpgaDIO->writeDO_PWMConfig_OutputSelect_2(RemapDigitalChannel(channel - 1), &localStatus);
483 break;
484 case 3:
485 m_fpgaDIO->writeDO_PWMConfig_OutputSelect_3(RemapDigitalChannel(channel - 1), &localStatus);
486 break;
487 }
488 wpi_setError(localStatus);
489}
490
491/**
492 * Configure the duty-cycle of the PWM generator
493 *
494 * @param pwmGenerator The generator index reserved by AllocateDO_PWM()
495 * @param dutyCycle The percent duty cycle to output [0..1].
496 */
497void DigitalModule::SetDO_PWMDutyCycle(UINT32 pwmGenerator, float dutyCycle)
498{
499 if (pwmGenerator == ~0ul) return;
500 if (dutyCycle > 1.0) dutyCycle = 1.0;
501 if (dutyCycle < 0.0) dutyCycle = 0.0;
502 float rawDutyCycle = 256.0 * dutyCycle;
503 if (rawDutyCycle > 255.5) rawDutyCycle = 255.5;
504 tRioStatusCode localStatus = NiFpga_Status_Success;
505 {
506 Synchronized sync(m_doPwmSemaphore);
507 UINT8 pwmPeriodPower = m_fpgaDIO->readDO_PWMConfig_PeriodPower(&localStatus);
508 if (pwmPeriodPower < 4)
509 {
510 // The resolution of the duty cycle drops close to the highest frequencies.
511 rawDutyCycle = rawDutyCycle / pow(2.0, 4 - pwmPeriodPower);
512 }
513 m_fpgaDIO->writeDO_PWMDutyCycle(pwmGenerator, (UINT8)rawDutyCycle, &localStatus);
514 }
515 wpi_setError(localStatus);
516}
517
518/**
519 * Return a pointer to an I2C object for this digital module
520 * The caller is responsible for deleting the pointer.
521 *
522 * @param address The address of the device on the I2C bus
523 * @return A pointer to an I2C object to talk to the device at address
524 */
525I2C* DigitalModule::GetI2C(UINT32 address)
526{
527 return new I2C(this, address);
528}
529
530