1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
/***************************************************************
*                 CANFunctions                                 *
****************************************************************
*     Created:  10/11/2002 (dd/mm/yyyy)                        *
****************************************************************
*     Created by:  Jose Sanchez and Ben Fine                   *
*     email: joseos@okstate.edu                                *
*     Telephone:  405 744 4669                                 *
*  This program is property of Jose Sanchez and Ben Fine       *
*  The code contained in this file could be distribuited and   *
*  used freely with the proper acreditation.                   *

dgi 2003 12 03:

I get a "Constant out of the valid range" error
on the ptr=TXB0D0; assignment. Appears that CCS does not accept
pointers to memory over FFh. Fix is to eliminate use of ptr, like
this: *(TXB0D0+i) = Data[i];

Also changed the ranges of the baud rate registers to BRP--,
to match the comments.

Added RXERRCNT and IsTxReady, IsRxReady to canfunctions.h.

Fixed overflow enable:
if (config & CAN_CONFIG_DBL_BUFFER_BIT)
        RXB0CON_RXB0DBEN = 1;

dgi 2004 01 01:

Removed fn "RegsToCANID" because it was dropping
the top three bits for some reason.

Changed CANSetMask param "val" to type "int32" to match calls.

Changed id type to int16 in Send and Recieve fns.
(No Extended IDs possible.)

dgi 2004 04 26:

Added code in CANInitialize to set the ENDRHI bit, to avoid floating output.
Deleted CAN ISRs- all CAN functions handled without interrupts.

dgi 2004 06 14

added code to initialize PIN_B2 to output and B3 to input - needed to make CAN work.


****************************************************************/

#include "canfunctions.h"

///////////////////////////////////////////////////////////////////////
/*********************************************************************
 * Function:        void CANSetBaudRate(BYTE SJW,
 *                                      BYTE BRP,
 *                                      BYTE PHSEG1,
 *                                      BYTE PHSEG2,
 *                                      BYTE PROPSEG,
 *                                      enum CAN_CONFIG_FLAGS flags)
 *
 * PreCondition:    MCU must be in Configuration mode or else these
 *                  values will be ignored.
 *
 * Input:           SJW     - SJW value as defined in 18CXX8 datasheet
 *                              (Must be between 1 thru 4)
 *                  BRP     - BRP value as defined in 18CXX8 datasheet
 *                              (Must be between 1 thru 64)
 *                  PHSEG1  - PHSEG1 value as defined in 18CXX8
 *                            datasheet
 *                              (Must be between 1 thru 8)
 *                  PHSEG2  - PHSEG2 value as defined in 18CXX8
 *                            datasheet
 *                              (Must be between 1 thru 8)
 *                  PROPSEG - PROPSEG value as defined in 18CXX8
 *                            datasheet
 *                              (Must be between 1 thru 8)
 *                  flags   - Value of type enum CAN_CONFIG_FLAGS
 *
 * Output:          CAN bit rate is set as per given values.
 *
 * Side Effects:    None
 *
 * Overview:        Given values are bit adjusted to fit in 18CXX8
 *                  BRGCONx registers and copied.
 *
 ********************************************************************/

void CANSetBaudRate(int SJW,int BRP,int PHSEG1,int PHSEG2,int PROPSEG,CAN_CONFIG_FLAGS flags)
{
   // Decrement these valuse to fit in registers.
   // The register values are offset from the Tq periods.
   SJW--;
   BRP--;
   PHSEG1--;
   PHSEG2--;
   PROPSEG--;

   // Bit adjust given values into their appropriate registers.
   BRGCON1 = SJW << 6;
   BRGCON1 |= BRP;

   BRGCON2 = PHSEG1 << 3;
   BRGCON2 |= PROPSEG;

   if ( !(flags & CAN_CONFIG_SAMPLE_BIT) )
      BRGCON2_SAM = 1;

   if ( flags & CAN_CONFIG_PHSEG2_PRG_BIT )
      BRGCON2_SEG2PHTS = 1;


   BRGCON3 = PHSEG2;
   //if ( flags & CAN_CONFIG_LINE_FILTER_BIT )
   BRGCON3_WAKFIL = 1;
}
////////////////////////////////////////////////////////////////////////
/*********************************************************************
 * Function:        void CANSetOperationMode(CAN_OP_MODE mode)
 *
 * PreCondition:    None
 *
 * Input:           mode    - Operation mode code
 *                            must be of type enum CAN_OP_MODES
 *
 * Output:          MCU is set to requested mode
 *
 * Side Effects:    None
 *
 * Overview:        Given mode byte is copied to CANSTAT and made
 *                  sure that requested mode is set.
 *
 * Note:            This is a blocking call.  It will not return until
 *                  requested mode is set.
 ********************************************************************/
void CANSetOperationMode(CAN_OP_MODE mode)
{
   // Request desired mode.
   CANCON = mode;

   // Wait till desired mode is set.

    while( (CANSTAT & CAN_OP_MODE_BITS) != mode );
}

//////////////////////////////////////////////////////////////////////
/*********************************************************************
 * Function:        void CANInitialize(BYTE SJW,
 *                                      BYTE BRP,
 *                                      BYTE PHSEG1,
 *                                      BYTE PHSEG2,
 *                                      BYTE PROPSEG,
 *                                      enum CAN_CONFIG_FLAGS flags)
 *
 * PreCondition:    MCU must be in Configuration mode or else these
 *                  values will be ignored.
 *
 * Input:           SJW     - SJW value as defined in 18CXX8 datasheet
 *                              (Must be between 1 thru 4)
 *                  BRP     - BRP value as defined in 18CXX8 datasheet
 *                              (Must be between 1 thru 64)
 *                  PHSEG1  - PHSEG1 value as defined in 18CXX8
 *                            datasheet
 *                              (Must be between 1 thru 8)
 *                  PHSEG2  - PHSEG2 value as defined in 18CXX8
 *                            datasheet
 *                              (Must be between 1 thru 8)
 *                  PROPSEG - PROPSEG value as defined in 18CXX8
 *                            datasheet
 *                              (Must be between 1 thru 8)
 *                  flags   - Value of type enum CAN_CONFIG_FLAGS
 *
 * Output:          CAN bit rate is set. All masks registers are set
 *                  '0' to allow all messages.
 *                  Filter registers are set according to flag value.
 *                  If (config & CAN_CONFIG_VALID_XTD_MSG)
 *                      Set all filters to XTD_MSG
 *                  Else if (config & CONFIG_VALID_STD_MSG)
 *                      Set all filters to STD_MSG
 *                  Else
 *                      Set half of the filters to STD while rests to
 *                      XTD_MSG.
 *
 * Side Effects:    All pending transmissions are aborted.
 *
 ********************************************************************/
void CANInitialize(int SJW,int BRP,int PHSEG1,int PHSEG2,int PROPSEG,CAN_CONFIG_FLAGS config)
{
   int FilterConfig1;
   int FilterConfig2;

   // set tristate register to allow CAN to use B2, B3:
   // B2 output, B3 input
   // Doing it this way does not disturb any other pins.
   TRISB_REG = (TRISB_REG & 0xFB) | 0x08;

   // In order to setup necessary config parameters of CAN module,
   // it must be in CONFIG mode.
   CANSetOperationMode(CAN_OP_MODE_CONFIG);

   // Now set the baud rate.
   CANSetBaudRate(SJW, BRP, PHSEG1, PHSEG2,PROPSEG,config);

   *RXB0CON = config & CAN_CONFIG_MSG_BITS;  //dgi changed
   if (config & CAN_CONFIG_DBL_BUFFER_BIT)
      RXB0CON_RXB0DBEN = 1;

   *RXB1CON = *RXB0CON;

   // Set ENDRHI to drive CANTX output high when recessive.
   // Otherwise it is floated when recessive.
   // This is the appropriate setting when using a
   // transceiver without a pullup on CANTX.
   // Alternatively, set ENDRHI = 0, and use a pullup.
   // Then you can communicate non-differentially
   // without a transciever.
   ENDRHI = 1;

   // Set default filter and mask registers for all receive buffers.
   // Default is to accept all messages
   CANSetMask(CAN_MASK_B1, 0x00000000, CAN_CONFIG_STD_MSG);
   CANSetMask(CAN_MASK_B2, 0x00000000, CAN_CONFIG_STD_MSG);

   switch( (config & CAN_CONFIG_MSG_BITS) | ~CAN_CONFIG_MSG_BITS )
   {
   case CAN_CONFIG_VALID_XTD_MSG:
      FilterConfig1 = CAN_CONFIG_XTD_MSG;
      FilterConfig2 = CAN_CONFIG_XTD_MSG;
      break;

   case CAN_CONFIG_VALID_STD_MSG:
      FilterConfig1 = CAN_CONFIG_STD_MSG;
      FilterConfig2 = CAN_CONFIG_STD_MSG;
      break;
   default:
      FilterConfig1 = CAN_CONFIG_STD_MSG;
      FilterConfig2 = CAN_CONFIG_XTD_MSG;
      break;
   }

   // By default, there will be no mask on any receive filters,
   // hence filter value of '0' will be ignored.
   CANSetFilter(CAN_FILTER_B1_F1, 0, FilterConfig1);
   CANSetFilter(CAN_FILTER_B1_F2, 0, FilterConfig1);
   CANSetFilter(CAN_FILTER_B2_F1, 0, FilterConfig2);
   CANSetFilter(CAN_FILTER_B2_F2, 0, FilterConfig2);
   CANSetFilter(CAN_FILTER_B2_F3, 0, FilterConfig2);
   CANSetFilter(CAN_FILTER_B2_F4, 0, FilterConfig2);

   // Restore to Normal mode.
   CANSetOperationMode(CAN_OP_MODE_NORMAL);
}

/*********************************************************************
 * Function:        BOOL CANSendMessage(int16 id,
 *                                  BYTE *Data,
 *                                  BYTE DataLen,
 *                                  enum CAN_TX_MSG_FLAGS MsgFlags)
 *
 * PreCondition:    None
 *
 * Input:           id          - CAN message identifier.
 *                                Range: 0x0000 - 0x07FF
 *
 *                  buffSelect  - select Tx buff 0, 1, or 2.
 *                  Data        - Data bytes of upto 8 bytes in length
 *                  DataLen     - Data length from 1 thru 8.
 *                  MsgFlags    - One or CAN_TX_MSG_FLAGS values ANDed
 *                                together
 *
 * Output:          If at least one empty transmit buffer is found,
 *                  given message is queued to be transmitted. If none
 *                  found FALSE value is returned.
 *
 * Side Effects:    None
 *
 ********************************************************************/
// This is not "#inline" !! Do not call CANSendMessage from interrupt!
BOOLEAN CANSendMessage(int16 val, int8 buffSelect, BYTE* Data, BYTE DataLen, CAN_TX_MSG_FLAGS MsgFlags)
{
   BYTE i;

   // use Buffer 0?
   if ( TXB0CON_TXREQ == 0 && buffSelect ==0 )
   {
      // Select which of the CAN buffers to switch into the access bank area
      CANCON &= 0b11110000;//0b11110001;
      CANCON |= 0b00001000;
      // Set transmit priority.
      TXB0CON |= MsgFlags & CAN_TX_PRIORITY_BITS;
      // Populate Extended identifier information only if it is
      // desired.

      if ( !(MsgFlags & CAN_TX_FRAME_BIT) )
         CANIDToRegs(&TXB0SIDH,val,CAN_CONFIG_XTD_MSG);
      else
         CANIDToRegs(&TXB0SIDH,val,CAN_CONFIG_STD_MSG);

      TXB0DLC = DataLen;

      if ( !(MsgFlags & CAN_TX_RTR_BIT) )
         TXB0DLC |= 0b01000000;

      // Populate data values.
      for (i=0;i<DataLen;i++)
         *(TXB0D0+i) = Data[i];
      TXB0CON_TXREQ=1;

   }
   // use Buffer 1?
   else if ( TXB1CON_TXREQ == 0 && buffSelect ==1 )
   {
      // TxBuffer1 is empty. Set WIN bits to point to TXB1
      CANCON &= 0b11110000;//0b11110001;
      CANCON |= 0b00000110;
      TXB1CON |= MsgFlags & CAN_TX_PRIORITY_BITS;
      // Populate Extended identifier information only if it is
      // desired.

      if ( !(MsgFlags & CAN_TX_FRAME_BIT) )
         CANIDToRegs(&TXB1SIDH,val,CAN_CONFIG_XTD_MSG);
      else
         CANIDToRegs(&TXB1SIDH,val,CAN_CONFIG_STD_MSG);

      TXB1DLC = DataLen;

      if ( !(MsgFlags & CAN_TX_RTR_BIT) )
         TXB1DLC |= 0b01000000;

      for (i=0;i<DataLen;i++)
         *(TXB1D0+i) = Data[i];
      TXB1CON_TXREQ=1;
   }
   // use Buffer 2?
   else if ( TXB2CON_TXREQ == 0 && buffSelect ==2 )
   {
      // TxBuffer2 is empty. Set WIN bits to point to TXB2
      CANCON &= 0b11110000;//0b11110001;
      CANCON |= 0b00000100;
      TXB2CON |= MsgFlags & CAN_TX_PRIORITY_BITS;
      // Populate Extended identifier information only if it is
      // desired.

      if ( !(MsgFlags & CAN_TX_FRAME_BIT) )
         CANIDToRegs(&TXB2SIDH,val,CAN_CONFIG_XTD_MSG);
      else
         CANIDToRegs(&TXB2SIDH,val,CAN_CONFIG_STD_MSG);

      TXB2DLC = DataLen;

      if ( !(MsgFlags & CAN_TX_RTR_BIT) )
         TXB2DLC |= 0b01000000;
      //ptr=TXB2D0;
      // Populate data values.
      for (i=0;i<DataLen;i++)
         *(TXB2D0+i) = Data[i];
      TXB2CON_TXREQ=1;
   }
   else
      // None of the transmit buffers were empty.
      return FALSE;


//RBSendNodeID = (RBSendNodeID +1)%numID;
   CANCON=CAN_OP_MODE_NORMAL;
   return TRUE;
}

/*********************************************************************
 * Function:        BOOL InlineCANSendMessage(int16 id,
 *                                  BYTE *Data,
 *                                  BYTE DataLen,
 *                                  enum CAN_TX_MSG_FLAGS MsgFlags)
 *
 * PreCondition:    None
 *
 * Input:           id          - CAN message identifier.
 *                                Range: 0x0000 - 0x07FF
 *
 *                  buffSelect  - select Tx buff 0, 1, or 2.
 *                  Data        - Data bytes of upto 8 bytes in length
 *                  DataLen     - Data length from 1 thru 8.
 *                  MsgFlags    - One or CAN_TX_MSG_FLAGS values ANDed
 *                                together
 *
 * Output:          If at least one empty transmit buffer is found,
 *                  given message is queued to be transmitted. If none
 *                  found FALSE value is returned.
 *
 * Side Effects:    None
 *
 * Extras:          Inline version of CanSendMessage
 *                  Assumes
 ********************************************************************/
/*
#int_CANTX0
void InlineCANSendMessage()
{
 BYTE* Data;
 int16 RBSendMsgID;
// sint16 angleVal;
 BYTE i;
   byte temp;

CAN_TX_MSG_FLAGS localMsgFlags = CAN_TX_PRIORITY_0 & CAN_TX_STD_FRAME & CAN_TX_NO_RTR_FRAME;

PIR3_TXB0IF = 0b0; // reset the interrupt flag

if(numID <= currGaitNumModules)
 RBSendNodeID = (RBSendNodeID+1)%numID;
 else
 RBSendNodeID = (RBSendNodeID+1)%currGaitNumModules;
 
 RBSendMsgID = 0x200 | (int16) gaitNID[RBSendNodeID];

if(RBSendNodeID == 0)
{
interpStep = (interpStep+1)%totalInterpSteps;
}

if(interpStep==0 && RBSendNodeID == 0)
{
currRow = (currRow+1)%currGaitLength;
nextRow = (nextRow+1)%currGaitLength;
}

if(interpStep ==0)
{
prevVal[RBSendNodeID] = gaitTable[currRow][RBSendNodeID];
//   actualPos =  (sint16) (((float) ((sint16) raw_adc - (sint16) feedbackCenter)) * feedbackScaleFactor);
interp[RBSendNodeID] = (sint16) ((float)(gaitTable[nextRow][RBSendNodeID] - gaitTable[currRow][RBSendNodeID])*0.02);
}

angleVal[RBSendNodeID] = prevVal[RBSendNodeID] + interpStep*interp[RBSendNodeID];
//memcpy(Data,&gaitTable[rowNum][RBSendNodeID],2);
memcpy(Data,&angleVal[RBSendNodeID],2);

if(RBSendNodeID == 0) // finished sending messages to all the nodes
{ // disable further interrupts
TXB0IE = 0b0;
CANCON=CAN_OP_MODE_NORMAL;
return;
}

recHeartBeat = gaitNID[RBSendNodeID];
   // Always use Buffer 0
      // Select which of the CAN buffers to switch into the access bank area
      CANCON &= 0b11110000;//0b11110001;
      CANCON |= 0b00001000;
      // Set transmit priority.
      TXB0CON |= localMsgFlags & CAN_TX_PRIORITY_BITS;
      // Populate Extended identifier information only if it is
      // desired.

//      CANIDToRegs(&TXB0SIDH,val,CAN_CONFIG_STD_MSG); Do this inline - all four lines below
      // Standard Identifier
      temp=(int)(RBSendMsgID>>3);
      *(&TXB0SIDH)=temp;
      temp=(int)(RBSendMsgID&0x7);
      *(&TXB0SIDH+1)=(temp<<5);

      TXB0DLC = 2; // length of data
  if ( !(localMsgFlags & CAN_TX_RTR_BIT) )
         TXB0DLC |= 0b01000000;

      // Populate data values.
      for (i=0;i<2;i++)
         *(TXB0D0+i) = Data[i];

      TXB0CON_TXREQ=1; //enable transmission

//   CANCON=CAN_OP_MODE_NORMAL;

   return;
}

*/

/*********************************************************************
 * Function:        void CANIDToRegs(BYTE* ptr,
 *                                      int32 val,
 *                                      enum CAN_CONFIG_FLAGS type)
 *
 * PreCondition:    None
 *
 * Input:           ptr     - Starting address of a buffer to be updated
 *                  val     - 32-bit value to be converted
 *                  type    - Type of message - either
 *                            CAN_CONFIG_XTD_MSG or CAN_CONFIG_STD_MSG
 *
 * Output:          Given CAN id value 'val' is bit adjusted and copied
 *                  into corresponding PIC18CXX8 CAN registers
 *
 * Side Effects:    None
 *
 * Overview:        If given id is of type standard identifier,
 *                  only SIDH and SIDL are updated
 *                  If given id is of type extended identifier,
 *                  bits val<17:0> is copied to EIDH, EIDL and SIDH<1:0>
 *                  bits val<28:18> is copied to SIDH and SIDL
 *
 ********************************************************************/
void CANIDToRegs(int *regaddress, int32 val, CAN_CONFIG_FLAGS type)
{
   byte temp;
   if (type == CAN_TX_STD_FRAME)
   {
      // Standard Identifier
      temp=(int)(val>>3);
      *regaddress=temp;
      temp=(int)(val&0x7);
      *(regaddress+1)=(temp<<5);
   }
   else
   {
      // Extended Identifier
      *regaddress=val>>21;
      *(regaddress+1)=((val>>13)&0xE0);
      *(regaddress+1)|=((val>>16)&0x3);
      *(regaddress+2)=val>>8;
      *(regaddress+3)=(int)val;
   }
}

//////////////////////////////////////////////////////////////////////
/*********************************************************************
 * Function:        void CANSetMask(enum CAN_MASK code,
 *                                  unsigned long val,
 *                                  enum CAN_CONFIG_FLAGS type)
 *
 * PreCondition:    MCU must be in Configuration mode.  If not, all
 *                  values will be ignored.
 *
 * Input:           code    - One of CAN_MASK value
 *                  val     - Actual mask register value.
 *                  type    - Type of message to filter either
 *                            CAN_CONFIG_XTD_MSG or CAN_CONFIG_STD_MSG
 *
 * Output:          Given value is bit adjusted to appropriate buffer
 *                  mask registers.
 *
 * Side Effects:    None
 *
 ********************************************************************/
void CANSetMask(CAN_MASK code, int32 val,CAN_CONFIG_FLAGS type)
{
   int16 ptr;

   // Select appropriate starting address based on given CAN_MASK
   // value.
   if ( code == CAN_MASK_B1 )
      ptr = RXM0SIDH;
   else
      ptr = RXM1SIDH;

   // Convert given 32-bit id value into corresponding register values.
   CANIDToRegs(ptr, val, type);
}

/*********************************************************************
 * Function:        void CANSetFilter(enum CAN_FILTER code,
 *                                   unsigned long val,
 *                                   enum CAN_CONFIG type)
 *
 * PreCondition:    MCU must be in Configuration mode.  If not, all
 *                  values will be ignored.
 *
 *
 Input:             code    - One of CAN_FILTER value
 *                  val     - Actual filter register value.
 *                  type    - Type of message to filter either
 *                            CAN_CONFIG_XTD_MSG or CAN_CONFIG_STD_MSG
 *
 * Output:          Given value is bit adjusted to appropriate buffer
 *                  filter registers.
 *
 * Side Effects:    None
 ********************************************************************/
void CANSetFilter(CAN_FILTER code,int32 val,CAN_CONFIG_FLAGS type)
{
   int16 ptr;

   // Select appropriate starting address based on given CAN_FILTER
   // code.
   switch(code)
   {
   case CAN_FILTER_B1_F1:
      ptr = RXF0SIDH;
      break;

   case CAN_FILTER_B1_F2:
      ptr = RXF1SIDH;
      break;

   case CAN_FILTER_B2_F1:
      ptr = RXF2SIDH;
      break;

   case CAN_FILTER_B2_F2:
      ptr = RXF3SIDH;
      break;

   case CAN_FILTER_B2_F3:
      ptr = RXF4SIDH;
      break;

default:
      ptr = RXF5SIDH;
      break;
   }

   // Convert 32-bit value into register values.
   CANIDToRegs(ptr, val, type);
}

//////////////////////////////////////////////////////////////////////
/*********************************************************************
 * Function:        BOOL CANReceiveMessage(int16 *id,
 *                                  BYTE *Data,
 *                                  BYTE DataLen,
 *                                  enum CAN_RX_MSG_FLAGS MsgFlags)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          id          - CAN message identifier.
 *                  Data        - Data bytes of upto 8 bytes in length
 *                  DataLen     - Data length from 1 thru 8.
 *                  MsgFlags    - One or CAN_RX_MSG_FLAGS values ANDed
 *                                together
 *
 * Output:          If at least one full receive buffer is found,
 *                  it is extrated and returned.
 *                  If none found FALSE value is returned.
 *
 * Side Effects:    None
 *
 ********************************************************************/

BOOLEAN CANReceiveMessage(int16 *id, BYTE *Data, BYTE *DataLen, CAN_RX_MSG_FLAGS *MsgFlags)
{
   BYTE i;
   BOOLEAN lbIsItBuffer0;

   // Start with no error or flags set.
   *MsgFlags = 0x0;

   // Find which buffer is ready.
   if ( RXB0CON_RXFUL )
   {
      // RXBuffer0 is full.
      CANCON &= 0b11110000; // clear Window Address bits (see sec 19.2.1)
      // dgi doesn't know if this is necessary? 2004-01-01

      lbIsItBuffer0 = TRUE;

      // Clear the received flag.
      PIR3_RXB0IF = 0;

      // Record and forget any previous overflow
      if ( COMSTAT_RXB0OVFL )
      {
         *MsgFlags |= CAN_RX_OVERFLOW;
         COMSTAT_RXB0OVFL = 0;
      }

      if ( RXB0CON_RXB0DBEN )
      {
         *MsgFlags |= RXB0CON & CAN_RX_FILTER_BITS;
         *MsgFlags &= 0x01;
      }

      // Retrieve message length.

      *DataLen = *RXB0DLC & 0b00001111;


      // Determine whether this was RTR or not.
      if ( RXB0DLC_RXRTR )
         *MsgFlags |= CAN_RX_RTR_FRAME;

      // Retrieve EIDX bytes only if this is extended message
      if ( RXB0SIDL_EXID )
      {
         *MsgFlags |= CAN_RX_XTD_FRAME;
      }
      else {
         *id =((int32)(*RXB0SIDH)) * 8;
         *id |= (int32)(((*RXB0SIDL) & 0xE0)>>5);
      }

      for ( i = 0; i < *DataLen; i++ )
         Data[i] = *(RXB0D0+i);

      CANCON=CAN_OP_MODE_NORMAL;

      // Record and Clear any previous invalid message bit flag.
      if ( PIR3_IRXIF )
      {
         *MsgFlags |= CAN_RX_INVALID_MSG;
         PIR3_IRXIF = 0;
      }
   }
   else if ( RXB1CON_RXFUL )
   {
      // RXBuffer1 is full
      CANCON &= 0b11110000; // clear Window Address bits (see sec 19.2.1)
      CANCON |= 0b00001010; // select RXBuff1

      lbIsItBuffer0 = FALSE;

      // Clear the received flag.
      PIR3_RXB1IF = 0;

      // Record and forget any previous overflow
      if ( COMSTAT_RXB1OVFL )
      {
         *MsgFlags |= CAN_RX_OVERFLOW;
         COMSTAT_RXB1OVFL = 0;
      }

      *MsgFlags |= RXB1CON & CAN_RX_FILTER_BITS;
      if ( *MsgFlags < 0x02 )
         *MsgFlags |= CAN_RX_DBL_BUFFERED;


      // Retrieve message length.
      *DataLen = *RXB1DLC & 0b00001111;

      // Determine whether this was RTR or not.
      if ( RXB1DLC_RXRTR )
         *MsgFlags |= CAN_RX_RTR_FRAME;

      // Retrieve EIDX bytes only if this is extended message
      if ( RXB1SIDL_EXID ) {
         *MsgFlags |= CAN_RX_XTD_FRAME;
      }
      else {
         *id =((int32)(*RXB1SIDH)) * 8;
         *id |= (int32)(((*RXB1SIDL) & 0xE0)>>5);
      }

      // Get message data itself
      //ptr = RXB1D0;
      for ( i = 0; i < *DataLen; i++ )
         Data[i] = *(RXB1D0+i);

      // Restore default RXB0 mapping.
      //CANCON &= 0b11110000;//0b11110001;
      CANCON=CAN_OP_MODE_NORMAL;
      // Record and Clear any previous invalid message bit flag.
      if ( PIR3_IRXIF )
      {
         *MsgFlags |= CAN_RX_INVALID_MSG;
         PIR3_IRXIF = 0;
      }
      RXB1CON_RXFUL = 0;
   }
   else
      return FALSE;

   if ( lbIsItBuffer0 )
      RXB0CON_RXFUL = 0;
   else
      RXB1CON_RXFUL = 0;

   return TRUE;
}