forked from vedderb/bldc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mcpwm_foc.c
2928 lines (2482 loc) · 78.3 KB
/
mcpwm_foc.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 2016 - 2019 Benjamin Vedder benjamin@vedder.se
This file is part of the VESC firmware.
The VESC firmware is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The VESC firmware is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "mcpwm_foc.h"
#include "mc_interface.h"
#include "ch.h"
#include "hal.h"
#include "stm32f4xx_conf.h"
#include "digital_filter.h"
#include "utils.h"
#include "ledpwm.h"
#include "terminal.h"
#include "encoder.h"
#include "commands.h"
#include "timeout.h"
#include "timer.h"
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "virtual_motor.h"
// Private types
typedef struct {
float id_target;
float iq_target;
float max_duty;
float duty_now;
float phase;
float i_alpha;
float i_beta;
float i_abs;
float i_abs_filter;
float i_bus;
float v_bus;
float v_alpha;
float v_beta;
float mod_d;
float mod_q;
float id;
float iq;
float id_filter;
float iq_filter;
float vd;
float vq;
float vd_int;
float vq_int;
uint32_t svm_sector;
} motor_state_t;
typedef struct {
int sample_num;
float avg_current_tot;
float avg_voltage_tot;
bool measure_inductance_now;
float measure_inductance_duty;
} mc_sample_t;
// Private variables
static volatile mc_configuration *m_conf;
static volatile mc_state m_state;
static volatile mc_control_mode m_control_mode;
static volatile motor_state_t m_motor_state;
static volatile int m_curr0_sum;
static volatile int m_curr1_sum;
static volatile int m_curr_samples;
static volatile int m_curr0_offset;
static volatile int m_curr1_offset;
static volatile int m_curr_unbalance;
static volatile bool m_phase_override;
static volatile float m_phase_now_override;
static volatile float m_duty_cycle_set;
static volatile float m_id_set;
static volatile float m_iq_set;
static volatile float m_openloop_speed;
static volatile float m_openloop_phase;
static volatile bool m_dccal_done;
static volatile bool m_output_on;
static volatile float m_pos_pid_set;
static volatile float m_speed_pid_set_rpm;
static volatile float m_phase_now_observer;
static volatile float m_phase_now_observer_override;
static volatile bool m_phase_observer_override;
static volatile float m_phase_now_encoder;
static volatile float m_phase_now_encoder_no_index;
static volatile float m_observer_x1;
static volatile float m_observer_x2;
static volatile float m_pll_phase;
static volatile float m_pll_speed;
static volatile mc_sample_t m_samples;
static volatile int m_tachometer;
static volatile int m_tachometer_abs;
static volatile float m_last_adc_isr_duration;
static volatile float m_pos_pid_now;
static volatile bool m_init_done = false;
static volatile float m_gamma_now;
#ifdef HW_HAS_3_SHUNTS
static volatile int m_curr2_sum;
static volatile int m_curr2_offset;
#endif
// Private functions
static void do_dc_cal(void);
void observer_update(float v_alpha, float v_beta, float i_alpha, float i_beta,
float dt, volatile float *x1, volatile float *x2, volatile float *phase);
static void pll_run(float phase, float dt, volatile float *phase_var,
volatile float *speed_var);
static void control_current(volatile motor_state_t *state_m, float dt);
static void svm(float alpha, float beta, uint32_t PWMHalfPeriod,
uint32_t* tAout, uint32_t* tBout, uint32_t* tCout, uint32_t *svm_sector);
static void run_pid_control_pos(float angle_now, float angle_set, float dt);
static void run_pid_control_speed(float dt);
static void stop_pwm_hw(void);
static void start_pwm_hw(void);
static int read_hall(void);
static float correct_encoder(float obs_angle, float enc_angle, float speed);
static float correct_hall(float angle, float speed, float dt);
// Threads
static THD_WORKING_AREA(timer_thread_wa, 2048);
static THD_FUNCTION(timer_thread, arg);
static volatile bool timer_thd_stop;
// Macros
#ifdef HW_HAS_3_SHUNTS
#define TIMER_UPDATE_DUTY(duty1, duty2, duty3) \
TIM1->CR1 |= TIM_CR1_UDIS; \
TIM1->CCR1 = duty1; \
TIM1->CCR2 = duty2; \
TIM1->CCR3 = duty3; \
TIM1->CR1 &= ~TIM_CR1_UDIS;
#else
#define TIMER_UPDATE_DUTY(duty1, duty2, duty3) \
TIM1->CR1 |= TIM_CR1_UDIS; \
TIM1->CCR1 = duty1; \
TIM1->CCR2 = duty3; \
TIM1->CCR3 = duty2; \
TIM1->CR1 &= ~TIM_CR1_UDIS;
#endif
#define TIMER_UPDATE_SAMP(samp) \
TIM8->CCR1 = samp;
#define TIMER_UPDATE_SAMP_TOP(samp, top) \
TIM1->CR1 |= TIM_CR1_UDIS; \
TIM8->CR1 |= TIM_CR1_UDIS; \
TIM1->ARR = top; \
TIM8->CCR1 = samp; \
TIM1->CR1 &= ~TIM_CR1_UDIS; \
TIM8->CR1 &= ~TIM_CR1_UDIS;
#ifdef HW_HAS_3_SHUNTS
#define TIMER_UPDATE_DUTY_SAMP(duty1, duty2, duty3, samp) \
TIM1->CR1 |= TIM_CR1_UDIS; \
TIM8->CR1 |= TIM_CR1_UDIS; \
TIM1->CCR1 = duty1; \
TIM1->CCR2 = duty2; \
TIM1->CCR3 = duty3; \
TIM8->CCR1 = samp; \
TIM1->CR1 &= ~TIM_CR1_UDIS; \
TIM8->CR1 &= ~TIM_CR1_UDIS;
#else
#define TIMER_UPDATE_DUTY_SAMP(duty1, duty2, duty3, samp) \
TIM1->CR1 |= TIM_CR1_UDIS; \
TIM8->CR1 |= TIM_CR1_UDIS; \
TIM1->CCR1 = duty1; \
TIM1->CCR2 = duty3; \
TIM1->CCR3 = duty2; \
TIM8->CCR1 = samp; \
TIM1->CR1 &= ~TIM_CR1_UDIS; \
TIM8->CR1 &= ~TIM_CR1_UDIS;
#endif
void mcpwm_foc_init(volatile mc_configuration *configuration) {
utils_sys_lock_cnt();
m_init_done = false;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_BDTRInitTypeDef TIM_BDTRInitStructure;
m_conf = configuration;
// Initialize variables
m_state = MC_STATE_OFF;
m_control_mode = CONTROL_MODE_NONE;
m_curr0_sum = 0;
m_curr1_sum = 0;
m_curr_unbalance = 0.0;
m_curr_samples = 0;
m_dccal_done = false;
m_phase_override = false;
m_phase_now_override = 0.0;
m_duty_cycle_set = 0.0;
m_id_set = 0.0;
m_iq_set = 0.0;
m_openloop_speed = 0.0;
m_openloop_phase = 0.0;
m_output_on = false;
m_pos_pid_set = 0.0;
m_speed_pid_set_rpm = 0.0;
m_phase_now_observer = 0.0;
m_phase_now_observer_override = 0.0;
m_phase_observer_override = false;
m_phase_now_encoder = 0.0;
m_phase_now_encoder_no_index = 0.0;
m_observer_x1 = 0.0;
m_observer_x2 = 0.0;
m_pll_phase = 0.0;
m_pll_speed = 0.0;
m_tachometer = 0;
m_tachometer_abs = 0;
m_last_adc_isr_duration = 0;
m_pos_pid_now = 0.0;
m_gamma_now = 0.0;
memset((void*)&m_motor_state, 0, sizeof(motor_state_t));
memset((void*)&m_samples, 0, sizeof(mc_sample_t));
virtual_motor_init();
#ifdef HW_HAS_3_SHUNTS
m_curr2_sum = 0;
#endif
TIM_DeInit(TIM1);
TIM_DeInit(TIM8);
TIM1->CNT = 0;
TIM8->CNT = 0;
// TIM1 clock enable
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
// Time Base configuration
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_CenterAligned1;
TIM_TimeBaseStructure.TIM_Period = SYSTEM_CORE_CLOCK / (int)m_conf->foc_f_sw;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
// Channel 1, 2 and 3 Configuration in PWM mode
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
TIM_OCInitStructure.TIM_Pulse = TIM1->ARR / 2;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Set;
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
TIM_OC2Init(TIM1, &TIM_OCInitStructure);
TIM_OC3Init(TIM1, &TIM_OCInitStructure);
TIM_OC4Init(TIM1, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OC2PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OC4PreloadConfig(TIM1, TIM_OCPreload_Enable);
// Automatic Output enable, Break, dead time and lock configuration
TIM_BDTRInitStructure.TIM_OSSRState = TIM_OSSRState_Enable;
TIM_BDTRInitStructure.TIM_OSSIState = TIM_OSSIState_Enable;
TIM_BDTRInitStructure.TIM_LOCKLevel = TIM_LOCKLevel_OFF;
TIM_BDTRInitStructure.TIM_DeadTime = conf_general_calculate_deadtime(HW_DEAD_TIME_NSEC, SYSTEM_CORE_CLOCK);
TIM_BDTRInitStructure.TIM_Break = TIM_Break_Disable;
TIM_BDTRInitStructure.TIM_BreakPolarity = TIM_BreakPolarity_High;
TIM_BDTRInitStructure.TIM_AutomaticOutput = TIM_AutomaticOutput_Disable;
TIM_BDTRConfig(TIM1, &TIM_BDTRInitStructure);
TIM_CCPreloadControl(TIM1, ENABLE);
TIM_ARRPreloadConfig(TIM1, ENABLE);
/*
* ADC!
*/
ADC_CommonInitTypeDef ADC_CommonInitStructure;
DMA_InitTypeDef DMA_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
// Clock
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2 | RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOC, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2 | RCC_APB2Periph_ADC3, ENABLE);
dmaStreamAllocate(STM32_DMA_STREAM(STM32_DMA_STREAM_ID(2, 4)),
3,
(stm32_dmaisr_t)mcpwm_foc_adc_int_handler,
(void *)0);
// DMA for the ADC
DMA_InitStructure.DMA_Channel = DMA_Channel_0;
DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)&ADC_Value;
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&ADC->CDR;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;
DMA_InitStructure.DMA_BufferSize = HW_ADC_CHANNELS;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_1QuarterFull;
DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;
DMA_Init(DMA2_Stream4, &DMA_InitStructure);
// DMA2_Stream0 enable
DMA_Cmd(DMA2_Stream4, ENABLE);
// Enable transfer complete interrupt
DMA_ITConfig(DMA2_Stream4, DMA_IT_TC, ENABLE);
// ADC Common Init
// Note that the ADC is running at 42MHz, which is higher than the
// specified 36MHz in the data sheet, but it works.
ADC_CommonInitStructure.ADC_Mode = ADC_TripleMode_RegSimult;
ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div2;
ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_1;
ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles;
ADC_CommonInit(&ADC_CommonInitStructure);
// Channel-specific settings
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ScanConvMode = ENABLE;
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_Falling;
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T8_CC1;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfConversion = HW_ADC_NBR_CONV;
ADC_Init(ADC1, &ADC_InitStructure);
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_ExternalTrigConv = 0;
ADC_Init(ADC2, &ADC_InitStructure);
ADC_Init(ADC3, &ADC_InitStructure);
// Enable Vrefint channel
ADC_TempSensorVrefintCmd(ENABLE);
// Enable DMA request after last transfer (Multi-ADC mode)
ADC_MultiModeDMARequestAfterLastTransferCmd(ENABLE);
hw_setup_adc_channels();
// Enable ADC1
ADC_Cmd(ADC1, ENABLE);
// Enable ADC2
ADC_Cmd(ADC2, ENABLE);
// Enable ADC3
ADC_Cmd(ADC3, ENABLE);
// ------------- Timer8 for ADC sampling ------------- //
// Time Base configuration
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM8, ENABLE);
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM8, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 500;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Set;
TIM_OC1Init(TIM8, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM8, TIM_OCPreload_Enable);
TIM_OC2Init(TIM8, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM8, TIM_OCPreload_Enable);
TIM_OC3Init(TIM8, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM8, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM8, ENABLE);
TIM_CCPreloadControl(TIM8, ENABLE);
// PWM outputs have to be enabled in order to trigger ADC on CCx
TIM_CtrlPWMOutputs(TIM8, ENABLE);
// TIM1 Master and TIM8 slave
TIM_SelectOutputTrigger(TIM1, TIM_TRGOSource_Update);
TIM_SelectMasterSlaveMode(TIM1, TIM_MasterSlaveMode_Enable);
TIM_SelectInputTrigger(TIM8, TIM_TS_ITR0);
TIM_SelectSlaveMode(TIM8, TIM_SlaveMode_Reset);
// Enable TIM1 and TIM8
TIM_Cmd(TIM1, ENABLE);
TIM_Cmd(TIM8, ENABLE);
// Main Output Enable
TIM_CtrlPWMOutputs(TIM1, ENABLE);
// ADC sampling locations
stop_pwm_hw();
// Sample intervals. For now they are fixed with voltage samples in the center of V7
// and current samples in the center of V0
TIMER_UPDATE_SAMP(MCPWM_FOC_CURRENT_SAMP_OFFSET);
// Enable CC1 interrupt, which will be fired in V0 and V7
TIM_ITConfig(TIM8, TIM_IT_CC1, ENABLE);
nvicEnableVector(TIM8_CC_IRQn, 6);
utils_sys_unlock_cnt();
CURRENT_FILTER_ON();
// Calibrate current offset
ENABLE_GATE();
DCCAL_OFF();
do_dc_cal();
// Start threads
timer_thd_stop = false;
chThdCreateStatic(timer_thread_wa, sizeof(timer_thread_wa), NORMALPRIO, timer_thread, NULL);
// Check if the system has resumed from IWDG reset
if (timeout_had_IWDG_reset()) {
mc_interface_fault_stop(FAULT_CODE_BOOTING_FROM_WATCHDOG_RESET);
}
m_init_done = true;
}
void mcpwm_foc_deinit(void) {
if (!m_init_done) {
return;
}
m_init_done = false;
timer_thd_stop = true;
while (timer_thd_stop) {
chThdSleepMilliseconds(1);
}
TIM_DeInit(TIM1);
TIM_DeInit(TIM8);
ADC_DeInit();
DMA_DeInit(DMA2_Stream4);
nvicDisableVector(ADC_IRQn);
dmaStreamRelease(STM32_DMA_STREAM(STM32_DMA_STREAM_ID(2, 4)));
}
bool mcpwm_foc_init_done(void) {
return m_init_done;
}
void mcpwm_foc_set_configuration(volatile mc_configuration *configuration) {
m_conf = configuration;
m_control_mode = CONTROL_MODE_NONE;
m_state = MC_STATE_OFF;
stop_pwm_hw();
uint32_t top = SYSTEM_CORE_CLOCK / (int)m_conf->foc_f_sw;
TIMER_UPDATE_SAMP_TOP(MCPWM_FOC_CURRENT_SAMP_OFFSET, top);
}
mc_state mcpwm_foc_get_state(void) {
return m_state;
}
bool mcpwm_foc_is_dccal_done(void) {
return m_dccal_done;
}
/**
* Switch off all FETs.
*/
void mcpwm_foc_stop_pwm(void) {
mcpwm_foc_set_current(0.0);
}
/**
* Use duty cycle control. Absolute values less than MCPWM_MIN_DUTY_CYCLE will
* stop the motor.
*
* @param dutyCycle
* The duty cycle to use.
*/
void mcpwm_foc_set_duty(float dutyCycle) {
m_control_mode = CONTROL_MODE_DUTY;
m_duty_cycle_set = dutyCycle;
if (m_state != MC_STATE_RUNNING) {
m_state = MC_STATE_RUNNING;
}
}
/**
* Use duty cycle control. Absolute values less than MCPWM_MIN_DUTY_CYCLE will
* stop the motor.
*
* WARNING: This function does not use ramping. A too large step with a large motor
* can destroy hardware.
*
* @param dutyCycle
* The duty cycle to use.
*/
void mcpwm_foc_set_duty_noramp(float dutyCycle) {
// TODO: Actually do this without ramping
mcpwm_foc_set_duty(dutyCycle);
}
/**
* Use PID rpm control. Note that this value has to be multiplied by half of
* the number of motor poles.
*
* @param rpm
* The electrical RPM goal value to use.
*/
void mcpwm_foc_set_pid_speed(float rpm) {
m_control_mode = CONTROL_MODE_SPEED;
m_speed_pid_set_rpm = rpm;
if (m_state != MC_STATE_RUNNING) {
m_state = MC_STATE_RUNNING;
}
}
/**
* Use PID position control. Note that this only works when encoder support
* is enabled.
*
* @param pos
* The desired position of the motor in degrees.
*/
void mcpwm_foc_set_pid_pos(float pos) {
m_control_mode = CONTROL_MODE_POS;
m_pos_pid_set = pos;
if (m_state != MC_STATE_RUNNING) {
m_state = MC_STATE_RUNNING;
}
}
/**
* Use current control and specify a goal current to use. The sign determines
* the direction of the torque. Absolute values less than
* conf->cc_min_current will release the motor.
*
* @param current
* The current to use.
*/
void mcpwm_foc_set_current(float current) {
if (fabsf(current) < m_conf->cc_min_current) {
m_control_mode = CONTROL_MODE_NONE;
m_state = MC_STATE_OFF;
stop_pwm_hw();
return;
}
m_control_mode = CONTROL_MODE_CURRENT;
m_iq_set = current;
if (m_state != MC_STATE_RUNNING) {
m_state = MC_STATE_RUNNING;
}
}
/**
* Brake the motor with a desired current. Absolute values less than
* conf->cc_min_current will release the motor.
*
* @param current
* The current to use. Positive and negative values give the same effect.
*/
void mcpwm_foc_set_brake_current(float current) {
if (fabsf(current) < m_conf->cc_min_current) {
m_control_mode = CONTROL_MODE_NONE;
m_state = MC_STATE_OFF;
stop_pwm_hw();
return;
}
m_control_mode = CONTROL_MODE_CURRENT_BRAKE;
m_iq_set = current;
if (m_state != MC_STATE_RUNNING) {
m_state = MC_STATE_RUNNING;
}
}
/**
* Apply a fixed static current vector in open loop to emulate an electric
* handbrake.
*
* @param current
* The brake current to use.
*/
void mcpwm_foc_set_handbrake(float current) {
if (fabsf(current) < m_conf->cc_min_current) {
m_control_mode = CONTROL_MODE_NONE;
m_state = MC_STATE_OFF;
stop_pwm_hw();
return;
}
m_control_mode = CONTROL_MODE_HANDBRAKE;
m_iq_set = current;
if (m_state != MC_STATE_RUNNING) {
m_state = MC_STATE_RUNNING;
}
}
/**
* Produce an openloop rotating current.
*
* @param current
* The current to use.
*
* @param rpm
* The RPM to use.
*/
void mcpwm_foc_set_openloop(float current, float rpm) {
if (fabsf(current) < m_conf->cc_min_current) {
m_control_mode = CONTROL_MODE_NONE;
m_state = MC_STATE_OFF;
stop_pwm_hw();
return;
}
utils_truncate_number(¤t, -m_conf->l_current_max * m_conf->l_current_max_scale,
m_conf->l_current_max * m_conf->l_current_max_scale);
m_control_mode = CONTROL_MODE_OPENLOOP;
m_iq_set = current;
m_openloop_speed = rpm * ((2.0 * M_PI) / 60.0);
if (m_state != MC_STATE_RUNNING) {
m_state = MC_STATE_RUNNING;
}
}
/**
* Produce an openloop current at a fixed phase.
*
* @param current
* The current to use.
*
* @param phase
* The phase to use in degrees, range [0.0 360.0]
*/
void mcpwm_foc_set_openloop_phase(float current, float phase) {
if (fabsf(current) < m_conf->cc_min_current) {
m_control_mode = CONTROL_MODE_NONE;
m_state = MC_STATE_OFF;
stop_pwm_hw();
return;
}
utils_truncate_number(¤t, -m_conf->l_current_max * m_conf->l_current_max_scale,
m_conf->l_current_max * m_conf->l_current_max_scale);
m_control_mode = CONTROL_MODE_OPENLOOP_PHASE;
m_iq_set = current;
m_openloop_phase = phase * M_PI / 180.0;
utils_norm_angle_rad((float*)&m_openloop_phase);
if (m_state != MC_STATE_RUNNING) {
m_state = MC_STATE_RUNNING;
}
}
/**
* Set current offsets values,
* this is used by the virtual motor to set the previously saved offsets back,
* when it is disconnected
*/
void mcpwm_foc_set_current_offsets(volatile int curr0_offset,
volatile int curr1_offset,
volatile int curr2_offset){
m_curr0_offset = curr0_offset;
m_curr1_offset = curr1_offset;
#ifdef HW_HAS_3_SHUNTS
m_curr2_offset = curr2_offset;
#else
(void)curr2_offset;
#endif
}
/**
* Produce an openloop rotating voltage.
*
* @param dutyCycle
* The duty cycle to use.
*
* @param rpm
* The RPM to use.
*/
void mcpwm_foc_set_openloop_duty(float dutyCycle, float rpm) {
m_control_mode = CONTROL_MODE_OPENLOOP_DUTY;
m_duty_cycle_set = dutyCycle;
m_openloop_speed = rpm * ((2.0 * M_PI) / 60.0);
if (m_state != MC_STATE_RUNNING) {
m_state = MC_STATE_RUNNING;
}
}
/**
* Produce an openloop voltage at a fixed phase.
*
* @param dutyCycle
* The duty cycle to use.
*
* @param phase
* The phase to use in degrees, range [0.0 360.0]
*/
void mcpwm_foc_set_openloop_duty_phase(float dutyCycle, float phase) {
m_control_mode = CONTROL_MODE_OPENLOOP_DUTY_PHASE;
m_duty_cycle_set = dutyCycle;
m_openloop_phase = phase * M_PI / 180.0;
utils_norm_angle_rad((float*)&m_openloop_phase);
if (m_state != MC_STATE_RUNNING) {
m_state = MC_STATE_RUNNING;
}
}
float mcpwm_foc_get_duty_cycle_set(void) {
return m_duty_cycle_set;
}
float mcpwm_foc_get_duty_cycle_now(void) {
return m_motor_state.duty_now;
}
float mcpwm_foc_get_pid_pos_set(void) {
return m_pos_pid_set;
}
float mcpwm_foc_get_pid_pos_now(void) {
return m_pos_pid_now;
}
/**
* Get the current switching frequency.
*
* @return
* The switching frequency in Hz.
*/
float mcpwm_foc_get_switching_frequency_now(void) {
return m_conf->foc_f_sw;
}
/**
* Get the current sampling frequency.
*
* @return
* The sampling frequency in Hz.
*/
float mcpwm_foc_get_sampling_frequency_now(void) {
#ifdef HW_HAS_PHASE_SHUNTS
if (m_conf->foc_sample_v0_v7) {
return m_conf->foc_f_sw;
} else {
return m_conf->foc_f_sw / 2.0;
}
#else
return m_conf->foc_f_sw / 2.0;
#endif
}
/**
* Returns Ts used for virtual motor sync
*/
float mcpwm_foc_get_ts(void){
#ifdef HW_HAS_PHASE_SHUNTS
if (m_conf->foc_sample_v0_v7) {
return (1.0 / m_conf->foc_f_sw) ;
} else {
return (1.0 / (m_conf->foc_f_sw / 2.0));
}
#else
return (1.0 / m_conf->foc_f_sw) ;
#endif
}
/**
* Calculate the current RPM of the motor. This is a signed value and the sign
* depends on the direction the motor is rotating in. Note that this value has
* to be divided by half the number of motor poles.
*
* @return
* The RPM value.
*/
float mcpwm_foc_get_rpm(void) {
return m_pll_speed / ((2.0 * M_PI) / 60.0);
}
/**
* Get the motor current. The sign of this value will
* represent whether the motor is drawing (positive) or generating
* (negative) current. This is the q-axis current which produces torque.
*
* @return
* The motor current.
*/
float mcpwm_foc_get_tot_current(void) {
return SIGN(m_motor_state.vq) * m_motor_state.iq;
}
/**
* Get the filtered motor current. The sign of this value will
* represent whether the motor is drawing (positive) or generating
* (negative) current. This is the q-axis current which produces torque.
*
* @return
* The filtered motor current.
*/
float mcpwm_foc_get_tot_current_filtered(void) {
return SIGN(m_motor_state.vq) * m_motor_state.iq_filter;
}
/**
* Get the magnitude of the motor current, which includes both the
* D and Q axis.
*
* @return
* The magnitude of the motor current.
*/
float mcpwm_foc_get_abs_motor_current(void) {
return m_motor_state.i_abs;
}
/**
* Get the magnitude of the motor current unbalance
*
* @return
* The magnitude of the phase currents unbalance.
*/
float mcpwm_foc_get_abs_motor_current_unbalance(void) {
return (float)(m_curr_unbalance) * FAC_CURRENT;
}
/**
* Get the magnitude of the motor voltage.
*
* @return
* The magnitude of the motor voltage.
*/
float mcpwm_foc_get_abs_motor_voltage(void) {
const float vd_tmp = m_motor_state.vd;
const float vq_tmp = m_motor_state.vq;
return sqrtf(SQ(vd_tmp) + SQ(vq_tmp));
}
/**
* Get the filtered magnitude of the motor current, which includes both the
* D and Q axis.
*
* @return
* The magnitude of the motor current.
*/
float mcpwm_foc_get_abs_motor_current_filtered(void) {
return m_motor_state.i_abs_filter;
}
/**
* Get the motor current. The sign of this value represents the direction
* in which the motor generates torque.
*
* @return
* The motor current.
*/
float mcpwm_foc_get_tot_current_directional(void) {
return m_motor_state.iq;
}
/**
* Get the filtered motor current. The sign of this value represents the
* direction in which the motor generates torque.
*
* @return
* The filtered motor current.
*/
float mcpwm_foc_get_tot_current_directional_filtered(void) {
return m_motor_state.iq_filter;
}
/**
* Get the direct axis motor current.
*
* @return
* The D axis current.
*/
float mcpwm_foc_get_id(void) {
return m_motor_state.id;
}
/**
* Get the quadrature axis motor current.
*
* @return
* The Q axis current.
*/
float mcpwm_foc_get_iq(void) {
return m_motor_state.iq;
}
/**
* Get the input current to the motor controller.
*
* @return
* The input current.
*/
float mcpwm_foc_get_tot_current_in(void) {
return m_motor_state.i_bus;
}
/**
* Get the filtered input current to the motor controller.
*
* @return
* The filtered input current.
*/
float mcpwm_foc_get_tot_current_in_filtered(void) {
return m_motor_state.i_bus; // TODO: Calculate filtered current?
}
/**
* Read the number of steps the motor has rotated. This number is signed and
* will return a negative number when the motor is rotating backwards.
*
* @param reset
* If true, the tachometer counter will be reset after this call.
*
* @return
* The tachometer value in motor steps. The number of motor revolutions will
* be this number divided by (3 * MOTOR_POLE_NUMBER).
*/
int mcpwm_foc_get_tachometer_value(bool reset) {
int val = m_tachometer;
if (reset) {
m_tachometer = 0;
}
return val;
}
/**
* Read the absolute number of steps the motor has rotated.
*
* @param reset
* If true, the tachometer counter will be reset after this call.
*
* @return
* The tachometer value in motor steps. The number of motor revolutions will
* be this number divided by (3 * MOTOR_POLE_NUMBER).
*/
int mcpwm_foc_get_tachometer_abs_value(bool reset) {
int val = m_tachometer_abs;
if (reset) {
m_tachometer_abs = 0;
}
return val;
}
/**
* Read the motor phase.
*
* @return
* The phase angle in degrees.
*/