forked from collin80/FlexCAN_Library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FlexCAN.cpp
1646 lines (1321 loc) · 37.8 KB
/
FlexCAN.cpp
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -------------------------------------------------------------
// a simple Arduino Teensy 3.1/3.2/3.5/3.6 CAN driver
// by teachop
// dual CAN support for MK66FX1M0 and updates for MK64FX512 by Pawelsky
// Interrupt driven Rx/Tx with buffers, object oriented callbacks by Collin Kidder
// RTR related code by H4nky84
// Statistics collection, timestamp and code clean-up my mdapoz
//
#include "FlexCAN.h"
#include "kinetis_flexcan.h"
#define FLEXCANb_MCR(b) (*(vuint32_t*)(b))
#define FLEXCANb_CTRL1(b) (*(vuint32_t*)(b+4))
#define FLEXCANb_RXMGMASK(b) (*(vuint32_t*)(b+0x10))
#define FLEXCANb_IFLAG1(b) (*(vuint32_t*)(b+0x30))
#define FLEXCANb_IMASK1(b) (*(vuint32_t*)(b+0x28))
#define FLEXCANb_RXFGMASK(b) (*(vuint32_t*)(b+0x48))
#define FLEXCANb_MBn_CS(b, n) (*(vuint32_t*)(b+0x80+n*0x10))
#define FLEXCANb_MBn_ID(b, n) (*(vuint32_t*)(b+0x84+n*0x10))
#define FLEXCANb_MBn_WORD0(b, n) (*(vuint32_t*)(b+0x88+n*0x10))
#define FLEXCANb_MBn_WORD1(b, n) (*(vuint32_t*)(b+0x8C+n*0x10))
#define FLEXCANb_IDFLT_TAB(b, n) (*(vuint32_t*)(b+0xE0+(n*4)))
#define FLEXCANb_MB_MASK(b, n) (*(vuint32_t*)(b+0x880+(n*4)))
#define FLEXCANb_ESR1(b) (*(vuint32_t*)(b+0x20))
#if defined(__MK66FX1M0__)
# define INCLUDE_FLEXCAN_CAN1
#endif
#undef INCLUDE_FLEXCAN_DEBUG
#if defined(INCLUDE_FLEXCAN_DEBUG)
# define dbg_print(fmt, args...) Serial.print (fmt , ## args)
# define dbg_println(fmt, args...) Serial.println (fmt , ## args)
#else
# define dbg_print(fmt, args...)
# define dbg_println(fmt, args...)
#endif
// Supported FlexCAN interfaces
FlexCAN Can0 (0);
#if defined(INCLUDE_FLEXCAN_CAN1)
FlexCAN Can1 (1);
#endif
// default mask to apply to all mailboxes
CAN_filter_t FlexCAN::defaultMask;
// Some of these are complete guesses. Only really 8 and 16 have been validated.
// You have been warned. But, there aren't too many options for some of these
uint8_t bitTimingTable[21][3] = {
// prop, seg1, seg2 (4 + prop + seg1 + seg2, seg2 must be at least 1)
// No value can go over 7 here.
{0,0,1}, //5
{1,0,1}, //6
{1,1,1}, //7
{2,1,1}, //8
{2,2,1}, //9
{2,3,1}, //10
{2,3,2}, //11
{2,4,2}, //12
{2,5,2}, //13
{2,5,3}, //14
{2,6,3}, //15
{2,7,3}, //16
{2,7,4}, //17
{3,7,4}, //18
{3,7,5}, //19
{4,7,5}, //20
{4,7,6}, //21
{5,7,6}, //22
{6,7,6}, //23
{6,7,7}, //24
{7,7,7}, //25
};
/*
* \brief Initialize the FlexCAN driver class
*
* \param id - CAN bus interface selection
*
* \retval none
*
*/
FlexCAN::FlexCAN (uint8_t id)
{
uint32_t i;
numTxMailboxes=2;
flexcanBase = FLEXCAN0_BASE;
#if defined (INCLUDE_FLEXCAN_CAN1)
if (id > 0) {
flexcanBase = FLEXCAN1_BASE;
}
#else
(void)id; // Just for avoid warning.
#endif
#if defined(__MK20DX256__)
IrqMessage=IRQ_CAN_MESSAGE;
#elif defined(__MK64FX512__)
IrqMessage=IRQ_CAN0_MESSAGE;
#elif defined(__MK66FX1M0__)
if (flexcanBase == FLEXCAN0_BASE) {
IrqMessage=IRQ_CAN0_MESSAGE;
} else {
IrqMessage=IRQ_CAN1_MESSAGE;
}
#endif
// Default mask is allow everything
defaultMask.flags.remote = 0;
defaultMask.flags.extended = 0;
defaultMask.id = 0;
sizeRxBuffer=SIZE_RX_BUFFER;
sizeTxBuffer=SIZE_TX_BUFFER;
tx_buffer=0;
rx_buffer=0;
// Initialize all message box spesific ring buffers to 0.
for (i=0; i<getNumMailBoxes(); i++) {
txRings[i]=0;
}
// clear any listeners for received packets
for (i = 0; i < SIZE_LISTENERS; i++) {
listener[i] = NULL;
}
// clear statistics counts
clearStats ();
}
/*
* \brief Bring the hardware into freeze which drops it off the CAN bus
*
* \param none
*
* \retval none
*
*/
void FlexCAN::end (void)
{
// enter freeze mode
halt();
FLEXCANb_MCR (flexcanBase) |= (FLEXCAN_MCR_HALT);
while (!(FLEXCANb_MCR(flexcanBase) & FLEXCAN_MCR_FRZ_ACK))
;
}
/*
* \brief Initializes the CAN bus to the given settings
*
* \param baud - Set the baud rate of the bus. Only certain values are valid 50000, 100000, 125000, 250000, 500000, 1000000
* \param mask - A default mask to use for all mailbox masks. Optional.
* \param txAlt - 1 to enable alternate Tx pin (where available)
* \param rxAlt - 1 to enable alternate Rx pin (where available)
*
* \retval none
*
*/
void FlexCAN::begin (uint32_t baud, const CAN_filter_t &mask, uint8_t txAlt, uint8_t rxAlt, bool receive_own)
{
initializeBuffers();
// set up the pins
setPins(txAlt,rxAlt);
// select clock source 16MHz xtal
OSC0_CR |= OSC_ERCLKEN;
if (flexcanBase == FLEXCAN0_BASE) {
SIM_SCGC6 |= SIM_SCGC6_FLEXCAN0;
#if defined(INCLUDE_FLEXCAN_CAN1)
} else if (flexcanBase == FLEXCAN1_BASE) {
SIM_SCGC3 |= SIM_SCGC3_FLEXCAN1;
#endif
}
FLEXCANb_CTRL1(flexcanBase) &= ~FLEXCAN_CTRL_CLK_SRC;
// enable CAN
FLEXCANb_MCR (flexcanBase) |= FLEXCAN_MCR_FRZ;
FLEXCANb_MCR (flexcanBase) &= ~FLEXCAN_MCR_MDIS;
while (FLEXCANb_MCR(flexcanBase) & FLEXCAN_MCR_LPM_ACK)
;
// soft reset
softReset();
// wait for freeze ack
waitFrozen();
// enable or disable self-reception
if (receive_own)
FLEXCANb_MCR (flexcanBase) &= ~FLEXCAN_MCR_SRX_DIS;
else
FLEXCANb_MCR (flexcanBase) |= FLEXCAN_MCR_SRX_DIS;
setBaudRate(baud);
// enable per-mailbox filtering
FLEXCANb_MCR(flexcanBase) |= FLEXCAN_MCR_IRMQ;
// now have to set mask and filter for all the Rx mailboxes or they won't receive anything by default.
for (uint8_t c = 0; c < getNumRxBoxes(); c++) {
setMask (0, c);
setFilter (mask, c);
}
// start the CAN
exitHalt();
waitReady();
setNumTxBoxes (numTxMailboxes);
NVIC_SET_PRIORITY (IrqMessage, IRQ_PRIORITY);
NVIC_ENABLE_IRQ (IrqMessage);
// enable interrupt masks for all 16 mailboxes
FLEXCANb_IMASK1 (flexcanBase) = 0xFFFF;
dbg_println ("CAN initialized properly");
}
/*
* \brief
*
* \param
*
* \retval None.
*
*/
void FlexCAN::setMailBoxTxBufferSize(uint8_t mbox, uint16_t size) {
if ( mbox>=getNumMailBoxes() || txRings[mbox]!=0 ) return;
volatile CAN_message_t *buf=new CAN_message_t[size];
txRings[mbox]=new ringbuffer_t;
initRingBuffer (*(txRings[mbox]), buf, size);
}
/*
* \brief Initializes dynamically sized buffers.
*
* \param mask - default filter mask
*
* \retval None.
*
*/
void FlexCAN::initializeBuffers() {
if ( isInitialized() ) return;
// set up the transmit and receive ring buffers
if (tx_buffer==0) tx_buffer=new CAN_message_t[sizeTxBuffer];
if (rx_buffer==0) rx_buffer=new CAN_message_t[sizeRxBuffer];
initRingBuffer (txRing, tx_buffer, sizeTxBuffer);
initRingBuffer (rxRing, rx_buffer, sizeRxBuffer);
}
/*
* \brief Initializes CAN pin definitions.
*
* \param txAlt - Atrenate tx pin
* \param rxAlt - Alternate rx pin
*
* \retval None.
*
*/
void FlexCAN::setPins(uint8_t txAlt, uint8_t rxAlt) {
if (flexcanBase == FLEXCAN0_BASE) {
dbg_println ("Begin setup of CAN0");
#if defined(__MK66FX1M0__) || defined(__MK64FX512__)
// 3=PTA12=CAN0_TX, 4=PTA13=CAN0_RX (default)
// 29=PTB18=CAN0_TX, 30=PTB19=CAN0_RX (alternative)
if (txAlt == 1)
CORE_PIN29_CONFIG = PORT_PCR_MUX(2);
else
CORE_PIN3_CONFIG = PORT_PCR_MUX(2);
// | PORT_PCR_PE | PORT_PCR_PS;
if (rxAlt == 1)
CORE_PIN30_CONFIG = PORT_PCR_MUX(2);
else
CORE_PIN4_CONFIG = PORT_PCR_MUX(2);
#else
// 3=PTA12=CAN0_TX, 4=PTA13=CAN0_RX (default)
// 32=PTB18=CAN0_TX, 25=PTB19=CAN0_RX (alternative)
if (txAlt == 1)
CORE_PIN32_CONFIG = PORT_PCR_MUX(2);
else
CORE_PIN3_CONFIG = PORT_PCR_MUX(2);
// | PORT_PCR_PE | PORT_PCR_PS;
if (rxAlt == 1)
CORE_PIN25_CONFIG = PORT_PCR_MUX(2);
else
CORE_PIN4_CONFIG = PORT_PCR_MUX(2);
#endif
}
#if defined(INCLUDE_FLEXCAN_CAN1)
else if (flexcanBase == FLEXCAN1_BASE) {
dbg_println("Begin setup of CAN1");
// 33=PTE24=CAN1_TX, 34=PTE25=CAN1_RX (default)
// NOTE: Alternative CAN1 pins are not broken out on Teensy 3.6
CORE_PIN33_CONFIG = PORT_PCR_MUX(2);
CORE_PIN34_CONFIG = PORT_PCR_MUX(2);// | PORT_PCR_PE | PORT_PCR_PS;
}
#endif
}
/*
* \brief Intializes bus baud rate setting.
*
* \param baud - desired baud rate
*
* \retval None.
*
now using a system that tries to automatically generate a viable baud setting.
Bear these things in mind:
- The master clock is 16Mhz
- You can freely divide it by anything from 1 to 256
- There is always a start bit (+1)
- The rest (prop, seg1, seg2) are specified 1 less than their actual value (aka +1)
- This gives the low end bit timing as 5 (1 + 1 + 2 + 1) and the high end 25 (1 + 8 + 8 + 8)
A worked example: 16Mhz clock, divisor = 19+1, bit values add up to 16 = 16Mhz / 20 / 16 = 50k baud
*/
void FlexCAN::setBaudRate(uint32_t baud) {
// have to find a divisor that ends up as close to the target baud as possible while keeping the end result between 5 and 25
dbg_println ("Set baud rate");
uint32_t divisor = 0;
uint32_t bestDivisor = 0;
uint32_t result = 16000000 / baud / (divisor + 1);
int error = baud - (16000000 / (result * (divisor + 1)));
int bestError = error;
while (result > 5) {
divisor++;
result = 16000000 / baud / (divisor + 1);
if (result <= 25) {
error = baud - (16000000 / (result * (divisor + 1)));
if (error < 0)
error *= -1;
// if this error is better than we've ever seen then use it - it's the best option
if (error < bestError) {
bestError = error;
bestDivisor = divisor;
}
// If this is equal to a previously good option then
// switch to it but only if the bit time result was in the middle of the range
// this biases the output to use the middle of the range all things being equal
// Otherwise it might try to use a higher divisor and smaller values for prop, seg1, seg2
// and that's not necessarily the best idea.
if ((error == bestError) && (result > 11) && (result < 19)) {
bestError = error;
bestDivisor = divisor;
}
}
}
divisor = bestDivisor;
result = 16000000 / baud / (divisor + 1);
if ((result < 5) || (result > 25) || (bestError > 300)) {
Serial.println ("Abort in CAN begin. Couldn't find a suitable baud config!");
return;
}
result -= 5; // the bitTimingTable is offset by 5 since there was no reason to store bit timings for invalid numbers
uint8_t propSeg = bitTimingTable[result][0];
uint8_t pSeg1 = bitTimingTable[result][1];
uint8_t pSeg2 = bitTimingTable[result][2];
// baud rate debug information
dbg_println (" Bit time values:");
dbg_print (" Prop = ");
dbg_println (propSeg + 1);
dbg_print (" Seg1 = ");
dbg_println (pSeg1 + 1);
dbg_print (" Seg2 = ");
dbg_println (pSeg2 + 1);
dbg_print (" Divisor = ");
dbg_println (divisor + 1);
FLEXCANb_CTRL1 (flexcanBase) = (FLEXCAN_CTRL_PROPSEG(propSeg) | FLEXCAN_CTRL_RJW(1) | FLEXCAN_CTRL_ERR_MSK |
FLEXCAN_CTRL_PSEG1(pSeg1) | FLEXCAN_CTRL_PSEG2(pSeg2) | FLEXCAN_CTRL_PRESDIV(divisor));
}
/*
* \brief Halts CAN bus.
*
* \param None.
*
* \retval None.
*
*/
void FlexCAN::halt() {
FLEXCANb_MCR(flexcanBase) |= (FLEXCAN_MCR_HALT);
waitFrozen();
}
/*
* \brief Exits from hat state.
*
* \param None.
*
* \retval None.
*
*/
void FlexCAN::exitHalt() {
// exit freeze mode and wait until it is unfrozen.
dbg_println ("Exit halt");
FLEXCANb_MCR(flexcanBase) &= ~(FLEXCAN_MCR_HALT);
waitNotFrozen();
}
/*
* \brief Makes CAN bus soft reset.
*
* \param None.
*
* \retval None.
*
*/
void FlexCAN::softReset() {
dbg_println ("Soft reset");
FLEXCANb_MCR (flexcanBase) ^= FLEXCAN_MCR_SOFT_RST;
while (FLEXCANb_MCR (flexcanBase) & FLEXCAN_MCR_SOFT_RST)
;
}
/*
* \brief Freezes CAN bus.
*
* \param None.
*
* \retval None.
*
*/
void FlexCAN::freeze() {
FLEXCANb_MCR(flexcanBase) |= FLEXCAN_MCR_FRZ;
}
/*
* \brief Waits until CAN bus is frozen
*
* \param None.
*
* \retval None.
*
*/
void FlexCAN::waitFrozen() {
// wait for freeze ack
dbg_println ("Wait frozen");
while (!isFrozen());
}
/*
* \brief Waits until CAN bus is not frozen.
*
* \param None.
*
* \retval None.
*
*/
void FlexCAN::waitNotFrozen() {
// wait for freeze ack
dbg_println ("Wait not frozen");
while (isFrozen());
}
/*
* \brief Waits until CAN bus is ready
*
* \param None.
*
* \retval None.
*
*/
void FlexCAN::waitReady() {
while (FLEXCANb_MCR(flexcanBase) & FLEXCAN_MCR_NOT_RDY);
}
/*
* \brief Tests is CAN bus frozen.
*
* \param None.
*
* \retval true, if CAN bus is frozen.
*
*/
bool FlexCAN::isFrozen() {
return (FLEXCANb_MCR(flexcanBase) & FLEXCAN_MCR_FRZ_ACK);
}
/*
* \brief Set listen only mode on or off.
*
* \param mode - set listen only mode?
*
* \retval None.
*
*/
void FlexCAN::setListenOnly (bool mode)
{
// enter freeze mode if not already there
if (!(FLEXCANb_MCR(flexcanBase) & FLEXCAN_MCR_FRZ_ACK)) {
FLEXCANb_MCR(flexcanBase) |= FLEXCAN_MCR_FRZ;
FLEXCANb_MCR(flexcanBase) |= FLEXCAN_MCR_HALT;
while (!(FLEXCANb_MCR(flexcanBase) & FLEXCAN_MCR_FRZ_ACK))
;
}
if (mode)
FLEXCANb_CTRL1(flexcanBase) |= FLEXCAN_CTRL_LOM;
else
FLEXCANb_CTRL1(flexcanBase) &= ~FLEXCAN_CTRL_LOM;
// exit freeze mode and wait until it is unfrozen.
FLEXCANb_MCR(flexcanBase) &= ~FLEXCAN_MCR_HALT;
while (FLEXCANb_MCR(flexcanBase) & FLEXCAN_MCR_FRZ_ACK)
;
}
/*
* \brief Initializes mailboxes to the requested mix of Rx and Tx boxes
*
* \param txboxes - How many of the 8 boxes should be used for Tx
*
* \retval number of tx boxes set.
*
*/
uint8_t FlexCAN::setNumTxBoxes (uint8_t txboxes)
{
uint8_t c;
uint32_t oldIde;
if (txboxes > getNumMailBoxes() - 1)
txboxes = getNumMailBoxes() - 1;
if (txboxes < 1)
txboxes = 1;
numTxMailboxes = txboxes;
if ( !isInitialized() ) return numTxMailboxes; // Just set the numTxMailboxes. Begin() will do final initialization.
// Inialize Rx boxen
for (c = 0; c < getNumRxBoxes(); c++) {
// preserve the existing filter ide setting
oldIde = FLEXCANb_MBn_CS(flexcanBase, c) & FLEXCAN_MB_CS_IDE;
FLEXCANb_MBn_CS(flexcanBase, c) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_RX_EMPTY) | oldIde;
}
// Initialize Tx boxen
for (c = getFirstTxBox(); c < getNumMailBoxes(); c++) {
FLEXCANb_MBn_CS(flexcanBase, c) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_INACTIVE);
}
return (numTxMailboxes);
}
/*
* \brief Sets a per-mailbox filter. Sets both the storage and the actual mailbox.
*
* \param filter - a filled out filter structure
* \param mbox - the mailbox to update
*
* \retval Nothing
*
*/
void FlexCAN::setFilter (const CAN_filter_t &filter, uint8_t mbox)
{
if ( mbox < getNumRxBoxes() ) {
MBFilters[mbox] = filter;
if (filter.flags.extended) {
FLEXCANb_MBn_ID(flexcanBase, mbox) = (filter.id & FLEXCAN_MB_ID_EXT_MASK);
FLEXCANb_MBn_CS(flexcanBase, mbox) |= FLEXCAN_MB_CS_IDE;
} else {
FLEXCANb_MBn_ID(flexcanBase, mbox) = FLEXCAN_MB_ID_IDSTD(filter.id);
FLEXCANb_MBn_CS(flexcanBase, mbox) &= ~FLEXCAN_MB_CS_IDE;
}
}
}
/*
* \brief Gets a per-mailbox filter.
*
* \param filter - returned filter structure
* \param mbox - mailbox selected
*
* \retval true if mailbox s valid, false otherwise
*
*/
bool FlexCAN::getFilter (CAN_filter_t &filter, uint8_t mbox)
{
if ( mbox < getNumRxBoxes() ) {
filter.id = MBFilters[mbox].id;
filter.flags.extended = MBFilters[mbox].flags.extended;
filter.flags.remote = MBFilters[mbox].flags.remote;
filter.flags.reserved = MBFilters[mbox].flags.reserved;
return (true);
}
return (false);
}
/*
* \brief Set the mailbox mask for filtering packets
*
* \param mask - mask to apply.
* \param mbox - mailbox number
*
* \retval None.
*/
void FlexCAN::setMask (uint32_t mask, uint8_t mbox)
{
if ( mbox < getNumRxBoxes() ) {
/* Per mailbox masks can only be set in freeze mode so have to enter that mode if not already there. */
bool wasFrozen=isFrozen();
if (!wasFrozen) {
freeze();
halt();
}
FLEXCANb_MB_MASK(flexcanBase, mbox) = mask;
if (!wasFrozen) exitHalt();
}
}
/*
* \brief How many messages are available to read.
*
* \param None
*
* \retval A count of the number of messages available.
*/
uint32_t FlexCAN::available (void)
{
irqLock();
uint32_t result=(ringBufferCount (rxRing));
irqRelease();
return result;
}
/*
* \brief Clear the collected statistics
*
* \param None
*
* \retval None
*/
#if defined(COLLECT_CAN_STATS)
void FlexCAN::clearStats (void)
{
// initialize the statistics structure
memset (&stats, 0, sizeof(stats));
stats.enabled = false;
stats.ringRxMax = SIZE_RX_BUFFER - 1;
stats.ringTxMax = SIZE_TX_BUFFER - 1;
stats.ringRxFramesLost = 0;
}
#endif
/*
* \brief Retrieve a frame from the RX buffer
*
* \param msg - buffer reference to the frame structure to fill out
*
* \retval 0 no frames waiting to be received, 1 if a frame was returned
*/
int FlexCAN::read (CAN_message_t &msg)
{
/* pull the next available message from the ring */
int result=0;
irqLock();
if (removeFromRingBuffer (rxRing, msg) == true) {
result=1;
}
irqRelease();
return result;
}
/*
* \brief Send a frame out of this canbus port
*
* \param msg - the filled out frame structure to use for sending
*
* \note Will do one of two things - 1. Send the given frame out of the first available mailbox
* or 2. queue the frame for sending later via interrupt. Automatically turns on TX interrupt
* if necessary.
* Messages may be transmitted out of order, if more than one transmit mailbox is enabled.
* The message queue ignores the message priority.
*
* Returns whether sending/queueing succeeded. Will not smash the queue if it gets full.
*/
int FlexCAN::write (const CAN_message_t &msg)
{
uint32_t index=getNumMailBoxes();
int result=0;
irqLock();
if ( isRingBufferEmpty(txRing) ) { // If there is nothing buffered, find free mailbox
for (index = getFirstTxBox(); index < getNumMailBoxes(); index++) {
if ( usesGlobalTxRing(index) && FLEXCAN_get_code(FLEXCANb_MBn_CS(flexcanBase, index)) == FLEXCAN_MB_CODE_TX_INACTIVE ) {
break;// found one
}
}
}
if (index < getNumMailBoxes()) {
dbg_println ("Writing a frame directly.");
writeTxRegisters (msg, index);
result=1;
} else {
// no mailboxes available. Try to buffer it
if (addToRingBuffer (txRing, msg) == true) {
result=1;
}
// else could not send the frame!
}
irqRelease();
return result;
}
/*
* \brief Send a frame out of this canbus port, using a specific mailbox. The TX queue is not used.
*
* \param msg - the filled out frame structure to use for sending
* \param mbox - mailbox selected
*
* \note If the mailbox is available, the message is placed in the mailbox. The CAN controller
* selects the next message to send from all filled transmit mailboxes, based on the priority.
* This method allows callers to not use the transmit queue and prioritize messages by using
* different mailboxes for different priority levels.
* Using the same mailbox for a group of messages enforces the transmit order for this group.
*
* Returns whether the message was placed in the mailbox for sending.
*/
int FlexCAN::write (const CAN_message_t &msg, uint8_t mbox)
{
int result=0;
if ( !isTxBox(mbox) ) return result;
irqLock();
if ( txRings[mbox]==0 || isRingBufferEmpty(*txRings[mbox]) ) {
if ( FLEXCAN_get_code(FLEXCANb_MBn_CS(flexcanBase, mbox)) == FLEXCAN_MB_CODE_TX_INACTIVE ) {
writeTxRegisters (msg, mbox);
result=1;
}
}
if (result==0 && txRings[mbox]!=0 && addToRingBuffer(*txRings[mbox], msg) ) {
result=1;
}
irqRelease();
return result;
}
/*
* \brief Write CAN message to the FlexCAN hardware registers.
*
* \param msg - message structure to send.
* \param buffer - mailbox number to write to.
*
* \retval None.
*
*/
void FlexCAN::writeTxRegisters (const CAN_message_t &msg, uint8_t buffer)
{
// transmit the frame
// Commented below by TTL. That caused lock time to time to FLEXCAN_MB_CODE_TX_ONCE state.
// FLEXCANb_MBn_CS(flexcanBase, buffer) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_INACTIVE);
if (msg.flags.extended) {
FLEXCANb_MBn_ID(flexcanBase, buffer) = (msg.id & FLEXCAN_MB_ID_EXT_MASK);
} else {
FLEXCANb_MBn_ID(flexcanBase, buffer) = FLEXCAN_MB_ID_IDSTD(msg.id);
}
FLEXCANb_MBn_WORD0(flexcanBase, buffer) = (msg.buf[0]<<24)|(msg.buf[1]<<16)|(msg.buf[2]<<8)|msg.buf[3];
FLEXCANb_MBn_WORD1(flexcanBase, buffer) = (msg.buf[4]<<24)|(msg.buf[5]<<16)|(msg.buf[6]<<8)|msg.buf[7];
if (msg.flags.extended) {
if (msg.flags.remote) {
FLEXCANb_MBn_CS(flexcanBase, buffer) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_ONCE) |
FLEXCAN_MB_CS_LENGTH(msg.len) | FLEXCAN_MB_CS_SRR |
FLEXCAN_MB_CS_IDE | FLEXCAN_MB_CS_RTR;
} else {
FLEXCANb_MBn_CS(flexcanBase, buffer) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_ONCE) |
FLEXCAN_MB_CS_LENGTH(msg.len) | FLEXCAN_MB_CS_SRR |
FLEXCAN_MB_CS_IDE;
}
} else {
if (msg.flags.remote) {
FLEXCANb_MBn_CS(flexcanBase, buffer) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_ONCE) |
FLEXCAN_MB_CS_LENGTH(msg.len) | FLEXCAN_MB_CS_RTR;
} else {
FLEXCANb_MBn_CS(flexcanBase, buffer) = FLEXCAN_MB_CS_CODE(FLEXCAN_MB_CODE_TX_ONCE) |
FLEXCAN_MB_CS_LENGTH(msg.len);
}
}
}
/*
* \brief Read CAN message from the FlexCAN hardware registers.
*
* \param msg - message structure to fill.
* \param buffer - mailbox number to read from.
*
* \retval None.
*
*/
void FlexCAN::readRxRegisters (CAN_message_t& msg, uint8_t buffer)
{
uint32_t mb_CS = FLEXCANb_MBn_CS(flexcanBase, buffer);
// get identifier and dlc
msg.len = FLEXCAN_get_length (mb_CS);
msg.flags.extended = (mb_CS & FLEXCAN_MB_CS_IDE) ? 1:0;
msg.flags.remote = (mb_CS & FLEXCAN_MB_CS_RTR) ? 1:0;
msg.timestamp = FLEXCAN_get_timestamp (mb_CS);
msg.flags.overrun = 0;
msg.flags.reserved = 0;
msg.id = (FLEXCANb_MBn_ID(flexcanBase, buffer) & FLEXCAN_MB_ID_EXT_MASK);
if (!msg.flags.extended) {
msg.id >>= FLEXCAN_MB_ID_STD_BIT_NO;
}
// check for mailbox buffer overruns
if (FLEXCAN_get_code (mb_CS) == FLEXCAN_MB_CODE_RX_OVERRUN) {
msg.flags.overrun = 1;
}
// copy out message
uint32_t dataIn = FLEXCANb_MBn_WORD0(flexcanBase, buffer);
msg.buf[3] = dataIn;
dataIn >>=8;
msg.buf[2] = dataIn;
dataIn >>=8;
msg.buf[1] = dataIn;
dataIn >>=8;
msg.buf[0] = dataIn;
if (msg.len > 4) {
dataIn = FLEXCANb_MBn_WORD1(flexcanBase, buffer);
msg.buf[7] = dataIn;
dataIn >>=8;
msg.buf[6] = dataIn;
dataIn >>=8;
msg.buf[5] = dataIn;
dataIn >>=8;
msg.buf[4] = dataIn;
}
for (uint32_t loop=msg.len; loop < 8; loop++ ) {
msg.buf[loop] = 0;
}
}
/*
* \brief Initialize the specified ring buffer.
*
* \param ring - ring buffer to initialize.
* \param buffer - buffer to use for storage.
* \param size - size of the buffer in bytes.
*
* \retval None.
*
*/
void FlexCAN::initRingBuffer (ringbuffer_t &ring, volatile CAN_message_t *buffer, uint32_t size)
{
ring.buffer = buffer;
ring.size = size;
ring.head = 0;
ring.tail = 0;
}
/*
* \brief Add a CAN message to the specified ring buffer.
*
* \param ring - ring buffer to use.
* \param msg - message structure to add.
*
* \retval true if added, false if the ring is full.
*
*/
bool FlexCAN::addToRingBuffer (ringbuffer_t &ring, const CAN_message_t &msg)
{
uint16_t nextEntry;
nextEntry = (ring.head + 1) % ring.size;
/* check if the ring buffer is full */
if (nextEntry == ring.tail) {