1 //*****************************************************************************
2 //
3 // can.c - Driver for the CAN module.
4 //
5 // Copyright (c) 2006-2011 Texas Instruments Incorporated.  All rights reserved.
6 // Software License Agreement
7 //
8 // Texas Instruments (TI) is supplying this software for use solely and
9 // exclusively on TI's microcontroller products. The software is owned by
10 // TI and/or its suppliers, and is protected under applicable copyright
11 // laws. You may not combine this software with "viral" open-source
12 // software in order to form a larger program.
13 //
14 // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
15 // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
16 // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17 // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
18 // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
19 // DAMAGES, FOR ANY REASON WHATSOEVER.
20 //
21 // This is part of revision 8264 of the Stellaris Peripheral Driver Library.
22 //
23 //*****************************************************************************
24 
25 //*****************************************************************************
26 //
27 //! \addtogroup can_api
28 //! @{
29 //
30 //*****************************************************************************
31 
32 #include "inc/hw_can.h"
33 #include "inc/hw_ints.h"
34 #include "inc/hw_nvic.h"
35 #include "inc/hw_memmap.h"
36 #include "inc/hw_types.h"
37 #include "driverlib/can.h"
38 #include "driverlib/debug.h"
39 #include "driverlib/interrupt.h"
40 
41 //*****************************************************************************
42 //
43 // This is the maximum number that can be stored as an 11bit Message
44 // identifier.
45 //
46 //*****************************************************************************
47 #define CAN_MAX_11BIT_MSG_ID    0x7ff
48 
49 //*****************************************************************************
50 //
51 // This is used as the loop delay for accessing the CAN controller registers.
52 //
53 //*****************************************************************************
54 #define CAN_RW_DELAY            5
55 
56 //*****************************************************************************
57 //
58 // The maximum CAN bit timing divisor is 19.
59 //
60 //*****************************************************************************
61 #define CAN_MAX_BIT_DIVISOR     19
62 
63 //*****************************************************************************
64 //
65 // The minimum CAN bit timing divisor is 4.
66 //
67 //*****************************************************************************
68 #define CAN_MIN_BIT_DIVISOR     4
69 
70 //*****************************************************************************
71 //
72 // The maximum CAN pre-divisor is 1024.
73 //
74 //*****************************************************************************
75 #define CAN_MAX_PRE_DIVISOR     1024
76 
77 //*****************************************************************************
78 //
79 // The minimum CAN pre-divisor is 1.
80 //
81 //*****************************************************************************
82 #define CAN_MIN_PRE_DIVISOR     1
83 
84 //*****************************************************************************
85 //
86 // Converts a set of CAN bit timing values into the value that needs to be
87 // programmed into the CAN_BIT register to achieve those timings.
88 //
89 //*****************************************************************************
90 #define CAN_BIT_VALUE(seg1, seg2, sjw)                                        \
91                                 ((((seg1 - 1) << CAN_BIT_TSEG1_S) &           \
92                                   CAN_BIT_TSEG1_M) |                          \
93                                  (((seg2 - 1) << CAN_BIT_TSEG2_S) &           \
94                                   CAN_BIT_TSEG2_M) |                          \
95                                  (((sjw - 1) << CAN_BIT_SJW_S) &              \
96                                   CAN_BIT_SJW_M))
97 
98 //*****************************************************************************
99 //
100 // This table is used by the CANBitRateSet() API as the register defaults for
101 // the bit timing values.
102 //
103 //*****************************************************************************
104 static const unsigned short g_usCANBitValues[] =
105 {
106     CAN_BIT_VALUE(2, 1, 1),     // 4 clocks/bit
107     CAN_BIT_VALUE(3, 1, 1),     // 5 clocks/bit
108     CAN_BIT_VALUE(3, 2, 2),     // 6 clocks/bit
109     CAN_BIT_VALUE(4, 2, 2),     // 7 clocks/bit
110     CAN_BIT_VALUE(4, 3, 3),     // 8 clocks/bit
111     CAN_BIT_VALUE(5, 3, 3),     // 9 clocks/bit
112     CAN_BIT_VALUE(5, 4, 4),     // 10 clocks/bit
113     CAN_BIT_VALUE(6, 4, 4),     // 11 clocks/bit
114     CAN_BIT_VALUE(6, 5, 4),     // 12 clocks/bit
115     CAN_BIT_VALUE(7, 5, 4),     // 13 clocks/bit
116     CAN_BIT_VALUE(7, 6, 4),     // 14 clocks/bit
117     CAN_BIT_VALUE(8, 6, 4),     // 15 clocks/bit
118     CAN_BIT_VALUE(8, 7, 4),     // 16 clocks/bit
119     CAN_BIT_VALUE(9, 7, 4),     // 17 clocks/bit
120     CAN_BIT_VALUE(9, 8, 4),     // 18 clocks/bit
121     CAN_BIT_VALUE(10, 8, 4)     // 19 clocks/bit
122 };
123 
124 //*****************************************************************************
125 //
126 //! \internal
127 //! Checks a CAN base address.
128 //!
129 //! \param ulBase is the base address of the CAN controller.
130 //!
131 //! This function determines if a CAN controller base address is valid.
132 //!
133 //! \return Returns \b true if the base address is valid and \b false
134 //! otherwise.
135 //
136 //*****************************************************************************
137 #ifdef DEBUG
138 static tBoolean
CANBaseValid(unsigned long ulBase)139 CANBaseValid(unsigned long ulBase)
140 {
141     return((ulBase == CAN0_BASE) || (ulBase == CAN1_BASE) ||
142            (ulBase == CAN2_BASE));
143 }
144 #endif
145 
146 //*****************************************************************************
147 //
148 //! \internal
149 //!
150 //! Returns the CAN controller interrupt number.
151 //!
152 //! \param ulBase is the base address of the selected CAN controller
153 //!
154 //! Given a CAN controller base address, this function returns the
155 //! corresponding interrupt number.
156 //!
157 //! This function replaces the original CANGetIntNumber() API and performs the
158 //! same actions.  A macro is provided in <tt>can.h</tt> to map the original
159 //! API to this API.
160 //!
161 //! \return Returns a CAN interrupt number, or -1 if \e ulPort is invalid.
162 //
163 //*****************************************************************************
164 static long
CANIntNumberGet(unsigned long ulBase)165 CANIntNumberGet(unsigned long ulBase)
166 {
167     long lIntNumber;
168 
169     //
170     // Return the interrupt number for the given CAN controller.
171     //
172     switch(ulBase)
173     {
174         //
175         // Return the interrupt number for CAN 0
176         //
177         case CAN0_BASE:
178         {
179             lIntNumber = INT_CAN0;
180             break;
181         }
182 
183         //
184         // Return the interrupt number for CAN 1
185         //
186         case CAN1_BASE:
187         {
188             lIntNumber = INT_CAN1;
189             break;
190         }
191 
192         //
193         // Return the interrupt number for CAN 2
194         //
195         case CAN2_BASE:
196         {
197             lIntNumber = INT_CAN2;
198             break;
199         }
200 
201         //
202         // Return -1 to indicate a bad address was passed in.
203         //
204         default:
205         {
206             lIntNumber = -1;
207         }
208     }
209     return(lIntNumber);
210 }
211 
212 //*****************************************************************************
213 //
214 //! \internal
215 //!
216 //! Reads a CAN controller register.
217 //!
218 //! \param ulRegAddress is the full address of the CAN register to be read.
219 //!
220 //! This function performs the necessary synchronization to read from a CAN
221 //! controller register.
222 //!
223 //! This function replaces the original CANReadReg() API and performs the same
224 //! actions.  A macro is provided in <tt>can.h</tt> to map the original API to
225 //! this API.
226 //!
227 //! \note This function provides the delay required to access CAN registers.
228 //! This delay is required when accessing CAN registers directly.
229 //!
230 //! \return Returns the value read from the register.
231 //
232 //*****************************************************************************
233 static unsigned long
CANRegRead(unsigned long ulRegAddress)234 CANRegRead(unsigned long ulRegAddress)
235 {
236     volatile unsigned long ulDelay;
237     unsigned long ulRetVal;
238     unsigned long ulIntNumber;
239     unsigned long ulReenableInts;
240 
241     //
242     // Get the CAN interrupt number from the register base address.
243     //
244     ulIntNumber = CANIntNumberGet(ulRegAddress & 0xfffff000);
245 
246     //
247     // Make sure that the CAN base address was valid.
248     //
249     ASSERT(ulIntNumber != (unsigned long)-1);
250 
251     //
252     // Remember current state so that CAN interrupts are only re-enabled if
253     // they were already enabled.
254     //
255     ulReenableInts = HWREG(NVIC_EN1) & (1 << (ulIntNumber - 48));
256 
257     //
258     // If the CAN interrupt was enabled then disable it.
259     //
260     if(ulReenableInts)
261     {
262         IntDisable(ulIntNumber);
263     }
264 
265     //
266     // Trigger the initial read to the CAN controller.  The value returned at
267     // this point is not valid.
268     //
269     HWREG(ulRegAddress);
270 
271     //
272     // This delay is necessary for the CAN have the correct data on the bus.
273     //
274     for(ulDelay = 0; ulDelay < CAN_RW_DELAY; ulDelay++)
275     {
276     }
277 
278     //
279     // Do the final read that has the valid value of the register.
280     //
281     ulRetVal = HWREG(ulRegAddress);
282 
283     //
284     // Enable CAN interrupts if they were enabled before this call.
285     //
286     if(ulReenableInts)
287     {
288         IntEnable(ulIntNumber);
289     }
290 
291     return(ulRetVal);
292 }
293 
294 //*****************************************************************************
295 //
296 //! \internal
297 //!
298 //! Writes a CAN controller register.
299 //!
300 //! \param ulRegAddress is the full address of the CAN register to be written.
301 //! \param ulRegValue is the value to write into the register specified by
302 //! \e ulRegAddress.
303 //!
304 //! This function takes care of the synchronization necessary to write to a
305 //! CAN controller register.
306 //!
307 //! This function replaces the original CANWriteReg() API and performs the same
308 //! actions.  A macro is provided in <tt>can.h</tt> to map the original API to
309 //! this API.
310 //!
311 //! \note The delays in this function are required when accessing CAN registers
312 //! directly.
313 //!
314 //! \return None.
315 //
316 //*****************************************************************************
317 static void
CANRegWrite(unsigned long ulRegAddress,unsigned long ulRegValue)318 CANRegWrite(unsigned long ulRegAddress, unsigned long ulRegValue)
319 {
320     volatile unsigned long ulDelay;
321 
322     //
323     // Trigger the initial write to the CAN controller.  The value will not make
324     // it out to the CAN controller for CAN_RW_DELAY cycles.
325     //
326     HWREG(ulRegAddress) = ulRegValue;
327 
328     //
329     // Delay to allow the CAN controller to receive the new data.
330     //
331     for(ulDelay = 0; ulDelay < CAN_RW_DELAY; ulDelay++)
332     {
333     }
334 }
335 
336 //*****************************************************************************
337 //
338 //! \internal
339 //!
340 //! Copies data from a buffer to the CAN Data registers.
341 //!
342 //! \param pucData is a pointer to the data to be written out to the CAN
343 //! controller's data registers.
344 //! \param pulRegister is an unsigned long pointer to the first register of the
345 //! CAN controller's data registers.  For example, in order to use the IF1
346 //! register set on CAN controller 0, the value would be: \b CAN0_BASE \b +
347 //! \b CAN_O_IF1DA1.
348 //! \param iSize is the number of bytes to copy into the CAN controller.
349 //!
350 //! This function takes the steps necessary to copy data from a contiguous
351 //! buffer in memory into the non-contiguous data registers used by the CAN
352 //! controller.  This function is rarely used outside of the CANMessageSet()
353 //! function.
354 //!
355 //! This function replaces the original CANWriteDataReg() API and performs the
356 //! same actions.  A macro is provided in <tt>can.h</tt> to map the original
357 //! API to this API.
358 //!
359 //! \return None.
360 //
361 //*****************************************************************************
362 static void
CANDataRegWrite(unsigned char * pucData,unsigned long * pulRegister,unsigned long ulSize)363 CANDataRegWrite(unsigned char *pucData, unsigned long *pulRegister,
364                 unsigned long ulSize)
365 {
366     unsigned long ulIdx, ulValue;
367 
368     //
369     // Loop always copies 1 or 2 bytes per iteration.
370     //
371     for(ulIdx = 0; ulIdx < ulSize; )
372     {
373 
374         //
375         // Write out the data 16 bits at a time since this is how the registers
376         // are aligned in memory.
377         //
378         ulValue = pucData[ulIdx++];
379 
380         //
381         // Only write the second byte if needed otherwise it will be zero.
382         //
383         if(ulIdx < ulSize)
384         {
385             ulValue |= (pucData[ulIdx++] << 8);
386         }
387         CANRegWrite((unsigned long)(pulRegister++), ulValue);
388     }
389 }
390 
391 //*****************************************************************************
392 //
393 //! \internal
394 //!
395 //! Copies data from a buffer to the CAN Data registers.
396 //!
397 //! \param pucData is a pointer to the location to store the data read from the
398 //! CAN controller's data registers.
399 //! \param pulRegister is an unsigned long pointer to the first register of the
400 //! CAN controller's data registers.  For example, in order to use the IF1
401 //! register set on CAN controller 1, the value would be: \b CAN0_BASE \b +
402 //! \b CAN_O_IF1DA1.
403 //! \param iSize is the number of bytes to copy from the CAN controller.
404 //!
405 //! This function takes the steps necessary to copy data to a contiguous buffer
406 //! in memory from the non-contiguous data registers used by the CAN
407 //! controller.  This function is rarely used outside of the CANMessageGet()
408 //! function.
409 //!
410 //! This function replaces the original CANReadDataReg() API and performs the
411 //! same actions.  A macro is provided in <tt>can.h</tt> to map the original
412 //! API to this API.
413 //!
414 //! \return None.
415 //
416 //*****************************************************************************
417 static void
CANDataRegRead(unsigned char * pucData,unsigned long * pulRegister,unsigned long ulSize)418 CANDataRegRead(unsigned char *pucData, unsigned long *pulRegister,
419                unsigned long ulSize)
420 {
421     unsigned long ulIdx, ulValue;
422 
423     //
424     // Loop always copies 1 or 2 bytes per iteration.
425     //
426     for(ulIdx = 0; ulIdx < ulSize; )
427     {
428         //
429         // Read out the data 16 bits at a time since this is how the registers
430         // are aligned in memory.
431         //
432         ulValue = CANRegRead((unsigned long)(pulRegister++));
433 
434         //
435         // Store the first byte.
436         //
437         pucData[ulIdx++] = (unsigned char)ulValue;
438 
439         //
440         // Only read the second byte if needed.
441         //
442         if(ulIdx < ulSize)
443         {
444             pucData[ulIdx++] = (unsigned char)(ulValue >> 8);
445         }
446     }
447 }
448 
449 //*****************************************************************************
450 //
451 //! Initializes the CAN controller after reset.
452 //!
453 //! \param ulBase is the base address of the CAN controller.
454 //!
455 //! After reset, the CAN controller is left in the disabled state.  However,
456 //! the memory used for message objects contains undefined values and must be
457 //! cleared prior to enabling the CAN controller the first time.  This prevents
458 //! unwanted transmission or reception of data before the message objects are
459 //! configured.  This function must be called before enabling the controller
460 //! the first time.
461 //!
462 //! \return None.
463 //
464 //*****************************************************************************
465 void
CANInit(unsigned long ulBase)466 CANInit(unsigned long ulBase)
467 {
468     unsigned long ulMsg;
469 
470     //
471     // Check the arguments.
472     //
473     ASSERT(CANBaseValid(ulBase));
474 
475     //
476     // Place CAN controller in init state, regardless of previous state.  This
477     // will put controller in idle, and allow the message object RAM to be
478     // programmed.
479     //
480     CANRegWrite(ulBase + CAN_O_CTL, CAN_CTL_INIT);
481 
482     //
483     // Wait for busy bit to clear
484     //
485     while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY)
486     {
487     }
488 
489     //
490     // Clear the message value bit in the arbitration register.  This indicates
491     // the message is not valid and is a "safe" condition to leave the message
492     // object.  The same arb reg is used to program all the message objects.
493     //
494     CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_WRNRD | CAN_IF1CMSK_ARB |
495                 CAN_IF1CMSK_CONTROL);
496     CANRegWrite(ulBase + CAN_O_IF1ARB2, 0);
497     CANRegWrite(ulBase + CAN_O_IF1MCTL, 0);
498 
499     //
500     // Loop through to program all 32 message objects
501     //
502     for(ulMsg = 1; ulMsg <= 32; ulMsg++)
503     {
504         //
505         // Wait for busy bit to clear
506         //
507         while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY)
508         {
509         }
510 
511         //
512         // Initiate programming the message object
513         //
514         CANRegWrite(ulBase + CAN_O_IF1CRQ, ulMsg);
515     }
516 
517     //
518     // Make sure that the interrupt and new data flags are updated for the
519     // message objects.
520     //
521     CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_NEWDAT |
522                 CAN_IF1CMSK_CLRINTPND);
523 
524     //
525     // Loop through to program all 32 message objects
526     //
527     for(ulMsg = 1; ulMsg <= 32; ulMsg++)
528     {
529         //
530         // Wait for busy bit to clear.
531         //
532         while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY)
533         {
534         }
535 
536         //
537         // Initiate programming the message object
538         //
539         CANRegWrite(ulBase + CAN_O_IF1CRQ, ulMsg);
540     }
541 
542     //
543     // Acknowledge any pending status interrupts.
544     //
545     CANRegRead(ulBase + CAN_O_STS);
546 }
547 
548 //*****************************************************************************
549 //
550 //! Enables the CAN controller.
551 //!
552 //! \param ulBase is the base address of the CAN controller to enable.
553 //!
554 //! Enables the CAN controller for message processing.  Once enabled, the
555 //! controller automatically transmits any pending frames, and processes any
556 //! received frames.  The controller can be stopped by calling CANDisable().
557 //! Prior to calling CANEnable(), CANInit() should have been called to
558 //! initialize the controller and the CAN bus clock should be configured by
559 //! calling CANBitTimingSet().
560 //!
561 //! \return None.
562 //
563 //*****************************************************************************
564 void
CANEnable(unsigned long ulBase)565 CANEnable(unsigned long ulBase)
566 {
567     //
568     // Check the arguments.
569     //
570     ASSERT(CANBaseValid(ulBase));
571 
572     //
573     // Clear the init bit in the control register.
574     //
575     CANRegWrite(ulBase + CAN_O_CTL,
576                 CANRegRead(ulBase + CAN_O_CTL) & ~CAN_CTL_INIT);
577 }
578 
579 //*****************************************************************************
580 //
581 //! Disables the CAN controller.
582 //!
583 //! \param ulBase is the base address of the CAN controller to disable.
584 //!
585 //! Disables the CAN controller for message processing.  When disabled, the
586 //! controller no longer automatically processes data on the CAN bus.  The
587 //! controller can be restarted by calling CANEnable().  The state of the CAN
588 //! controller and the message objects in the controller are left as they were
589 //! before this call was made.
590 //!
591 //! \return None.
592 //
593 //*****************************************************************************
594 void
CANDisable(unsigned long ulBase)595 CANDisable(unsigned long ulBase)
596 {
597     //
598     // Check the arguments.
599     //
600     ASSERT(CANBaseValid(ulBase));
601 
602     //
603     // Set the init bit in the control register.
604     //
605     CANRegWrite(ulBase + CAN_O_CTL,
606                 CANRegRead(ulBase + CAN_O_CTL) | CAN_CTL_INIT);
607 }
608 
609 //*****************************************************************************
610 //
611 //! Reads the current settings for the CAN controller bit timing.
612 //!
613 //! \param ulBase is the base address of the CAN controller.
614 //! \param pClkParms is a pointer to a structure to hold the timing parameters.
615 //!
616 //! This function reads the current configuration of the CAN controller bit
617 //! clock timing and stores the resulting information in the structure
618 //! supplied by the caller.  Refer to CANBitTimingSet() for the meaning of the
619 //! values that are returned in the structure pointed to by \e pClkParms.
620 //!
621 //! This function replaces the original CANGetBitTiming() API and performs the
622 //! same actions.  A macro is provided in <tt>can.h</tt> to map the original
623 //! API to this API.
624 //!
625 //! \return None.
626 //
627 //*****************************************************************************
628 void
CANBitTimingGet(unsigned long ulBase,tCANBitClkParms * pClkParms)629 CANBitTimingGet(unsigned long ulBase, tCANBitClkParms *pClkParms)
630 {
631     unsigned long ulBitReg;
632 
633     //
634     // Check the arguments.
635     //
636     ASSERT(CANBaseValid(ulBase));
637     ASSERT(pClkParms != 0);
638 
639     //
640     // Read out all the bit timing values from the CAN controller registers.
641     //
642     ulBitReg = CANRegRead(ulBase + CAN_O_BIT);
643 
644     //
645     // Set the phase 2 segment.
646     //
647     pClkParms->ulPhase2Seg =
648         ((ulBitReg & CAN_BIT_TSEG2_M) >> CAN_BIT_TSEG2_S) + 1;
649 
650     //
651     // Set the phase 1 segment.
652     //
653     pClkParms->ulSyncPropPhase1Seg =
654         ((ulBitReg & CAN_BIT_TSEG1_M) >> CAN_BIT_TSEG1_S) + 1;
655 
656     //
657     // Set the synchronous jump width.
658     //
659     pClkParms->ulSJW = ((ulBitReg & CAN_BIT_SJW_M) >> CAN_BIT_SJW_S) + 1;
660 
661     //
662     // Set the pre-divider for the CAN bus bit clock.
663     //
664     pClkParms->ulQuantumPrescaler =
665         ((ulBitReg & CAN_BIT_BRP_M) |
666          ((CANRegRead(ulBase + CAN_O_BRPE) & CAN_BRPE_BRPE_M) << 6)) + 1;
667 }
668 
669 //*****************************************************************************
670 //
671 //! Sets the CAN bit timing values to a nominal setting based on a desired
672 //! bit rate.
673 //!
674 //! \param ulBase is the base address of the CAN controller.
675 //! \param ulSourceClock is the system clock for the device in Hz.
676 //! \param ulBitRate is the desired bit rate.
677 //!
678 //! This function sets the CAN bit timing for the bit rate passed in the
679 //! \e ulBitRate parameter based on the \e ulSourceClock parameter.  Because the
680 //! CAN clock is based off of the system clock, the calling function should pass
681 //! in the source clock rate either by retrieving it from SysCtlClockGet() or
682 //! using a specific value in Hz.  The CAN bit timing is calculated assuming a
683 //! minimal amount of propagation delay, which works for most cases where
684 //! the network length is short.  If tighter timing requirements or longer
685 //! network lengths are needed, then the CANBitTimingSet() function is
686 //! available for full customization of all of the CAN bit timing values.
687 //! Because not all bit rates can be matched exactly, the bit rate is set to
688 //! the value closest to the desired bit rate without being higher than the
689 //! \e ulBitRate value.
690 //!
691 //! \note On some devices the source clock is fixed at 8MHz so the
692 //! \e ulSourceClock should be set to 8000000.
693 //!
694 //! \return This function returns the bit rate that the CAN controller was
695 //! configured to use or it returns 0 to indicate that the bit rate was not
696 //! changed because the requested bit rate was not valid.
697 //!
698 //*****************************************************************************
699 unsigned long
CANBitRateSet(unsigned long ulBase,unsigned long ulSourceClock,unsigned long ulBitRate)700 CANBitRateSet(unsigned long ulBase, unsigned long ulSourceClock,
701               unsigned long ulBitRate)
702 {
703     unsigned long ulDesiredRatio;
704     unsigned long ulCANBits;
705     unsigned long ulPreDivide;
706     unsigned long ulRegValue;
707     unsigned short usCANCTL;
708 
709     //
710     // Check the arguments.
711     //
712     ASSERT(CANBaseValid(ulBase));
713     ASSERT(ulSourceClock != 0);
714     ASSERT(ulBitRate != 0);
715 
716     //
717     // Calculate the desired clock rate.
718     //
719     ulDesiredRatio = ulSourceClock / ulBitRate;
720 
721     //
722     // Make sure that the ratio of CAN bit rate to processor clock is not too
723     // small or too large.
724     //
725     ASSERT(ulDesiredRatio <= (CAN_MAX_PRE_DIVISOR * CAN_MAX_BIT_DIVISOR));
726     ASSERT(ulDesiredRatio >= (CAN_MIN_PRE_DIVISOR * CAN_MIN_BIT_DIVISOR));
727 
728     //
729     // Make sure that the Desired Ratio is not too large.  This enforces the
730     // requirement that the bit rate is larger than requested.
731     //
732     if((ulSourceClock / ulDesiredRatio) > ulBitRate)
733     {
734         ulDesiredRatio += 1;
735     }
736 
737     //
738     // Check all possible values to find a matching value.
739     //
740     while(ulDesiredRatio <= (CAN_MAX_PRE_DIVISOR * CAN_MAX_BIT_DIVISOR))
741     {
742         //
743         // Loop through all possible CAN bit divisors.
744         //
745         for(ulCANBits = CAN_MAX_BIT_DIVISOR; ulCANBits >= CAN_MIN_BIT_DIVISOR;
746             ulCANBits--)
747         {
748             //
749             // For a given CAN bit divisor save the pre divisor.
750             //
751             ulPreDivide = ulDesiredRatio / ulCANBits;
752 
753             //
754             // If the calculated divisors match the desired clock ratio then
755             // return these bit rate and set the CAN bit timing.
756             //
757             if((ulPreDivide * ulCANBits) == ulDesiredRatio)
758             {
759                 //
760                 // Start building the bit timing value by adding the bit timing
761                 // in time quanta.
762                 //
763                 ulRegValue = g_usCANBitValues[ulCANBits - CAN_MIN_BIT_DIVISOR];
764 
765                 //
766                 // To set the bit timing register, the controller must be placed
767                 // in init mode (if not already), and also configuration change
768                 // bit enabled.  The state of the register should be saved
769                 // so it can be restored.
770                 //
771                 usCANCTL = CANRegRead(ulBase + CAN_O_CTL);
772                 CANRegWrite(ulBase + CAN_O_CTL,
773                             usCANCTL | CAN_CTL_INIT | CAN_CTL_CCE);
774 
775                 //
776                 // Now add in the pre-scalar on the bit rate.
777                 //
778                 ulRegValue |= ((ulPreDivide - 1) & CAN_BIT_BRP_M);
779 
780                 //
781                 // Set the clock bits in the and the lower bits of the
782                 // pre-scalar.
783                 //
784                 CANRegWrite(ulBase + CAN_O_BIT, ulRegValue);
785 
786                 //
787                 // Set the divider upper bits in the extension register.
788                 //
789                 CANRegWrite(ulBase + CAN_O_BRPE,
790                             ((ulPreDivide - 1) >> 6) & CAN_BRPE_BRPE_M);
791 
792                 //
793                 // Restore the saved CAN Control register.
794                 //
795                 CANRegWrite(ulBase + CAN_O_CTL, usCANCTL);
796 
797                 //
798                 // Return the computed bit rate.
799                 //
800                 return(ulSourceClock / ( ulPreDivide * ulCANBits));
801             }
802         }
803 
804         //
805         // Move the divisor up one and look again.  Only in rare cases are
806         // more than 2 loops required to find the value.
807         //
808         ulDesiredRatio++;
809     }
810 
811     //
812     // A valid combination could not be found, so return 0 to indicate that the
813     // bit rate was not changed.
814     //
815     return(0);
816 }
817 
818 //*****************************************************************************
819 //
820 //! Configures the CAN controller bit timing.
821 //!
822 //! \param ulBase is the base address of the CAN controller.
823 //! \param pClkParms points to the structure with the clock parameters.
824 //!
825 //! Configures the various timing parameters for the CAN bus bit timing:
826 //! Propagation segment, Phase Buffer 1 segment, Phase Buffer 2 segment, and
827 //! the Synchronization Jump Width.  The values for Propagation and Phase
828 //! Buffer 1 segments are derived from the combination
829 //! \e pClkParms->ulSyncPropPhase1Seg parameter.  Phase Buffer 2 is determined
830 //! from the \e pClkParms->ulPhase2Seg parameter.  These two parameters, along
831 //! with \e pClkParms->ulSJW are based in units of bit time quanta.  The actual
832 //! quantum time is determined by the \e pClkParms->ulQuantumPrescaler value,
833 //! which specifies the divisor for the CAN module clock.
834 //!
835 //! The total bit time, in quanta, is the sum of the two Seg parameters,
836 //! as follows:
837 //!
838 //! bit_time_q = ulSyncPropPhase1Seg + ulPhase2Seg + 1
839 //!
840 //! Note that the Sync_Seg is always one quantum in duration, and is added
841 //! to derive the correct duration of Prop_Seg and Phase1_Seg.
842 //!
843 //! The equation to determine the actual bit rate is as follows:
844 //!
845 //! CAN Clock /
846 //! ((\e ulSyncPropPhase1Seg + \e ulPhase2Seg + 1) * (\e ulQuantumPrescaler))
847 //!
848 //! Thus with \e ulSyncPropPhase1Seg = 4, \e ulPhase2Seg = 1,
849 //! \e ulQuantumPrescaler = 2 and an 8 MHz CAN clock, the bit rate is
850 //! (8 MHz) / ((5 + 2 + 1) * 2) or 500 Kbit/sec.
851 //!
852 //! This function replaces the original CANSetBitTiming() API and performs the
853 //! same actions.  A macro is provided in <tt>can.h</tt> to map the original
854 //! API to this API.
855 //!
856 //! \return None.
857 //
858 //*****************************************************************************
859 void
CANBitTimingSet(unsigned long ulBase,tCANBitClkParms * pClkParms)860 CANBitTimingSet(unsigned long ulBase, tCANBitClkParms *pClkParms)
861 {
862     unsigned long ulBitReg, ulSavedInit;
863 
864     //
865     // Check the arguments.
866     //
867     ASSERT(CANBaseValid(ulBase));
868     ASSERT(pClkParms != 0);
869 
870     //
871     // The phase 1 segment must be in the range from 2 to 16.
872     //
873     ASSERT((pClkParms->ulSyncPropPhase1Seg >= 2) &&
874            (pClkParms->ulSyncPropPhase1Seg <= 16));
875 
876     //
877     // The phase 2 segment must be in the range from 1 to 8.
878     //
879     ASSERT((pClkParms->ulPhase2Seg >= 1) && (pClkParms->ulPhase2Seg <= 8));
880 
881     //
882     // The synchronous jump windows must be in the range from 1 to 4.
883     //
884     ASSERT((pClkParms->ulSJW >= 1) && (pClkParms->ulSJW <= 4));
885 
886     //
887     // The CAN clock pre-divider must be in the range from 1 to 1024.
888     //
889     ASSERT((pClkParms->ulQuantumPrescaler <= 1024) &&
890            (pClkParms->ulQuantumPrescaler >= 1));
891 
892     //
893     // To set the bit timing register, the controller must be placed in init
894     // mode (if not already), and also configuration change bit enabled.  State
895     // of the init bit should be saved so it can be restored at the end.
896     //
897     ulSavedInit = CANRegRead(ulBase + CAN_O_CTL);
898     CANRegWrite(ulBase + CAN_O_CTL, ulSavedInit | CAN_CTL_INIT | CAN_CTL_CCE);
899 
900     //
901     // Set the bit fields of the bit timing register according to the parms.
902     //
903     ulBitReg = (((pClkParms->ulPhase2Seg - 1) << CAN_BIT_TSEG2_S) &
904                 CAN_BIT_TSEG2_M);
905     ulBitReg |= (((pClkParms->ulSyncPropPhase1Seg - 1) << CAN_BIT_TSEG1_S) &
906                  CAN_BIT_TSEG1_M);
907     ulBitReg |= ((pClkParms->ulSJW - 1) << CAN_BIT_SJW_S) & CAN_BIT_SJW_M;
908     ulBitReg |= (pClkParms->ulQuantumPrescaler - 1) & CAN_BIT_BRP_M;
909     CANRegWrite(ulBase + CAN_O_BIT, ulBitReg);
910 
911     //
912     // Set the divider upper bits in the extension register.
913     //
914     CANRegWrite(ulBase + CAN_O_BRPE,
915                 ((pClkParms->ulQuantumPrescaler - 1) >> 6) & CAN_BRPE_BRPE_M);
916 
917     //
918     // Clear the config change bit, and restore the init bit.
919     //
920     ulSavedInit &= ~CAN_CTL_CCE;
921 
922     //
923     // If Init was not set before, then clear it.
924     //
925     if(ulSavedInit & CAN_CTL_INIT)
926     {
927         ulSavedInit &= ~CAN_CTL_INIT;
928     }
929     CANRegWrite(ulBase + CAN_O_CTL, ulSavedInit);
930 }
931 
932 //*****************************************************************************
933 //
934 //! Registers an interrupt handler for the CAN controller.
935 //!
936 //! \param ulBase is the base address of the CAN controller.
937 //! \param pfnHandler is a pointer to the function to be called when the
938 //! enabled CAN interrupts occur.
939 //!
940 //! This function registers the interrupt handler in the interrupt vector
941 //! table, and enables CAN interrupts on the interrupt controller; specific CAN
942 //! interrupt sources must be enabled using CANIntEnable().  The interrupt
943 //! handler being registered must clear the source of the interrupt using
944 //! CANIntClear().
945 //!
946 //! If the application is using a static interrupt vector table stored in
947 //! flash, then it is not necessary to register the interrupt handler this way.
948 //! Instead, IntEnable() should be used to enable CAN interrupts on the
949 //! interrupt controller.
950 //!
951 //! \sa IntRegister() for important information about registering interrupt
952 //! handlers.
953 //!
954 //! \return None.
955 //
956 //*****************************************************************************
957 void
CANIntRegister(unsigned long ulBase,void (* pfnHandler)(void))958 CANIntRegister(unsigned long ulBase, void (*pfnHandler)(void))
959 {
960     unsigned long ulIntNumber;
961 
962     //
963     // Check the arguments.
964     //
965     ASSERT(CANBaseValid(ulBase));
966 
967     //
968     // Get the actual interrupt number for this CAN controller.
969     //
970     ulIntNumber = CANIntNumberGet(ulBase);
971 
972     //
973     // Register the interrupt handler.
974     //
975     IntRegister(ulIntNumber, pfnHandler);
976 
977     //
978     // Enable the Ethernet interrupt.
979     //
980     IntEnable(ulIntNumber);
981 }
982 
983 //*****************************************************************************
984 //
985 //! Unregisters an interrupt handler for the CAN controller.
986 //!
987 //! \param ulBase is the base address of the controller.
988 //!
989 //! This function unregisters the previously registered interrupt handler and
990 //! disables the interrupt in the interrupt controller.
991 //!
992 //! \sa IntRegister() for important information about registering interrupt
993 //! handlers.
994 //!
995 //! \return None.
996 //
997 //*****************************************************************************
998 void
CANIntUnregister(unsigned long ulBase)999 CANIntUnregister(unsigned long ulBase)
1000 {
1001     unsigned long ulIntNumber;
1002 
1003     //
1004     // Check the arguments.
1005     //
1006     ASSERT(CANBaseValid(ulBase));
1007 
1008     //
1009     // Get the actual interrupt number for this CAN controller.
1010     //
1011     ulIntNumber = CANIntNumberGet(ulBase);
1012 
1013     //
1014     // Disable the CAN interrupt.
1015     //
1016     IntDisable(ulIntNumber);
1017 
1018     //
1019     // Register the interrupt handler.
1020     //
1021     IntUnregister(ulIntNumber);
1022 }
1023 
1024 //*****************************************************************************
1025 //
1026 //! Enables individual CAN controller interrupt sources.
1027 //!
1028 //! \param ulBase is the base address of the CAN controller.
1029 //! \param ulIntFlags is the bit mask of the interrupt sources to be enabled.
1030 //!
1031 //! This function enables specific interrupt sources of the CAN controller.
1032 //! Only enabled sources cause a processor interrupt.
1033 //!
1034 //! The \e ulIntFlags parameter is the logical OR of any of the following:
1035 //!
1036 //! - \b CAN_INT_ERROR - a controller error condition has occurred
1037 //! - \b CAN_INT_STATUS - a message transfer has completed, or a bus error has
1038 //! been detected
1039 //! - \b CAN_INT_MASTER - allow CAN controller to generate interrupts
1040 //!
1041 //! In order to generate any interrupts, \b CAN_INT_MASTER must be enabled.
1042 //! Further, for any particular transaction from a message object to generate
1043 //! an interrupt, that message object must have interrupts enabled (see
1044 //! CANMessageSet()).  \b CAN_INT_ERROR will generate an interrupt if the
1045 //! controller enters the ``bus off'' condition, or if the error counters reach
1046 //! a limit.  \b CAN_INT_STATUS generates an interrupt under quite a few
1047 //! status conditions and may provide more interrupts than the application
1048 //! needs to handle.  When an interrupt occurs, use CANIntStatus() to determine
1049 //! the cause.
1050 //!
1051 //! \return None.
1052 //
1053 //*****************************************************************************
1054 void
CANIntEnable(unsigned long ulBase,unsigned long ulIntFlags)1055 CANIntEnable(unsigned long ulBase, unsigned long ulIntFlags)
1056 {
1057     //
1058     // Check the arguments.
1059     //
1060     ASSERT(CANBaseValid(ulBase));
1061     ASSERT((ulIntFlags & ~(CAN_CTL_EIE | CAN_CTL_SIE | CAN_CTL_IE)) == 0);
1062 
1063     //
1064     // Enable the specified interrupts.
1065     //
1066     CANRegWrite(ulBase + CAN_O_CTL,
1067                 CANRegRead(ulBase + CAN_O_CTL) | ulIntFlags);
1068 }
1069 
1070 //*****************************************************************************
1071 //
1072 //! Disables individual CAN controller interrupt sources.
1073 //!
1074 //! \param ulBase is the base address of the CAN controller.
1075 //! \param ulIntFlags is the bit mask of the interrupt sources to be disabled.
1076 //!
1077 //! Disables the specified CAN controller interrupt sources.  Only enabled
1078 //! interrupt sources can cause a processor interrupt.
1079 //!
1080 //! The \e ulIntFlags parameter has the same definition as in the
1081 //! CANIntEnable() function.
1082 //!
1083 //! \return None.
1084 //
1085 //*****************************************************************************
1086 void
CANIntDisable(unsigned long ulBase,unsigned long ulIntFlags)1087 CANIntDisable(unsigned long ulBase, unsigned long ulIntFlags)
1088 {
1089     //
1090     // Check the arguments.
1091     //
1092     ASSERT(CANBaseValid(ulBase));
1093     ASSERT((ulIntFlags & ~(CAN_CTL_EIE | CAN_CTL_SIE | CAN_CTL_IE)) == 0);
1094 
1095     //
1096     // Disable the specified interrupts.
1097     //
1098     CANRegWrite(ulBase + CAN_O_CTL,
1099                 CANRegRead(ulBase + CAN_O_CTL) & ~(ulIntFlags));
1100 }
1101 
1102 //*****************************************************************************
1103 //
1104 //! Returns the current CAN controller interrupt status.
1105 //!
1106 //! \param ulBase is the base address of the CAN controller.
1107 //! \param eIntStsReg indicates which interrupt status register to read
1108 //!
1109 //! This function returns the value of one of two interrupt status registers.
1110 //! The interrupt status register read is determined by the \e eIntStsReg
1111 //! parameter, which can have one of the following values:
1112 //!
1113 //! - \b CAN_INT_STS_CAUSE - indicates the cause of the interrupt
1114 //! - \b CAN_INT_STS_OBJECT - indicates pending interrupts of all message
1115 //! objects
1116 //!
1117 //! \b CAN_INT_STS_CAUSE returns the value of the controller interrupt register
1118 //! and indicates the cause of the interrupt. The value returned is
1119 //! \b CAN_INT_INTID_STATUS if the cause is a status interrupt.  In this case,
1120 //! the status register should be read with the CANStatusGet() function.
1121 //! Calling this function to read the status also clears the status
1122 //! interrupt.  If the value of the interrupt register is in the range 1-32,
1123 //! then this indicates the number of the highest priority message object that
1124 //! has an interrupt pending.  The message object interrupt can be cleared by
1125 //! using the CANIntClear() function, or by reading the message using
1126 //! CANMessageGet() in the case of a received message.  The interrupt handler
1127 //! can read the interrupt status again to make sure all pending interrupts are
1128 //! cleared before returning from the interrupt.
1129 //!
1130 //! \b CAN_INT_STS_OBJECT returns a bit mask indicating which message objects
1131 //! have pending interrupts.  This value can be used to discover all of the
1132 //! pending interrupts at once, as opposed to repeatedly reading the interrupt
1133 //! register by using \b CAN_INT_STS_CAUSE.
1134 //!
1135 //! \return Returns the value of one of the interrupt status registers.
1136 //
1137 //*****************************************************************************
1138 unsigned long
CANIntStatus(unsigned long ulBase,tCANIntStsReg eIntStsReg)1139 CANIntStatus(unsigned long ulBase, tCANIntStsReg eIntStsReg)
1140 {
1141     unsigned long ulStatus;
1142 
1143     //
1144     // Check the arguments.
1145     //
1146     ASSERT(CANBaseValid(ulBase));
1147 
1148     //
1149     // See which status the caller is looking for.
1150     //
1151     switch(eIntStsReg)
1152     {
1153         //
1154         // The caller wants the global interrupt status for the CAN controller
1155         // specified by ulBase.
1156         //
1157         case CAN_INT_STS_CAUSE:
1158         {
1159             ulStatus = CANRegRead(ulBase + CAN_O_INT);
1160             break;
1161         }
1162 
1163         //
1164         // The caller wants the current message status interrupt for all
1165         // messages.
1166         //
1167         case CAN_INT_STS_OBJECT:
1168         {
1169             //
1170             // Read and combine both 16 bit values into one 32bit status.
1171             //
1172             ulStatus = (CANRegRead(ulBase + CAN_O_MSG1INT) &
1173                         CAN_MSG1INT_INTPND_M);
1174             ulStatus |= (CANRegRead(ulBase + CAN_O_MSG2INT) << 16);
1175             break;
1176         }
1177 
1178         //
1179         // Request was for unknown status so just return 0.
1180         //
1181         default:
1182         {
1183             ulStatus = 0;
1184             break;
1185         }
1186     }
1187 
1188     //
1189     // Return the interrupt status value
1190     //
1191     return(ulStatus);
1192 }
1193 
1194 //*****************************************************************************
1195 //
1196 //! Clears a CAN interrupt source.
1197 //!
1198 //! \param ulBase is the base address of the CAN controller.
1199 //! \param ulIntClr is a value indicating which interrupt source to clear.
1200 //!
1201 //! This function can be used to clear a specific interrupt source.  The
1202 //! \e ulIntClr parameter should be one of the following values:
1203 //!
1204 //! - \b CAN_INT_INTID_STATUS - Clears a status interrupt.
1205 //! - 1-32 - Clears the specified message object interrupt
1206 //!
1207 //! It is not necessary to use this function to clear an interrupt.  This
1208 //! function should only be used if the application wants to clear an interrupt
1209 //! source without taking the normal interrupt action.
1210 //!
1211 //! Normally, the status interrupt is cleared by reading the controller status
1212 //! using CANStatusGet().  A specific message object interrupt is normally
1213 //! cleared by reading the message object using CANMessageGet().
1214 //!
1215 //! \note Because there is a write buffer in the Cortex-M processor, it may
1216 //! take several clock cycles before the interrupt source is actually cleared.
1217 //! Therefore, it is recommended that the interrupt source be cleared early in
1218 //! the interrupt handler (as opposed to the very last action) to avoid
1219 //! returning from the interrupt handler before the interrupt source is
1220 //! actually cleared.  Failure to do so may result in the interrupt handler
1221 //! being immediately reentered (because the interrupt controller still sees
1222 //! the interrupt source asserted).
1223 //!
1224 //! \return None.
1225 //
1226 //*****************************************************************************
1227 void
CANIntClear(unsigned long ulBase,unsigned long ulIntClr)1228 CANIntClear(unsigned long ulBase, unsigned long ulIntClr)
1229 {
1230     //
1231     // Check the arguments.
1232     //
1233     ASSERT(CANBaseValid(ulBase));
1234     ASSERT((ulIntClr == CAN_INT_INTID_STATUS) ||
1235            ((ulIntClr>=1) && (ulIntClr <=32)));
1236 
1237     if(ulIntClr == CAN_INT_INTID_STATUS)
1238     {
1239         //
1240         // Simply read and discard the status to clear the interrupt.
1241         //
1242         CANRegRead(ulBase + CAN_O_STS);
1243     }
1244     else
1245     {
1246         //
1247         // Wait to be sure that this interface is not busy.
1248         //
1249         while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY)
1250         {
1251         }
1252 
1253         //
1254         // Only change the interrupt pending state by setting only the
1255         // CAN_IF1CMSK_CLRINTPND bit.
1256         //
1257         CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_CLRINTPND);
1258 
1259         //
1260         // Send the clear pending interrupt command to the CAN controller.
1261         //
1262         CANRegWrite(ulBase + CAN_O_IF1CRQ, ulIntClr & CAN_IF1CRQ_MNUM_M);
1263 
1264         //
1265         // Wait to be sure that this interface is not busy.
1266         //
1267         while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY)
1268         {
1269         }
1270     }
1271 }
1272 
1273 //*****************************************************************************
1274 //
1275 //! Sets the CAN controller automatic retransmission behavior.
1276 //!
1277 //! \param ulBase is the base address of the CAN controller.
1278 //! \param bAutoRetry enables automatic retransmission.
1279 //!
1280 //! This function enables or disables automatic retransmission of messages with
1281 //! detected errors.  If \e bAutoRetry is \b true, then automatic retransmission
1282 //! is enabled, otherwise it is disabled.
1283 //!
1284 //! \return None.
1285 //
1286 //*****************************************************************************
1287 void
CANRetrySet(unsigned long ulBase,tBoolean bAutoRetry)1288 CANRetrySet(unsigned long ulBase, tBoolean bAutoRetry)
1289 {
1290     unsigned long ulCtlReg;
1291 
1292     //
1293     // Check the arguments.
1294     //
1295     ASSERT(CANBaseValid(ulBase));
1296 
1297     ulCtlReg = CANRegRead(ulBase + CAN_O_CTL);
1298 
1299     //
1300     // Conditionally set the DAR bit to enable/disable auto-retry.
1301     //
1302     if(bAutoRetry)
1303     {
1304         //
1305         // Clearing the DAR bit tells the controller to not disable the
1306         // auto-retry of messages which were not transmitted or received
1307         // correctly.
1308         //
1309         ulCtlReg &= ~CAN_CTL_DAR;
1310     }
1311     else
1312     {
1313         //
1314         // Setting the DAR bit tells the controller to disable the auto-retry
1315         // of messages which were not transmitted or received correctly.
1316         //
1317         ulCtlReg |= CAN_CTL_DAR;
1318     }
1319 
1320     CANRegWrite(ulBase + CAN_O_CTL, ulCtlReg);
1321 }
1322 
1323 //*****************************************************************************
1324 //
1325 //! Returns the current setting for automatic retransmission.
1326 //!
1327 //! \param ulBase is the base address of the CAN controller.
1328 //!
1329 //! This function reads the current setting for automatic retransmission in the CAN
1330 //! controller and returns it to the caller.
1331 //!
1332 //! \return Returns \b true if automatic retransmission is enabled, \b false
1333 //! otherwise.
1334 //
1335 //*****************************************************************************
1336 tBoolean
CANRetryGet(unsigned long ulBase)1337 CANRetryGet(unsigned long ulBase)
1338 {
1339     //
1340     // Check the arguments.
1341     //
1342     ASSERT(CANBaseValid(ulBase));
1343 
1344     //
1345     // Read the disable automatic retry setting from the CAN controller.
1346     //
1347     if(CANRegRead(ulBase + CAN_O_CTL) & CAN_CTL_DAR)
1348     {
1349         //
1350         // Automatic data retransmission is not enabled.
1351         //
1352         return(false);
1353     }
1354 
1355     //
1356     // Automatic data retransmission is enabled.
1357     //
1358     return(true);
1359 }
1360 
1361 //*****************************************************************************
1362 //
1363 //! Reads one of the controller status registers.
1364 //!
1365 //! \param ulBase is the base address of the CAN controller.
1366 //! \param eStatusReg is the status register to read.
1367 //!
1368 //! This function reads a status register of the CAN controller and returns it
1369 //! to the caller.
1370 //! The different status registers are:
1371 //!
1372 //! - \b CAN_STS_CONTROL - the main controller status
1373 //! - \b CAN_STS_TXREQUEST - bit mask of objects pending transmission
1374 //! - \b CAN_STS_NEWDAT - bit mask of objects with new data
1375 //! - \b CAN_STS_MSGVAL - bit mask of objects with valid configuration
1376 //!
1377 //! When reading the main controller status register, a pending status
1378 //! interrupt is cleared.  This parameter should be used in the interrupt
1379 //! handler for the CAN controller if the cause is a status interrupt.  The
1380 //! controller status register fields are as follows:
1381 //!
1382 //! - \b CAN_STATUS_BUS_OFF - controller is in bus-off condition
1383 //! - \b CAN_STATUS_EWARN - an error counter has reached a limit of at least 96
1384 //! - \b CAN_STATUS_EPASS - CAN controller is in the error passive state
1385 //! - \b CAN_STATUS_RXOK - a message was received successfully (independent of
1386 //! any message filtering).
1387 //! - \b CAN_STATUS_TXOK - a message was successfully transmitted
1388 //! - \b CAN_STATUS_LEC_MSK - mask of last error code bits (3 bits)
1389 //! - \b CAN_STATUS_LEC_NONE - no error
1390 //! - \b CAN_STATUS_LEC_STUFF - stuffing error detected
1391 //! - \b CAN_STATUS_LEC_FORM - a format error occurred in the fixed format part
1392 //! of a message
1393 //! - \b CAN_STATUS_LEC_ACK - a transmitted message was not acknowledged
1394 //! - \b CAN_STATUS_LEC_BIT1 - dominant level detected when trying to send in
1395 //! recessive mode
1396 //! - \b CAN_STATUS_LEC_BIT0 - recessive level detected when trying to send in
1397 //! dominant mode
1398 //! - \b CAN_STATUS_LEC_CRC - CRC error in received message
1399 //!
1400 //! The remaining status registers consist of 32-bit-wide bit maps to the
1401 //! message objects. They can be used to quickly obtain information about the
1402 //! status of all the message objects without needing to query each one.  They
1403 //! contain the following information:
1404 //!
1405 //! - \b CAN_STS_TXREQUEST - if a message object's TXRQST bit is set, a
1406 //! transmission is pending on that object.  The application can use this
1407 //! information to determine which objects are still waiting to send a
1408 //! message.
1409 //! - \b CAN_STS_NEWDAT - if a message object's NEWDAT bit is set, a new
1410 //! message has been received in that object, and has not yet been picked up
1411 //! by the host application
1412 //! - \b CAN_STS_MSGVAL - if a message object's MSGVAL bit is set, the object
1413 //! has a valid configuration programmed.  The host application can use this
1414 //! information to determine which message objects are empty/unused.
1415 //!
1416 //! \return Returns the value of the status register.
1417 //
1418 //*****************************************************************************
1419 unsigned long
CANStatusGet(unsigned long ulBase,tCANStsReg eStatusReg)1420 CANStatusGet(unsigned long ulBase, tCANStsReg eStatusReg)
1421 {
1422     unsigned long ulStatus;
1423 
1424     //
1425     // Check the arguments.
1426     //
1427     ASSERT(CANBaseValid(ulBase));
1428 
1429     switch(eStatusReg)
1430     {
1431         //
1432         // Just return the global CAN status register since that is what was
1433         // requested.
1434         //
1435         case CAN_STS_CONTROL:
1436         {
1437             ulStatus = CANRegRead(ulBase + CAN_O_STS);
1438             CANRegWrite(ulBase + CAN_O_STS,
1439                         ~(CAN_STS_RXOK | CAN_STS_TXOK | CAN_STS_LEC_M));
1440             break;
1441         }
1442 
1443         //
1444         // Combine the Transmit status bits into one 32bit value.
1445         //
1446         case CAN_STS_TXREQUEST:
1447         {
1448             ulStatus = CANRegRead(ulBase + CAN_O_TXRQ1);
1449             ulStatus |= CANRegRead(ulBase + CAN_O_TXRQ2) << 16;
1450             break;
1451         }
1452 
1453         //
1454         // Combine the New Data status bits into one 32bit value.
1455         //
1456         case CAN_STS_NEWDAT:
1457         {
1458             ulStatus = CANRegRead(ulBase + CAN_O_NWDA1);
1459             ulStatus |= CANRegRead(ulBase + CAN_O_NWDA2) << 16;
1460             break;
1461         }
1462 
1463         //
1464         // Combine the Message valid status bits into one 32bit value.
1465         //
1466         case CAN_STS_MSGVAL:
1467         {
1468             ulStatus = CANRegRead(ulBase + CAN_O_MSG1VAL);
1469             ulStatus |= CANRegRead(ulBase + CAN_O_MSG2VAL) << 16;
1470             break;
1471         }
1472 
1473         //
1474         // Unknown CAN status requested so return 0.
1475         //
1476         default:
1477         {
1478             ulStatus = 0;
1479             break;
1480         }
1481     }
1482     return(ulStatus);
1483 }
1484 
1485 //*****************************************************************************
1486 //
1487 //! Reads the CAN controller error counter register.
1488 //!
1489 //! \param ulBase is the base address of the CAN controller.
1490 //! \param pulRxCount is a pointer to storage for the receive error counter.
1491 //! \param pulTxCount is a pointer to storage for the transmit error counter.
1492 //!
1493 //! This function reads the error counter register and returns the transmit and
1494 //! receive error counts to the caller along with a flag indicating if the
1495 //! controller receive counter has reached the error passive limit.  The values
1496 //! of the receive and transmit error counters are returned through the pointers
1497 //! provided as parameters.
1498 //!
1499 //! After this call, \e *pulRxCount holds the current receive error count
1500 //! and \e *pulTxCount holds the current transmit error count.
1501 //!
1502 //! \return Returns \b true if the receive error count has reached the error
1503 //! passive limit, and \b false if the error count is below the error passive
1504 //! limit.
1505 //
1506 //*****************************************************************************
1507 tBoolean
CANErrCntrGet(unsigned long ulBase,unsigned long * pulRxCount,unsigned long * pulTxCount)1508 CANErrCntrGet(unsigned long ulBase, unsigned long *pulRxCount,
1509               unsigned long *pulTxCount)
1510 {
1511     unsigned long ulCANError;
1512 
1513     //
1514     // Check the arguments.
1515     //
1516     ASSERT(CANBaseValid(ulBase));
1517 
1518     //
1519     // Read the current count of transmit/receive errors.
1520     //
1521     ulCANError = CANRegRead(ulBase + CAN_O_ERR);
1522 
1523     //
1524     // Extract the error numbers from the register value.
1525     //
1526     *pulRxCount = (ulCANError & CAN_ERR_REC_M) >> CAN_ERR_REC_S;
1527     *pulTxCount = (ulCANError & CAN_ERR_TEC_M) >> CAN_ERR_TEC_S;
1528 
1529     if(ulCANError & CAN_ERR_RP)
1530     {
1531         return(true);
1532     }
1533     return(false);
1534 }
1535 
1536 //*****************************************************************************
1537 //
1538 //! Configures a message object in the CAN controller.
1539 //!
1540 //! \param ulBase is the base address of the CAN controller.
1541 //! \param ulObjID is the object number to configure (1-32).
1542 //! \param pMsgObject is a pointer to a structure containing message object
1543 //! settings.
1544 //! \param eMsgType indicates the type of message for this object.
1545 //!
1546 //! This function is used to configure any one of the 32 message objects in the
1547 //! CAN controller.  A message object can be configured to be any type of CAN
1548 //! message object as well as to use automatic transmission and reception.
1549 //! This call also allows the message object to be configured to generate
1550 //! interrupts on completion of message receipt or transmission.  The
1551 //! message object can also be configured with a filter/mask so that actions
1552 //! are only taken when a message that meets certain parameters is seen on the
1553 //! CAN bus.
1554 //!
1555 //! The \e eMsgType parameter must be one of the following values:
1556 //!
1557 //! - \b MSG_OBJ_TYPE_TX - CAN transmit message object.
1558 //! - \b MSG_OBJ_TYPE_TX_REMOTE - CAN transmit remote request message object.
1559 //! - \b MSG_OBJ_TYPE_RX - CAN receive message object.
1560 //! - \b MSG_OBJ_TYPE_RX_REMOTE - CAN receive remote request message object.
1561 //! - \b MSG_OBJ_TYPE_RXTX_REMOTE - CAN remote frame receive remote, then
1562 //! transmit message object.
1563 //!
1564 //! The message object pointed to by \e pMsgObject must be populated by the
1565 //! caller, as follows:
1566 //!
1567 //! - \e ulMsgID - contains the message ID, either 11 or 29 bits.
1568 //! - \e ulMsgIDMask - mask of bits from \e ulMsgID that must match if
1569 //! identifier filtering is enabled.
1570 //! - \e ulFlags
1571 //!   - Set \b MSG_OBJ_TX_INT_ENABLE flag to enable interrupt on transmission.
1572 //!   - Set \b MSG_OBJ_RX_INT_ENABLE flag to enable interrupt on receipt.
1573 //!   - Set \b MSG_OBJ_USE_ID_FILTER flag to enable filtering based on the
1574 //!   identifier mask specified by \e ulMsgIDMask.
1575 //! - \e ulMsgLen - the number of bytes in the message data.  This parameter
1576 //! should be non-zero even for a remote frame; it should match the expected
1577 //! bytes of data in the responding data frame.
1578 //! - \e pucMsgData - points to a buffer containing up to 8 bytes of data for a
1579 //! data frame.
1580 //!
1581 //! \b Example: To send a data frame or remote frame (in response to a remote
1582 //! request), take the following steps:
1583 //!
1584 //! -# Set \e eMsgType to \b MSG_OBJ_TYPE_TX.
1585 //! -# Set \e pMsgObject->ulMsgID to the message ID.
1586 //! -# Set \e pMsgObject->ulFlags. Make sure to set \b MSG_OBJ_TX_INT_ENABLE to
1587 //! allow an interrupt to be generated when the message is sent.
1588 //! -# Set \e pMsgObject->ulMsgLen to the number of bytes in the data frame.
1589 //! -# Set \e pMsgObject->pucMsgData to point to an array containing the bytes
1590 //! to send in the message.
1591 //! -# Call this function with \e ulObjID set to one of the 32 object buffers.
1592 //!
1593 //! \b Example: To receive a specific data frame, take the following steps:
1594 //!
1595 //! -# Set \e eMsgObjType to \b MSG_OBJ_TYPE_RX.
1596 //! -# Set \e pMsgObject->ulMsgID to the full message ID, or a partial mask to
1597 //! use partial ID matching.
1598 //! -# Set \e pMsgObject->ulMsgIDMask bits that should be used for masking
1599 //! during comparison.
1600 //! -# Set \e pMsgObject->ulFlags as follows:
1601 //!   - Set \b MSG_OBJ_RX_INT_ENABLE flag to be interrupted when the data frame
1602 //!   is received.
1603 //!   - Set \b MSG_OBJ_USE_ID_FILTER flag to enable identifier-based filtering.
1604 //! -# Set \e pMsgObject->ulMsgLen to the number of bytes in the expected data
1605 //! frame.
1606 //! -# The buffer pointed to by \e pMsgObject->pucMsgData is not used by this
1607 //! call as no data is present at the time of the call.
1608 //! -# Call this function with \e ulObjID set to one of the 32 object buffers.
1609 //!
1610 //! If you specify a message object buffer that already contains a message
1611 //! definition, it is overwritten.
1612 //!
1613 //! \return None.
1614 //
1615 //*****************************************************************************
1616 void
CANMessageSet(unsigned long ulBase,unsigned long ulObjID,tCANMsgObject * pMsgObject,tMsgObjType eMsgType)1617 CANMessageSet(unsigned long ulBase, unsigned long ulObjID,
1618               tCANMsgObject *pMsgObject, tMsgObjType eMsgType)
1619 {
1620     unsigned short usCmdMaskReg;
1621     unsigned short usMaskReg0, usMaskReg1;
1622     unsigned short usArbReg0, usArbReg1;
1623     unsigned short usMsgCtrl;
1624     tBoolean bTransferData;
1625     tBoolean bUseExtendedID;
1626 
1627     bTransferData = 0;
1628 
1629     //
1630     // Check the arguments.
1631     //
1632     ASSERT(CANBaseValid(ulBase));
1633     ASSERT((ulObjID <= 32) && (ulObjID != 0));
1634     ASSERT((eMsgType == MSG_OBJ_TYPE_TX) ||
1635            (eMsgType == MSG_OBJ_TYPE_TX_REMOTE) ||
1636            (eMsgType == MSG_OBJ_TYPE_RX) ||
1637            (eMsgType == MSG_OBJ_TYPE_RX_REMOTE) ||
1638            (eMsgType == MSG_OBJ_TYPE_TX_REMOTE) ||
1639            (eMsgType == MSG_OBJ_TYPE_RXTX_REMOTE));
1640 
1641     //
1642     // Wait for busy bit to clear
1643     //
1644     while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY)
1645     {
1646     }
1647 
1648     //
1649     // See if we need to use an extended identifier or not.
1650     //
1651     if((pMsgObject->ulMsgID > CAN_MAX_11BIT_MSG_ID) ||
1652        (pMsgObject->ulFlags & MSG_OBJ_EXTENDED_ID))
1653     {
1654         bUseExtendedID = 1;
1655     }
1656     else
1657     {
1658         bUseExtendedID = 0;
1659     }
1660 
1661     //
1662     // This is always a write to the Message object as this call is setting a
1663     // message object.  This call will also always set all size bits so it sets
1664     // both data bits.  The call will use the CONTROL register to set control
1665     // bits so this bit needs to be set as well.
1666     //
1667     usCmdMaskReg = (CAN_IF1CMSK_WRNRD | CAN_IF1CMSK_DATAA | CAN_IF1CMSK_DATAB |
1668                     CAN_IF1CMSK_CONTROL);
1669 
1670     //
1671     // Initialize the values to a known state before filling them in based on
1672     // the type of message object that is being configured.
1673     //
1674     usArbReg0 = 0;
1675     usArbReg1 = 0;
1676     usMsgCtrl = 0;
1677     usMaskReg0 = 0;
1678     usMaskReg1 = 0;
1679 
1680     switch(eMsgType)
1681     {
1682         //
1683         // Transmit message object.
1684         //
1685         case MSG_OBJ_TYPE_TX:
1686         {
1687             //
1688             // Set the TXRQST bit and the reset the rest of the register.
1689             //
1690             usMsgCtrl |= CAN_IF1MCTL_TXRQST;
1691             usArbReg1 = CAN_IF1ARB2_DIR;
1692             bTransferData = 1;
1693             break;
1694         }
1695 
1696         //
1697         // Transmit remote request message object
1698         //
1699         case MSG_OBJ_TYPE_TX_REMOTE:
1700         {
1701             //
1702             // Set the TXRQST bit and the reset the rest of the register.
1703             //
1704             usMsgCtrl |= CAN_IF1MCTL_TXRQST;
1705             usArbReg1 = 0;
1706             break;
1707         }
1708 
1709         //
1710         // Receive message object.
1711         //
1712         case MSG_OBJ_TYPE_RX:
1713         {
1714             //
1715             // This clears the DIR bit along with everything else.  The TXRQST
1716             // bit was cleared by defaulting usMsgCtrl to 0.
1717             //
1718             usArbReg1 = 0;
1719             break;
1720         }
1721 
1722         //
1723         // Receive remote request message object.
1724         //
1725         case MSG_OBJ_TYPE_RX_REMOTE:
1726         {
1727             //
1728             // The DIR bit is set to one for remote receivers.  The TXRQST bit
1729             // was cleared by defaulting usMsgCtrl to 0.
1730             //
1731             usArbReg1 = CAN_IF1ARB2_DIR;
1732 
1733             //
1734             // Set this object so that it only indicates that a remote frame
1735             // was received and allow for software to handle it by sending back
1736             // a data frame.
1737             //
1738             usMsgCtrl = CAN_IF1MCTL_UMASK;
1739 
1740             //
1741             // Use the full Identifier by default.
1742             //
1743             usMaskReg0 = 0xffff;
1744             usMaskReg1 = 0x1fff;
1745 
1746             //
1747             // Make sure to send the mask to the message object.
1748             //
1749             usCmdMaskReg |= CAN_IF1CMSK_MASK;
1750             break;
1751         }
1752 
1753         //
1754         // Remote frame receive remote, with auto-transmit message object.
1755         //
1756         case MSG_OBJ_TYPE_RXTX_REMOTE:
1757         {
1758             //
1759             // Oddly the DIR bit is set to one for remote receivers.
1760             //
1761             usArbReg1 = CAN_IF1ARB2_DIR;
1762 
1763             //
1764             // Set this object to auto answer if a matching identifier is seen.
1765             //
1766             usMsgCtrl = CAN_IF1MCTL_RMTEN | CAN_IF1MCTL_UMASK;
1767 
1768             //
1769             // The data to be returned needs to be filled in.
1770             //
1771             bTransferData = 1;
1772             break;
1773         }
1774 
1775         //
1776         // This case should never happen due to the ASSERT statement at the
1777         // beginning of this function.
1778         //
1779         default:
1780         {
1781             return;
1782         }
1783     }
1784 
1785     //
1786     // Configure the Mask Registers.
1787     //
1788     if(pMsgObject->ulFlags & MSG_OBJ_USE_ID_FILTER)
1789     {
1790         if(bUseExtendedID)
1791         {
1792             //
1793             // Set the 29 bits of Identifier mask that were requested.
1794             //
1795             usMaskReg0 = pMsgObject->ulMsgIDMask & CAN_IF1MSK1_IDMSK_M;
1796             usMaskReg1 = ((pMsgObject->ulMsgIDMask >> 16) &
1797                             CAN_IF1MSK2_IDMSK_M);
1798         }
1799         else
1800         {
1801             //
1802             // Lower 16 bit are unused so set them to zero.
1803             //
1804             usMaskReg0 = 0;
1805 
1806             //
1807             // Put the 11 bit Mask Identifier into the upper bits of the field
1808             // in the register.
1809             //
1810             usMaskReg1 = ((pMsgObject->ulMsgIDMask << 2) &
1811                             CAN_IF1MSK2_IDMSK_M);
1812         }
1813     }
1814 
1815     //
1816     // If the caller wants to filter on the extended ID bit then set it.
1817     //
1818     if((pMsgObject->ulFlags & MSG_OBJ_USE_EXT_FILTER) ==
1819        MSG_OBJ_USE_EXT_FILTER)
1820     {
1821         usMaskReg1 |= CAN_IF1MSK2_MXTD;
1822     }
1823 
1824     //
1825     // The caller wants to filter on the message direction field.
1826     //
1827     if((pMsgObject->ulFlags & MSG_OBJ_USE_DIR_FILTER) ==
1828        MSG_OBJ_USE_DIR_FILTER)
1829     {
1830         usMaskReg1 |= CAN_IF1MSK2_MDIR;
1831     }
1832 
1833     if(pMsgObject->ulFlags & (MSG_OBJ_USE_ID_FILTER | MSG_OBJ_USE_DIR_FILTER |
1834                               MSG_OBJ_USE_EXT_FILTER))
1835     {
1836         //
1837         // Set the UMASK bit to enable using the mask register.
1838         //
1839         usMsgCtrl |= CAN_IF1MCTL_UMASK;
1840 
1841         //
1842         // Set the MASK bit so that this gets transferred to the Message Object.
1843         //
1844         usCmdMaskReg |= CAN_IF1CMSK_MASK;
1845     }
1846 
1847     //
1848     // Set the Arb bit so that this gets transferred to the Message object.
1849     //
1850     usCmdMaskReg |= CAN_IF1CMSK_ARB;
1851 
1852     //
1853     // Configure the Arbitration registers.
1854     //
1855     if(bUseExtendedID)
1856     {
1857         //
1858         // Set the 29 bit version of the Identifier for this message object.
1859         //
1860         usArbReg0 |= pMsgObject->ulMsgID & CAN_IF1ARB1_ID_M;
1861         usArbReg1 |= (pMsgObject->ulMsgID >> 16) & CAN_IF1ARB2_ID_M;
1862 
1863         //
1864         // Mark the message as valid and set the extended ID bit.
1865         //
1866         usArbReg1 |= CAN_IF1ARB2_MSGVAL | CAN_IF1ARB2_XTD;
1867     }
1868     else
1869     {
1870         //
1871         // Set the 11 bit version of the Identifier for this message object.
1872         // The lower 18 bits are set to zero.
1873         //
1874         usArbReg1 |= (pMsgObject->ulMsgID << 2) & CAN_IF1ARB2_ID_M;
1875 
1876         //
1877         // Mark the message as valid.
1878         //
1879         usArbReg1 |= CAN_IF1ARB2_MSGVAL;
1880     }
1881 
1882     //
1883     // Set the data length since this is set for all transfers.  This is also a
1884     // single transfer and not a FIFO transfer so set EOB bit.
1885     //
1886     usMsgCtrl |= (pMsgObject->ulMsgLen & CAN_IF1MCTL_DLC_M);
1887 
1888     //
1889     // Mark this as the last entry if this is not the last entry in a FIFO.
1890     //
1891     if((pMsgObject->ulFlags & MSG_OBJ_FIFO) == 0)
1892     {
1893         usMsgCtrl |= CAN_IF1MCTL_EOB;
1894     }
1895 
1896     //
1897     // Enable transmit interrupts if they should be enabled.
1898     //
1899     if(pMsgObject->ulFlags & MSG_OBJ_TX_INT_ENABLE)
1900     {
1901         usMsgCtrl |= CAN_IF1MCTL_TXIE;
1902     }
1903 
1904     //
1905     // Enable receive interrupts if they should be enabled.
1906     //
1907     if(pMsgObject->ulFlags & MSG_OBJ_RX_INT_ENABLE)
1908     {
1909         usMsgCtrl |= CAN_IF1MCTL_RXIE;
1910     }
1911 
1912     //
1913     // Write the data out to the CAN Data registers if needed.
1914     //
1915     if(bTransferData)
1916     {
1917         CANDataRegWrite(pMsgObject->pucMsgData,
1918                         (unsigned long *)(ulBase + CAN_O_IF1DA1),
1919                         pMsgObject->ulMsgLen);
1920     }
1921 
1922     //
1923     // Write out the registers to program the message object.
1924     //
1925     CANRegWrite(ulBase + CAN_O_IF1CMSK, usCmdMaskReg);
1926     CANRegWrite(ulBase + CAN_O_IF1MSK1, usMaskReg0);
1927     CANRegWrite(ulBase + CAN_O_IF1MSK2, usMaskReg1);
1928     CANRegWrite(ulBase + CAN_O_IF1ARB1, usArbReg0);
1929     CANRegWrite(ulBase + CAN_O_IF1ARB2, usArbReg1);
1930     CANRegWrite(ulBase + CAN_O_IF1MCTL, usMsgCtrl);
1931 
1932     //
1933     // Transfer the message object to the message object specified by ulObjID.
1934     //
1935     CANRegWrite(ulBase + CAN_O_IF1CRQ, ulObjID & CAN_IF1CRQ_MNUM_M);
1936 }
1937 
1938 //*****************************************************************************
1939 //
1940 //! Reads a CAN message from one of the message object buffers.
1941 //!
1942 //! \param ulBase is the base address of the CAN controller.
1943 //! \param ulObjID is the object number to read (1-32).
1944 //! \param pMsgObject points to a structure containing message object fields.
1945 //! \param bClrPendingInt indicates whether an associated interrupt should be
1946 //! cleared.
1947 //!
1948 //! This function is used to read the contents of one of the 32 message objects
1949 //! in the CAN controller and return it to the caller.  The data returned is
1950 //! stored in the fields of the caller-supplied structure pointed to by
1951 //! \e pMsgObject.  The data consists of all of the parts of a CAN message,
1952 //! plus some control and status information.
1953 //!
1954 //! Normally, this function is used to read a message object that has received
1955 //! and stored a CAN message with a certain identifier.  However, this function
1956 //! could also be used to read the contents of a message object in order to
1957 //! load the fields of the structure in case only part of the structure must
1958 //! be changed from a previous setting.
1959 //!
1960 //! When using CANMessageGet(), all of the same fields of the structure are
1961 //! populated in the same way as when the CANMessageSet() function is used,
1962 //! with the following exceptions:
1963 //!
1964 //! \e pMsgObject->ulFlags:
1965 //!
1966 //! - \b MSG_OBJ_NEW_DATA indicates if this data is new since the last time it
1967 //! was read
1968 //! - \b MSG_OBJ_DATA_LOST indicates that at least one message was received on
1969 //! this message object and not read by the host before being overwritten.
1970 //!
1971 //! \return None.
1972 //
1973 //*****************************************************************************
1974 void
CANMessageGet(unsigned long ulBase,unsigned long ulObjID,tCANMsgObject * pMsgObject,tBoolean bClrPendingInt)1975 CANMessageGet(unsigned long ulBase, unsigned long ulObjID,
1976               tCANMsgObject *pMsgObject, tBoolean bClrPendingInt)
1977 {
1978     unsigned short usCmdMaskReg;
1979     unsigned short usMaskReg0, usMaskReg1;
1980     unsigned short usArbReg0, usArbReg1;
1981     unsigned short usMsgCtrl;
1982 
1983     //
1984     // Check the arguments.
1985     //
1986     ASSERT(CANBaseValid(ulBase));
1987     ASSERT((ulObjID <= 32) && (ulObjID != 0));
1988 
1989     //
1990     // This is always a read to the Message object as this call is setting a
1991     // message object.
1992     //
1993     usCmdMaskReg = (CAN_IF1CMSK_DATAA | CAN_IF1CMSK_DATAB |
1994                     CAN_IF1CMSK_CONTROL | CAN_IF1CMSK_MASK | CAN_IF1CMSK_ARB);
1995 
1996     //
1997     // Clear a pending interrupt and new data in a message object.
1998     //
1999     if(bClrPendingInt)
2000     {
2001         usCmdMaskReg |= CAN_IF1CMSK_CLRINTPND;
2002     }
2003 
2004     //
2005     // Set up the request for data from the message object.
2006     //
2007     CANRegWrite(ulBase + CAN_O_IF2CMSK, usCmdMaskReg);
2008 
2009     //
2010     // Transfer the message object to the message object specified by ulObjID.
2011     //
2012     CANRegWrite(ulBase + CAN_O_IF2CRQ, ulObjID & CAN_IF1CRQ_MNUM_M);
2013 
2014     //
2015     // Wait for busy bit to clear
2016     //
2017     while(CANRegRead(ulBase + CAN_O_IF2CRQ) & CAN_IF1CRQ_BUSY)
2018     {
2019     }
2020 
2021     //
2022     // Read out the IF Registers.
2023     //
2024     usMaskReg0 = CANRegRead(ulBase + CAN_O_IF2MSK1);
2025     usMaskReg1 = CANRegRead(ulBase + CAN_O_IF2MSK2);
2026     usArbReg0 = CANRegRead(ulBase + CAN_O_IF2ARB1);
2027     usArbReg1 = CANRegRead(ulBase + CAN_O_IF2ARB2);
2028     usMsgCtrl = CANRegRead(ulBase + CAN_O_IF2MCTL);
2029 
2030     pMsgObject->ulFlags = MSG_OBJ_NO_FLAGS;
2031 
2032     //
2033     // Determine if this is a remote frame by checking the TXRQST and DIR bits.
2034     //
2035     if((!(usMsgCtrl & CAN_IF1MCTL_TXRQST) && (usArbReg1 & CAN_IF1ARB2_DIR)) ||
2036        ((usMsgCtrl & CAN_IF1MCTL_TXRQST) && (!(usArbReg1 & CAN_IF1ARB2_DIR))))
2037     {
2038         pMsgObject->ulFlags |= MSG_OBJ_REMOTE_FRAME;
2039     }
2040 
2041     //
2042     // Get the identifier out of the register, the format depends on size of
2043     // the mask.
2044     //
2045     if(usArbReg1 & CAN_IF1ARB2_XTD)
2046     {
2047         //
2048         // Set the 29 bit version of the Identifier for this message object.
2049         //
2050         pMsgObject->ulMsgID = ((usArbReg1 & CAN_IF1ARB2_ID_M) << 16) |
2051             usArbReg0;
2052 
2053         pMsgObject->ulFlags |= MSG_OBJ_EXTENDED_ID;
2054     }
2055     else
2056     {
2057         //
2058         // The Identifier is an 11 bit value.
2059         //
2060         pMsgObject->ulMsgID = (usArbReg1 & CAN_IF1ARB2_ID_M) >> 2;
2061     }
2062 
2063     //
2064     // Indicate that we lost some data.
2065     //
2066     if(usMsgCtrl & CAN_IF1MCTL_MSGLST)
2067     {
2068         pMsgObject->ulFlags |= MSG_OBJ_DATA_LOST;
2069     }
2070 
2071     //
2072     // Set the flag to indicate if ID masking was used.
2073     //
2074     if(usMsgCtrl & CAN_IF1MCTL_UMASK)
2075     {
2076         if(usArbReg1 & CAN_IF1ARB2_XTD)
2077         {
2078             //
2079             // The Identifier Mask is assumed to also be a 29 bit value.
2080             //
2081             pMsgObject->ulMsgIDMask =
2082                 ((usMaskReg1 & CAN_IF1MSK2_IDMSK_M) << 16) | usMaskReg0;
2083 
2084             //
2085             // If this is a fully specified Mask and a remote frame then don't
2086             // set the MSG_OBJ_USE_ID_FILTER because the ID was not really
2087             // filtered.
2088             //
2089             if((pMsgObject->ulMsgIDMask != 0x1fffffff) ||
2090                ((pMsgObject->ulFlags & MSG_OBJ_REMOTE_FRAME) == 0))
2091             {
2092                 pMsgObject->ulFlags |= MSG_OBJ_USE_ID_FILTER;
2093             }
2094         }
2095         else
2096         {
2097             //
2098             // The Identifier Mask is assumed to also be an 11 bit value.
2099             //
2100             pMsgObject->ulMsgIDMask = ((usMaskReg1 & CAN_IF1MSK2_IDMSK_M) >>
2101                                        2);
2102 
2103             //
2104             // If this is a fully specified Mask and a remote frame then don't
2105             // set the MSG_OBJ_USE_ID_FILTER because the ID was not really
2106             // filtered.
2107             //
2108             if((pMsgObject->ulMsgIDMask != 0x7ff) ||
2109                ((pMsgObject->ulFlags & MSG_OBJ_REMOTE_FRAME) == 0))
2110             {
2111                 pMsgObject->ulFlags |= MSG_OBJ_USE_ID_FILTER;
2112             }
2113         }
2114 
2115         //
2116         // Indicate if the extended bit was used in filtering.
2117         //
2118         if(usMaskReg1 & CAN_IF1MSK2_MXTD)
2119         {
2120             pMsgObject->ulFlags |= MSG_OBJ_USE_EXT_FILTER;
2121         }
2122 
2123         //
2124         // Indicate if direction filtering was enabled.
2125         //
2126         if(usMaskReg1 & CAN_IF1MSK2_MDIR)
2127         {
2128             pMsgObject->ulFlags |= MSG_OBJ_USE_DIR_FILTER;
2129         }
2130     }
2131 
2132     //
2133     // Set the interrupt flags.
2134     //
2135     if(usMsgCtrl & CAN_IF1MCTL_TXIE)
2136     {
2137         pMsgObject->ulFlags |= MSG_OBJ_TX_INT_ENABLE;
2138     }
2139     if(usMsgCtrl & CAN_IF1MCTL_RXIE)
2140     {
2141         pMsgObject->ulFlags |= MSG_OBJ_RX_INT_ENABLE;
2142     }
2143 
2144     //
2145     // See if there is new data available.
2146     //
2147     if(usMsgCtrl & CAN_IF1MCTL_NEWDAT)
2148     {
2149         //
2150         // Get the amount of data needed to be read.
2151         //
2152         pMsgObject->ulMsgLen = (usMsgCtrl & CAN_IF1MCTL_DLC_M);
2153 
2154         //
2155         // Don't read any data for a remote frame, there is nothing valid in
2156         // that buffer anyway.
2157         //
2158         if((pMsgObject->ulFlags & MSG_OBJ_REMOTE_FRAME) == 0)
2159         {
2160             //
2161             // Read out the data from the CAN registers.
2162             //
2163             CANDataRegRead(pMsgObject->pucMsgData,
2164                            (unsigned long *)(ulBase + CAN_O_IF2DA1),
2165                            pMsgObject->ulMsgLen);
2166         }
2167 
2168         //
2169         // Now clear out the new data flag.
2170         //
2171         CANRegWrite(ulBase + CAN_O_IF2CMSK, CAN_IF1CMSK_NEWDAT);
2172 
2173         //
2174         // Transfer the message object to the message object specified by
2175         // ulObjID.
2176         //
2177         CANRegWrite(ulBase + CAN_O_IF2CRQ, ulObjID & CAN_IF1CRQ_MNUM_M);
2178 
2179         //
2180         // Wait for busy bit to clear
2181         //
2182         while(CANRegRead(ulBase + CAN_O_IF2CRQ) & CAN_IF1CRQ_BUSY)
2183         {
2184         }
2185 
2186         //
2187         // Indicate that there is new data in this message.
2188         //
2189         pMsgObject->ulFlags |= MSG_OBJ_NEW_DATA;
2190     }
2191     else
2192     {
2193         //
2194         // Along with the MSG_OBJ_NEW_DATA not being set the amount of data
2195         // needs to be set to zero if none was available.
2196         //
2197         pMsgObject->ulMsgLen = 0;
2198     }
2199 }
2200 
2201 //*****************************************************************************
2202 //
2203 //! Clears a message object so that it is no longer used.
2204 //!
2205 //! \param ulBase is the base address of the CAN controller.
2206 //! \param ulObjID is the message object number to disable (1-32).
2207 //!
2208 //! This function frees the specified message object from use.  Once a message
2209 //! object has been ``cleared,'' it no longer automatically sends or
2210 //! receives messages, nor does it generate interrupts.
2211 //!
2212 //! \return None.
2213 //
2214 //*****************************************************************************
2215 void
CANMessageClear(unsigned long ulBase,unsigned long ulObjID)2216 CANMessageClear(unsigned long ulBase, unsigned long ulObjID)
2217 {
2218     //
2219     // Check the arguments.
2220     //
2221     ASSERT(CANBaseValid(ulBase));
2222     ASSERT((ulObjID >= 1) && (ulObjID <= 32));
2223 
2224     //
2225     // Wait for busy bit to clear
2226     //
2227     while(CANRegRead(ulBase + CAN_O_IF1CRQ) & CAN_IF1CRQ_BUSY)
2228     {
2229     }
2230 
2231     //
2232     // Clear the message value bit in the arbitration register.  This indicates
2233     // the message is not valid.
2234     //
2235     CANRegWrite(ulBase + CAN_O_IF1CMSK, CAN_IF1CMSK_WRNRD | CAN_IF1CMSK_ARB);
2236     CANRegWrite(ulBase + CAN_O_IF1ARB1, 0);
2237     CANRegWrite(ulBase + CAN_O_IF1ARB2, 0);
2238 
2239     //
2240     // Initiate programming the message object
2241     //
2242     CANRegWrite(ulBase + CAN_O_IF1CRQ, ulObjID & CAN_IF1CRQ_MNUM_M);
2243 }
2244 
2245 //*****************************************************************************
2246 //
2247 // Close the Doxygen group.
2248 //! @}
2249 //
2250 //*****************************************************************************
2251