/
dual_motor_torque_ctrl.c
1767 lines (1409 loc) · 59 KB
/
dual_motor_torque_ctrl.c
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
// --COPYRIGHT--,BSD
// Copyright (c) 2015, Texas Instruments Incorporated
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//7
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Texas Instruments Incorporated nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// --/COPYRIGHT
//! \file solutions/instaspin_motion/src/proj_lab12c.c
//! \brief Dual sensored speed control using SpinTAC
//!
//! (C) Copyright 2015, Texas Instruments, Inc.
//! \defgroup PROJ_LAB12C PROJ_LAB12C
//@{
//! \defgroup PROJ_LAB12C_OVERVIEW Project Overview
//!
//! Basic implementation of FOC by using the estimator for angle and speed
//! feedback only. Adds in SpinTAC Velocity Contol and SpinTAC Velocity Move
//! Dual sensored speed control using SpinTAC
//!
// **************************************************************************
// the includes
// system includes
#include <math.h>
#include <amd_motorware_ext/button.h>
#include <amd_motorware_ext/utils.h>
#include "main_2mtr.h"
#include "main_helper.h"
#include "spiapi.h"
#include "spintac.h"
#include <strings.h>
#ifdef FLASH
#pragma CODE_SECTION(motor1_ISR, "ramfuncs");
#pragma CODE_SECTION(motor2_ISR, "ramfuncs");
#pragma CODE_SECTION(xint1_ISR, "ramfuncs");
#pragma CODE_SECTION(spi_ISR, "ramfuncs");
#endif
// **************************************************************************
// the defines
// **************************************************************************
// the globals
//! \name Objects and Handles
//! \brief State objects and handles for the used software modules
//!
//! Typically each module of the MotorWare library has an object type that
//! stores the state of the object as well as a handle type that is simply a
//! pointer to the object. When calling functions of the module, the handle is
//! passed so that the function can operate on the current state.
//!
//! For most of the modules there are two object instances, one for each motor
//! (the first one in the array refers to HAL_MTR1, the second one to HAL_MTR2).
//!
//! \{
//! \brief The handles for the hardware abstraction layer for common CPU setup
HAL_Handle halHandle;
//! \brief The hardware abstraction layer object
HAL_Obj hal;
//! \brief The handles for the hardware abstraction layer specific to the motor
//! board.
HAL_Handle_mtr halHandleMtr[2];
//! \brief The hardware abstraction layer object specific to the motor board.
HAL_Obj_mtr halMtr[2];
//! \brief The handles for the current Clarke transform
CLARKE_Handle clarkeHandle_I[2];
//! \brief The current Clarke transform objects
CLARKE_Obj clarke_I[2];
//! \brief The handles for the current Park transfrom
PARK_Handle parkHandle[2];
//! \brief The current Parke transform objects
PARK_Obj park[2];
//! \brief The handles for the voltage Clarke transform
CLARKE_Handle clarkeHandle_V[2];
//! \brief The voltage Clarke transform objects
CLARKE_Obj clarke_V[2];
//! \brief The handles for the inverse Park transform
IPARK_Handle iparkHandle[2];
//! \brief The inverse Park transform object
IPARK_Obj ipark[2];
//! \brief The handles for the estimator
//!
//! There is no EST_Obj because this is stored in the ROM of the MCU.
EST_Handle estHandle[2];
//! \brief The handles for the PID controllers
//!
//! First dimention: 0 = motor 1, 1 = motor 2
//! Second dimention: 0 = Speed, 1 = Id, 2 = Iq
PID_Handle pidHandle[2][3];
//! \brief The objects for the PID controllers
PID_Obj pid[2][3];
//! \brief The handles for the space vector generator
SVGEN_Handle svgenHandle[2];
//! \brief The space vector generator objects
SVGEN_Obj svgen[2];
//! \brief The handles for the encoder
ENC_Handle encHandle[2];
//! \brief The encoder objects
ENC_Obj enc[2];
//! \brief The handles for the slip compensator
SLIP_Handle slipHandle[2];
//! \brief The slip compensator objects
SLIP_Obj slip[2];
//! \brief The handles for the angle compensation
ANGLE_COMP_Handle angleCompHandle[2];
//! \brief The angle compensation objects
ANGLE_COMP_Obj angleComp[2];
//! \brief The handles for the 3 current and 3 voltage filters for offset
//! calculation.
FILTER_FO_Handle filterHandle[2][6];
//! \brief the 3-current and 3-voltage filters for offset calculation of each
//! motor.
FILTER_FO_Obj filter[2][6];
//! \brief The handles for the SpinTAC objects
ST_Handle stHandle[2];
//! \brief The SpinTAC objects
ST_Obj st_obj[2];
//! \}
//! \name Counters
//! \brief Counter variables used for decimation and timing of processes
//! \{
//! \brief Count variable to decimate the execution of the high-level controller
uint16_t stCntSpeed[2] = {0, 0};
//! \brief Count variable to decimate the execution of SpinTAC Position
//! Converter
uint16_t stCntPosConv[2] = {0, 0};
//! \brief Count variable to measure duration of the offset calculation
uint32_t gOffsetCalcCount[2] = {0, 0};
//! \brief Count variable to measure duration of the motor alignment
uint32_t gAlignCount[2] = {0, 0};
//! \}
//! \name Enable Flags
//! \brief Flags to enable/disable parts of the program
//! \{
//! While set, the current position is stored as offset which is removed from
//! the position before sending it via SPI (i.e. the current position becomes
//! zero).
//! \note This feature is currently disabled!
bool gFlag_resetZeroPositionOffset = false;
//! \brief If true, a rollover of the PosConv module will trigger an error.
//!
//! This is nice for position control applications where the motor is not
//! expected to move far enough to ever observe an rollover. By throwing an
//! error in the case it happens nonetheless, it is ensured that the system will
//! not explode.
//!
//! \note For applications where rollovers are expected (i.e. motor spinning
//! freely), this should be disabled!
bool gFlag_enablePosRolloverError = false;
//! \}
//! \name Data Variables
//! \brief These variables are used to store data values like measured current,
//! voltage, reference values in pu, scale factors, etc.
//! \{
//! \brief Contains the pwm values for each phase.
//!
//! -1.0 is 0%, 1.0 is 100%
HAL_PwmData_t gPwmData[2] = {
{_IQ(0.0), _IQ(0.0), _IQ(0.0)},
{_IQ(0.0), _IQ(0.0), _IQ(0.0)}
};
//! \brief Contains three current values, three voltage values and one DC bus
//! value.
HAL_AdcData_t gAdcData[2];
//! \brief Contains the offsets for the current feedback
MATH_vec3 gOffsets_I_pu[2] = {
{_IQ(0.0), _IQ(0.0), _IQ(0.0)},
{_IQ(0.0), _IQ(0.0), _IQ(0.0)}
};
//! \brief Contains the offsets for the voltage feedback
MATH_vec3 gOffsets_V_pu[2] = {
{_IQ(0.0), _IQ(0.0), _IQ(0.0)},
{_IQ(0.0), _IQ(0.0), _IQ(0.0)}
};
//! \brief Contains the Id and Iq references
MATH_vec2 gIdq_ref_pu[2] = {
{_IQ(0.0), _IQ(0.0)},
{_IQ(0.0), _IQ(0.0)}
};
//! \brief Contains the output Vd and Vq from the current controllers
MATH_vec2 gVdq_out_pu[2] = {
{_IQ(0.0), _IQ(0.0)},
{_IQ(0.0), _IQ(0.0)}
};
//! \brief Contains the Id and Iq measured values
MATH_vec2 gIdq_pu[2] = {
{_IQ(0.0), _IQ(0.0)},
{_IQ(0.0), _IQ(0.0)}
};
//! \brief Some scale factor used for torque computation
_iq gTorque_Ls_Id_Iq_pu_to_Nm_sf[2];
//! \brief Some scale factor used for torque computation
_iq gTorque_Flux_Iq_pu_to_Nm_sf[2];
//! \brief Scale factor to convert speed from pu to krpm
_iq gSpeed_pu_to_krpm_sf[2];
//! \brief Scale factor to convert current from A to pu
_iq gCurrent_A_to_pu_sf[2];
//! \brief Offset that is removed from the position before sending it via SPI.
_iq gZeroPositionOffset[2] = {0, 0};
//! \brief Flag to enable the index encoder offset compensation. (position=0 at the index)
bool gEnableIndexOffsetCompensation[2] = {false,false};
//! \brief last position used by the Custom software Velocity Filter
_iq gLastPosition[2] = {0,0};
//! \}
//! \brief Decimation factor for the SpinTAC Position Converter
//!
//! Store this to array so it can be used in generic_motor_ISR.
const uint16_t gNumIsrTicksPerPosConvTick[2] = {
ISR_TICKS_PER_POSCONV_TICK,
ISR_TICKS_PER_POSCONV_TICK_2
};
//! \brief User Parameters
//!
//! Contains parameters from the user*.h config files.
USER_Params gUserParams[2];
//! \brief Global motor variables
//!
//! Several status information about the motors is stored here so they can be
//! accessed from the debugger or the GUI.
volatile MOTOR_Vars_t gMotorVars[2] = {MOTOR_Vars_INIT_Mtr1,
MOTOR_Vars_INIT_Mtr2};
#ifdef FLASH
// Used for running BackGround in flash, and ISR in RAM
extern uint16_t *RamfuncsLoadStart, *RamfuncsLoadEnd, *RamfuncsRunStart;
#endif
#ifdef DRV8301_SPI
// Watch window interface to the 8301 SPI
DRV_SPI_8301_Vars_t gDrvSpi8301Vars[2];
#endif
#ifdef DRV8305_SPI
// Watch window interface to the 8305 SPI
DRV_SPI_8305_Vars_t gDrvSpi8305Vars[2];
#endif
//! Timestamp based on timer 0 (increased by one at each timer interrupt).
uint32_t gTimer0_cnt = 0;
//! Timestamp based on gtimer0_cnt and rectified to count milleseconds elapsed.
uint32_t gTimer0_stamp = 0;
//! Last time the blinking status LED was toggled (based on gTimer0_stamp).
uint32_t gStatusLedBlinkLastToggleTime = 0;
//! Last time a IqRef message was received via SPI (based on gTimer0_stamp).
uint32_t gSPILastReceivedIqRef_stamp = 0;
//! Timeout for incoming IqRef messages. If exceeded, error is set. To disable
//! timeout, set to 0.
uint32_t gSPIReceiveIqRefTimeout = 0;
//! Errors that occured in the system. gErrors.all == 0 if no errors occured.
Error_t gErrors;
//! QEP index watchdog data for both encoders.
QepIndexWatchdog_t gQepIndexWatchdog[2] = {
{.isInitialized = false, .indexError_counts = 0, .toggleBit = false},
{.isInitialized = false, .indexError_counts = 0, .toggleBit = false}};
//! Time for slowly increasing the torque used for calibration.
uint_least32_t gCalibrationWrampupTime = (uint_least32_t)( 0.5 * USER_CTRL_FREQ_Hz);
//! Time to hold the motor steady at calibration current for calibration.
uint_least32_t gCalibrationHoldTime = (uint_least32_t)( 0.5 * USER_CTRL_FREQ_Hz);
_iq gIdq_ref_pu_calibrate[2] = {_IQ(0.), _IQ(0.)};
// function prototypes
interrupt void xint1_ISR(void);
inline void spi_load_firsts_words();
inline void spi_prepare_and_read_msg();
inline void spi_apply_mode_commands(uint16_t *packet);
inline void spi_apply_command_motor(uint16_t *packet);
//Holds 2 spi packets (one to read, one to write) and a boolean to indicate which is which
spi_SUPER_packets gSPI_packets_recv;
spi_SUPER_packets gSPI_packets_send;
//Current packet to read and write to in SPI interrupts
volatile uint16_t *gSPI_current_rx_packet;
volatile uint16_t *gSPI_current_tx_packet;
volatile int gSPI_rx_ptr;
volatile int gSPI_tx_ptr;
//Running CRCs
uint32_t gSPI_crc_send;
uint32_t gSPI_crc_recv;
long int gDebug_wrong_CRC = 0;
//Is SPI currently transmitting ?
volatile bool gSPI_transmitting = false;
//Is a new packet ready to send ?
volatile bool gSPI_msg_prepared = false;
//Has a new SPI packet arrived completely ?
volatile bool gSPI_msg_received = false;
//Indicate when to read receive packets and prepare a new one to send (asynchronously)
volatile bool gSPI_timer = false;
//! \brief Feedforward Iq Currents
_iq gIqFeedforward_A[2] = {0,0};
//! \brief Position gains
_iq gKp_ApMrev[2] = {0,0};
//! \brief Velocity gains
_iq gKd_Apkrpm[2] = {0,0};
//! \brief PD+ saturation current.
_iq gIqSat[2] = {0,0};
//! \brief reference positions
_iq gPositionRef[2] = {0,0};
//! \brief reference velocities
_iq gVelocityRef[2] = {0,0};
//! \brief If a PD control should be applied right after startup for debugging modules or not.
//#define DEBUG_PD_AT_STARTUP
void setupSPI() {
bzero(&gSPI_packets_recv, sizeof(spi_SUPER_packets));
bzero(&gSPI_packets_send, sizeof(spi_SUPER_packets));
gSPI_current_rx_packet = (void*) packet_to_write(gSPI_packets_recv);
gSPI_current_tx_packet = (void*) packet_ready(gSPI_packets_send);
gSPI_rx_ptr = 0;
gSPI_tx_ptr = 0;
}
// **************************************************************************
// the functions
inline void spi_apply_mode_commands(uint16_t *packet) {
uint16_t mode = SPI_REG_u16(packet, SPI_COMMAND_MODE);
//Enable system only if there is no error
if(gErrors.all==0)
{
gMotorVars[HAL_MTR1].Flag_enableSys = (bool) ((mode & SPI_COMMAND_MODE_ES) != 0);
}
gMotorVars[HAL_MTR1].Flag_Run_Identify = ((mode & SPI_COMMAND_MODE_EM1) != 0);
gMotorVars[HAL_MTR2].Flag_Run_Identify = ((mode & SPI_COMMAND_MODE_EM2) != 0);
gSPIReceiveIqRefTimeout = mode & SPI_COMMAND_MODE_TIMEOUT;
gFlag_enablePosRolloverError = ((mode & SPI_COMMAND_MODE_EPRE) != 0);
gEnableIndexOffsetCompensation[HAL_MTR1] = ((mode & SPI_COMMAND_MODE_EI1OC) != 0);
gEnableIndexOffsetCompensation[HAL_MTR2] = ((mode & SPI_COMMAND_MODE_EI2OC) != 0);
}
inline void spi_load_firsts_words() {
HAL_Obj *obj = (HAL_Obj *)halHandle;
SPI_Obj *spiB = (SPI_Obj *)obj->spiBHandle;
/* Reset FIFOs and disable interrupts */
SPI_resetTxFifo(spiB);
SPI_enableTxFifo(spiB);
/* reset pointers */
gSPI_tx_ptr = 0;
gSPI_crc_send = 0xFFFFFFFF;
/* Start filling the TX FIFO with the next packet */
// I have to fill 'by hand' otherwise the first word of RXFIFO is not push in it for the 1st word of the transmission...
spiB->SPIDAT = gSPI_current_tx_packet[0];
updateCRC(&gSPI_crc_send, gSPI_current_tx_packet[0]);
for(gSPI_tx_ptr=1;gSPI_tx_ptr<5;gSPI_tx_ptr++) {
SPI_write(spiB, gSPI_current_tx_packet[gSPI_tx_ptr]);
updateCRC(&gSPI_crc_send, gSPI_current_tx_packet[gSPI_tx_ptr]);
}
}
interrupt void xint1_ISR() // generated when the SPI-CS line changes, indicating the start or the end of a packet
{
HAL_Obj *obj = (HAL_Obj *)halHandle;
SPI_Obj *spiB = (SPI_Obj *)obj->spiBHandle;
if(GPIO_read(obj->gpioHandle,GPIO_Number_27)) { //CS Line goes high <=> This is the end of a packet
/* This interrupt can be triggered before spi_ISR, so the last two words can still be in the buffer */
if(gSPI_rx_ptr < SPI_TOTAL_LEN) { //1st word
gSPI_current_rx_packet[gSPI_rx_ptr++] = SPI_read(spiB);
updateCRC(&gSPI_crc_recv, gSPI_current_rx_packet[gSPI_rx_ptr-1]);
}
if(gSPI_rx_ptr < SPI_TOTAL_LEN) { //2nd word
gSPI_current_rx_packet[gSPI_rx_ptr++] = SPI_read(spiB);
updateCRC(&gSPI_crc_recv, gSPI_current_rx_packet[gSPI_rx_ptr-1]);
}
/* Resets SPI */
SPI_resetRxFifo(spiB);
SPI_enableRxFifo(spiB);
/* One message has been received */
gSPI_msg_received = true;
/* End of transmission */
gSPI_transmitting = false;
spi_load_firsts_words();
} else { //CS Line goes low <=> beginning of a packet
/* Beginning of transmission */
gSPI_transmitting = true;
/* Prevent reading the packet that is being written */
gSPI_msg_received = false;
/* Initialize CRC */
gSPI_crc_recv = 0xFFFFFFFF;
/* Reset pointer */
gSPI_rx_ptr = 0;
}
/* Acknowledge the interrupt */
PIE_clearInt(obj->pieHandle, PIE_GroupNumber_1);
}
interrupt void spi_ISR() // generated every 2 words received/sent
{
HAL_Obj *obj = (HAL_Obj *)halHandle;
SPI_Obj *spiB = (SPI_Obj *)obj->spiBHandle;
if(gSPI_transmitting) { //If this interrupt occurs after the CS went high the words received has already been handled in xint1_ISR
/* Remove the 2 words received from RX FIFO and put it in the global rx packet */
gSPI_current_rx_packet[gSPI_rx_ptr++] = SPI_read(spiB); //1st word
updateCRC(&gSPI_crc_recv, gSPI_current_rx_packet[gSPI_rx_ptr-1]); //running CRC
gSPI_current_rx_packet[gSPI_rx_ptr++] = SPI_read(spiB); //2nd word
updateCRC(&gSPI_crc_recv, gSPI_current_rx_packet[gSPI_rx_ptr-1]); //running CRC
/* Fill the TX FIFO with data from global tx packet */
/* Checks if everything has already been put in the FIFO*/
if(gSPI_tx_ptr < SPI_TOTAL_LEN) {
updateCRC(&gSPI_crc_send, gSPI_current_tx_packet[gSPI_tx_ptr]); //running CRC
SPI_write(spiB, gSPI_current_tx_packet[gSPI_tx_ptr++]); //1st word
}
/* Checks if the only remaining data to send is the CRC*/
if(gSPI_tx_ptr == SPI_TOTAL_LEN - 2) {
SPI_REG_u32(gSPI_current_tx_packet, SPI_TOTAL_CRC) = gSPI_crc_send; //Copy running CRC at the right place in the global tx packet
}
/* Same for the 2nd word */
if(gSPI_tx_ptr < SPI_TOTAL_LEN) {
updateCRC(&gSPI_crc_send, gSPI_current_tx_packet[gSPI_tx_ptr]);
SPI_write(spiB, gSPI_current_tx_packet[gSPI_tx_ptr++]);
}
if(gSPI_tx_ptr == SPI_TOTAL_LEN - 2) {
SPI_REG_u32(gSPI_current_tx_packet, SPI_TOTAL_CRC) = gSPI_crc_send;
}
}
/* Acknowledge the interrupt */
SPI_clearRxFifoInt(spiB);
PIE_clearInt(obj->pieHandle, PIE_GroupNumber_6);
}
void main(void)
{
// IMPORTANT NOTE: If you are not familiar with MotorWare coding guidelines
// please refer to the following document:
// C:/ti/motorware/motorware_1_01_00_1x/docs/motorware_coding_standards.pdf
// Only used if running from FLASH
// Note that the variable FLASH is defined by the project
#ifdef FLASH
// Copy time critical code and Flash setup code to RAM
// The RamfuncsLoadStart, RamfuncsLoadEnd, and RamfuncsRunStart
// symbols are created by the linker. Refer to the linker files.
memCopy((uint16_t *)&RamfuncsLoadStart, (uint16_t *)&RamfuncsLoadEnd,
(uint16_t *)&RamfuncsRunStart);
#endif
// At the beginning, there are no errors
gErrors.all = 0;
#ifdef DEBUG_PD_AT_STARTUP
// For debugging: Enable the motors programmatically.
gMotorVars[HAL_MTR1].Flag_enableSys = true; // enable the system in general
gMotorVars[HAL_MTR1].Flag_Run_Identify = true; // enable the motor
gMotorVars[HAL_MTR2].Flag_enableSys = true; // enable the system in general
gMotorVars[HAL_MTR2].Flag_Run_Identify = true; // enable the motor
// Run a P controller by default. This is useful for testing the udriver
// without attaching a master board to it.
gIqSat[HAL_MTR1] = _IQ(2.0);
gIqSat[HAL_MTR2] = _IQ(2.0);
gKp_ApMrev[HAL_MTR1] = _IQ(1.);
gKp_ApMrev[HAL_MTR2] = _IQ(1.);
#endif
// initialize the Hardware Abstraction Layer (HAL)
// halHandle will be used throughout the code to interface with the HAL
// (set parameters, get and set functions, etc) halHandle is required since
// this is how all objects are interfaced, and it allows interface with
// multiple objects by simply passing a different handle. The use of
// handles is explained in this document:
// C:/ti/motorware/motorware_1_01_00_1x/docs/motorware_coding_standards.pdf
halHandle = HAL_init(&hal, sizeof(hal));
// initialize the user parameters
// This function initializes all values of structure gUserParams with
// values defined in user.h. The values in gUserParams will be then used by
// the hardware abstraction layer (HAL) to configure peripherals such as
// PWM, ADC, interrupts, etc.
USER_setParamsMtr1(&gUserParams[HAL_MTR1]);
USER_setParamsMtr2(&gUserParams[HAL_MTR2]);
// set the hardware abstraction layer parameters
// This function initializes all peripherals through a Hardware Abstraction
// Layer (HAL). It uses all values stored in gUserParams.
HAL_setParams(halHandle, &gUserParams[HAL_MTR1]);
// Overwrite GPIO Qualification Settings
// =====================================
// To allow fast movement with lots-of-lines-encoders, the sampling period
// of the GPIO qualification filter has to be reduced (otherwise encoder
// pulses get rejected as noise). The following lines overwrite the
// settings done in HAL_setupGpio() (hal.c).
// "period = 11" results in actual sampling period 11*2*(1/90MHz) = 0.24us
// Note: Setting the period is done for blocks of GPIO pins.
//
// GPIO 16-23 (covering eQEP1)
GPIO_setQualificationPeriod(hal.gpioHandle, GPIO_Number_16, 11); //GPIO16-23
// GPIO 50-55 and 56-58 (covering eQEP2)
GPIO_setQualificationPeriod(hal.gpioHandle, GPIO_Number_50, 11); //GPIO50-55
GPIO_setQualificationPeriod(hal.gpioHandle, GPIO_Number_56, 11); //GPIO56-58
// Overwrite the settings for timer0 (we want it faster)
uint32_t timerPeriod_cnts = ((uint32_t)gUserParams[0].systemFreq_MHz * 1e6l)
/ TIMER0_FREQ_Hz - 1;
overwriteSetupTimer0(halHandle, timerPeriod_cnts);
// initialize the estimator
estHandle[HAL_MTR1] = EST_init((void *)USER_EST_HANDLE_ADDRESS, 0x200);
estHandle[HAL_MTR2] = EST_init((void *)USER_EST_HANDLE_ADDRESS_1, 0x200);
{
uint_least8_t mtrNum;
for(mtrNum=HAL_MTR1;mtrNum<=HAL_MTR2;mtrNum++)
{
// initialize the individual motor hal files
halHandleMtr[mtrNum] = HAL_init_mtr(
&halMtr[mtrNum],
sizeof(halMtr[mtrNum]),
(HAL_MtrSelect_e)mtrNum);
// Setup each motor board to its specific setting
HAL_setParamsMtr(
halHandleMtr[mtrNum], halHandle, &gUserParams[mtrNum]);
{
// These function calls are used to initialize the estimator
// with ROM function calls. It needs the specific address where
// the controller object is declared by the ROM code.
CTRL_Handle ctrlHandle = CTRL_init(
(void *)USER_CTRL_HANDLE_ADDRESS, 0x200);
CTRL_Obj *obj = (CTRL_Obj *)ctrlHandle;
// this sets the estimator handle (part of the controller
// object) to the same value initialized above by the
// EST_init() function call. This is done so the next function
// implemented in ROM, can successfully initialize the
// estimator as part of the controller object.
obj->estHandle = estHandle[mtrNum];
// initialize the estimator through the controller. These three
// function calls are needed for the F2806xF/M implementation
// of InstaSPIN.
CTRL_setParams(ctrlHandle, &gUserParams[mtrNum]);
CTRL_setUserMotorParams(ctrlHandle);
CTRL_setupEstIdleState(ctrlHandle);
}
//Compensates for the delay introduced
//from the time when the system inputs are sampled to when the PWM
//voltages are applied to the motor windings.
angleCompHandle[mtrNum] = ANGLE_COMP_init(
&angleComp[mtrNum],
sizeof(angleComp[mtrNum]));
ANGLE_COMP_setParams(angleCompHandle[mtrNum],
gUserParams[mtrNum].iqFullScaleFreq_Hz,
gUserParams[mtrNum].pwmPeriod_usec,
gUserParams[mtrNum].numPwmTicksPerIsrTick);
// initialize the Clarke modules
// Clarke handle initialization for current signals
clarkeHandle_I[mtrNum] = CLARKE_init(
&clarke_I[mtrNum],
sizeof(clarke_I[mtrNum]));
// Clarke handle initialization for voltage signals
clarkeHandle_V[mtrNum] = CLARKE_init(
&clarke_V[mtrNum],
sizeof(clarke_V[mtrNum]));
// Park handle initialization for current signals
parkHandle[mtrNum] = PARK_init(
&park[mtrNum], sizeof(park[mtrNum]));
//*** compute scaling factors
gTorque_Ls_Id_Iq_pu_to_Nm_sf[mtrNum] =
USER_computeTorque_Ls_Id_Iq_pu_to_Nm_sf(
&gUserParams[mtrNum]);
gTorque_Flux_Iq_pu_to_Nm_sf[mtrNum] =
USER_computeTorque_Flux_Iq_pu_to_Nm_sf(
&gUserParams[mtrNum]);
gSpeed_pu_to_krpm_sf[mtrNum] = _IQ(
(gUserParams[mtrNum].iqFullScaleFreq_Hz * 60.0)
/ ((float_t)gUserParams[mtrNum].motor_numPolePairs
* 1000.0));
gCurrent_A_to_pu_sf[mtrNum] = _IQ(
1.0 / gUserParams[mtrNum].iqFullScaleCurrent_A);
// disable Rs recalculation
EST_setFlag_enableRsRecalc(estHandle[mtrNum], false);
// set the number of current sensors
setupClarke_I(clarkeHandle_I[mtrNum],
gUserParams[mtrNum].numCurrentSensors);
// set the number of voltage sensors
setupClarke_V(clarkeHandle_V[mtrNum],
gUserParams[mtrNum].numVoltageSensors);
// initialize the PID controllers
// There are two PI controllers, one for Iq and one for Id.
// This is for the Id current controller
pidHandle[mtrNum][1] = PID_init(&pid[mtrNum][1],
sizeof(pid[mtrNum][1]));
// This is for the Iq current controller
pidHandle[mtrNum][2] = PID_init(&pid[mtrNum][2],
sizeof(pid[mtrNum][2]));
// This sets up both controllers
pidSetup(pidHandle[mtrNum], gUserParams[mtrNum]);
// initialize the inverse Park module
iparkHandle[mtrNum] = IPARK_init(&ipark[mtrNum],
sizeof(ipark[mtrNum]));
// initialize the space vector generator module
svgenHandle[mtrNum] = SVGEN_init(&svgen[mtrNum],
sizeof(svgen[mtrNum]));
// initialize and configure offsets using filters
{
uint16_t cnt = 0;
_iq b0 = _IQ(gUserParams[mtrNum].offsetPole_rps
/ (float_t)gUserParams[mtrNum].ctrlFreq_Hz);
_iq a1 = (b0 - _IQ(1.0));
_iq b1 = _IQ(0.0);
for(cnt=0;cnt<6;cnt++)
{
filterHandle[mtrNum][cnt] = FILTER_FO_init(
&filter[mtrNum][cnt],
sizeof(filter[mtrNum][0]));
FILTER_FO_setDenCoeffs(filterHandle[mtrNum][cnt], a1);
FILTER_FO_setNumCoeffs(filterHandle[mtrNum][cnt], b0, b1);
FILTER_FO_setInitialConditions(filterHandle[mtrNum][cnt],
_IQ(0.0),
_IQ(0.0));
}
gMotorVars[mtrNum].Flag_enableOffsetcalc = false;
}
// initialize the encoder module
encHandle[mtrNum] = ENC_init(&enc[mtrNum], sizeof(enc[mtrNum]));
// initialize the slip compensation module
slipHandle[mtrNum] = SLIP_init(
&slip[mtrNum], sizeof(slip[mtrNum]));
// setup the SLIP module
SLIP_setup(slipHandle[mtrNum],
_IQ(gUserParams[mtrNum].ctrlPeriod_sec));
// setup faults
HAL_setupFaults(halHandleMtr[mtrNum]);
// initialize the SpinTAC Components
stHandle[mtrNum] = ST_init(
&st_obj[mtrNum], sizeof(st_obj[mtrNum]));
} // End of for loop
}
// setup the encoder module
ENC_setup(
encHandle[HAL_MTR1],
1,
USER_MOTOR_NUM_POLE_PAIRS,
USER_MOTOR_ENCODER_LINES,
0,
USER_IQ_FULL_SCALE_FREQ_Hz,
USER_ISR_FREQ_Hz,
8000.0);
ENC_setup(
encHandle[HAL_MTR2],
1,
USER_MOTOR_NUM_POLE_PAIRS_2,
USER_MOTOR_ENCODER_LINES_2,
0,
USER_IQ_FULL_SCALE_FREQ_Hz_2,
USER_ISR_FREQ_Hz_2,
8000.0);
// setup encoder index interrupts
setupQepIndexInterrupt(halHandle, halHandleMtr, &qep1IndexISR,
&qep2IndexISR);
// setup the SpinTAC Components
ST_setupPosConv_mtr1(stHandle[HAL_MTR1]);
ST_setupPosConv_mtr2(stHandle[HAL_MTR2]);
// set the pre-determined current and voltage feedback offset values
gOffsets_I_pu[HAL_MTR1].value[0] = _IQ(I_A_offset);
gOffsets_I_pu[HAL_MTR1].value[1] = _IQ(I_B_offset);
gOffsets_I_pu[HAL_MTR1].value[2] = _IQ(I_C_offset);
gOffsets_V_pu[HAL_MTR1].value[0] = _IQ(V_A_offset);
gOffsets_V_pu[HAL_MTR1].value[1] = _IQ(V_B_offset);
gOffsets_V_pu[HAL_MTR1].value[2] = _IQ(V_C_offset);
gOffsets_I_pu[HAL_MTR2].value[0] = _IQ(I_A_offset_2);
gOffsets_I_pu[HAL_MTR2].value[1] = _IQ(I_B_offset_2);
gOffsets_I_pu[HAL_MTR2].value[2] = _IQ(I_C_offset_2);
gOffsets_V_pu[HAL_MTR2].value[0] = _IQ(V_A_offset_2);
gOffsets_V_pu[HAL_MTR2].value[1] = _IQ(V_B_offset_2);
gOffsets_V_pu[HAL_MTR2].value[2] = _IQ(V_C_offset_2);
// initialize the interrupt vector table
HAL_initIntVectorTable(halHandle);
// enable the ADC interrupts
HAL_enableAdcInts(halHandle);
// enable global interrupts
HAL_enableGlobalInts(halHandle);
// enable debug interrupts
HAL_enableDebugInt(halHandle);
// enable the Timer 0 interrupts
HAL_enableTimer0Int(halHandle);
PIE_registerTimer0IntHandler(hal.pieHandle, &timer0_ISR);
// disable the PWM
HAL_disablePwm(halHandleMtr[HAL_MTR1]);
HAL_disablePwm(halHandleMtr[HAL_MTR2]);
// reconfigure GPIO pins for LEDs and button
HAL_overwriteSetupGpio(halHandle);
//Interrupt on SPI CS Line
GPIO_setDirection(halHandle->gpioHandle,GPIO_Number_27,GPIO_Direction_Input); // something was overriding my GPIO22 input setting, so we'll do it here again
GPIO_setExtInt(halHandle->gpioHandle, GPIO_Number_27, CPU_ExtIntNumber_1);
setupXINT1(halHandle, &xint1_ISR);
//Interrupt on SPI RX FIFO
setupSPIBRXInt(halHandle, &spi_ISR);
// Setup everything related to SPI communication
setupSPI();
// enable the system by default
gMotorVars[HAL_MTR1].Flag_enableSys = true;
#ifdef DRV8301_SPI
// turn on the DRV8301 if present
HAL_enableDrv(halHandleMtr[HAL_MTR1]);
HAL_enableDrv(halHandleMtr[HAL_MTR2]);
// initialize the DRV8301 interface
HAL_setupDrvSpi(halHandleMtr[HAL_MTR1], &gDrvSpi8301Vars[HAL_MTR1]);
HAL_setupDrvSpi(halHandleMtr[HAL_MTR2], &gDrvSpi8301Vars[HAL_MTR2]);
#endif
#ifdef DRV8305_SPI
// turn on the DRV8305 if present
HAL_enableDrv(halHandleMtr[HAL_MTR1]);
HAL_enableDrv(halHandleMtr[HAL_MTR2]);
// HAL_turnLedOn(halHandle, LED_ONBOARD_RED);
// HAL_turnLedOn(halHandle, LED_EXTERN_RED);
// initialize the DRV8305 interface
HAL_setupDrvSpi(halHandleMtr[HAL_MTR1], &gDrvSpi8305Vars[HAL_MTR1]);
HAL_setupDrvSpi(halHandleMtr[HAL_MTR2], &gDrvSpi8305Vars[HAL_MTR2]);
#endif
//Can be used for debugging purpose
//GPIO_setDirection(hal.gpioHandle, GPIO_Number_57, GPIO_Direction_Output);
//GPIO_setDirection(hal.gpioHandle, GPIO_Number_44, GPIO_Direction_Output);
GPIO_setDirection(hal.gpioHandle, GPIO_Number_33, GPIO_Direction_Output);
// Begin the background loop
for(;;)
{
// Waiting for enable system flag to be set
// Motor 1 Flag_enableSys is the master control.
while(!(gMotorVars[HAL_MTR1].Flag_enableSys))
{
LED_run(halHandle);
/* Asynchronous SPI message read and write */
if(!gSPI_transmitting && gSPI_timer) {
spi_prepare_and_read_msg();
gSPI_timer = false;
}
}
// loop while the enable system flag is true
// Motor 1 Flag_enableSys is the master control.
while(gMotorVars[HAL_MTR1].Flag_enableSys)
{
uint_least8_t mtrNum = HAL_MTR1;
/*** Error Checks ***/
checkErrors();
LED_run(halHandle);
// When there is an error, shut down the system to be safe
if (gErrors.all) {
gMotorVars[HAL_MTR1].Flag_enableSys = false;
break; // immediately exit the enabled == true loop
}
/* Asynchronous SPI message read and write */
if(!gSPI_transmitting && gSPI_timer) {
spi_prepare_and_read_msg();
gSPI_timer = false;
}
// Set the position reset flag via button on a GPIO
//gFlag_resetZeroPositionOffset = BUTTON_isPressed(hal.gpioHandle);
// We don't really need the position offset. Rather use the button
// as a soft emergency stop (i.e. disable system)
if (BUTTON_isPressed(hal.gpioHandle)) {
//EA: This always stops the modified µDriver from running.
//gMotorVars[HAL_MTR1].Flag_enableSys = false;
}
for(mtrNum=HAL_MTR1;mtrNum<=HAL_MTR2;mtrNum++)
{
// If the flag is set, set current position as zero offset
//if (gFlag_resetZeroPositionOffset) {
// gZeroPositionOffset[mtrNum] = STPOSCONV_getPosition_mrev(
// st_obj[mtrNum].posConvHandle);
//}
// If Flag_enableSys is set AND Flag_Run_Identify is set THEN
// enable PWMs and set the speed reference
if(gMotorVars[mtrNum].Flag_Run_Identify)
{
// update estimator state
EST_updateState(estHandle[mtrNum], 0);
#ifdef FAST_ROM_V1p6
// call this function to fix 1p6. This is only used for
// F2806xF/M implementation of InstaSPIN (version 1.6 of
// ROM), since the inductance calculation is not done
// correctly in ROM, so this function fixes that ROM bug.
softwareUpdate1p6(estHandle[mtrNum], &gUserParams[mtrNum]);
#endif
// enable the PWM
HAL_enablePwm(halHandleMtr[mtrNum]);
}
else // Flag_enableSys is set AND Flag_Run_Identify is not set
{
// set estimator to Idle
EST_setIdle(estHandle[mtrNum]);
// disable the PWM
HAL_disablePwm(halHandleMtr[mtrNum]);
// clear integrator outputs
PID_setUi(pidHandle[mtrNum][0], _IQ(0.0));
PID_setUi(pidHandle[mtrNum][1], _IQ(0.0));
PID_setUi(pidHandle[mtrNum][2], _IQ(0.0));
// clear Id and Iq references