forked from vedderb/bldc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mcpwm_foc.c
2220 lines (1868 loc) · 60.5 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 2015 Benjamin Vedder benjamin@vedder.se
This program 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.
This program 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/>.
*/
/*
* mcpwm_foc.c
*
* Created on: 10 okt 2015
* Author: benjamin
*/
#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 "hw.h"
#include "terminal.h"
#include "encoder.h"
#include "commands.h"
#include "timeout.h"
#include <math.h>
#include <string.h>
#include <stdlib.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;
} 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 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 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 last_inj_adc_isr_duration;
static volatile float m_pos_pid_now;
// 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);
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_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;
// Constants
#define ONE_BY_SQRT3 (0.57735026919)
#define TWO_BY_SQRT3 (2.0f * 0.57735026919)
#define SQRT3_BY_2 (0.86602540378)
// Macros
#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;
#define TIMER_UPDATE_SAMP(current_samp, voltage_samp) \
TIM1->CR1 |= TIM_CR1_UDIS; \
TIM8->CR1 |= TIM_CR1_UDIS; \
TIM8->CCR1 = voltage_samp; \
TIM1->CCR4 = current_samp; \
TIM8->CCR2 = current_samp; \
TIM1->CR1 &= ~TIM_CR1_UDIS; \
TIM8->CR1 &= ~TIM_CR1_UDIS;
#define TIMER_UPDATE_SAMP_TOP(current_samp, voltage_samp, top) \
TIM1->CR1 |= TIM_CR1_UDIS; \
TIM8->CR1 |= TIM_CR1_UDIS; \
TIM1->ARR = top; \
TIM8->ARR = top; \
TIM8->CCR1 = voltage_samp; \
TIM1->CCR4 = current_samp; \
TIM8->CCR2 = current_samp; \
TIM1->CR1 &= ~TIM_CR1_UDIS; \
TIM8->CR1 &= ~TIM_CR1_UDIS;
#define TIMER_UPDATE_DUTY_CURRENTSAMP(duty1, duty2, duty3, current_samp) \
TIM1->CR1 |= TIM_CR1_UDIS; \
TIM8->CR1 |= TIM_CR1_UDIS; \
TIM1->CCR1 = duty1; \
TIM1->CCR2 = duty3; \
TIM1->CCR3 = duty2; \
TIM1->CCR4 = current_samp; \
TIM8->CCR2 = current_samp; \
TIM1->CR1 &= ~TIM_CR1_UDIS; \
TIM8->CR1 &= ~TIM_CR1_UDIS;
#define TIMER_DISABLE_PRELOAD_DUTY1() TIM1->CCMR1 &= (uint16_t)(~TIM_CCMR1_OC1PE)
#define TIMER_DISABLE_PRELOAD_DUTY2() TIM1->CCMR2 &= (uint16_t)(~TIM_CCMR2_OC3PE)
#define TIMER_DISABLE_PRELOAD_DUTY3() TIM1->CCMR1 &= (uint16_t)(~TIM_CCMR1_OC2PE)
#define TIMER_ENABLE_PRELOAD_DUTY1() TIM1->CCMR1 |= (uint16_t)(TIM_CCMR1_OC1PE)
#define TIMER_ENABLE_PRELOAD_DUTY2() TIM1->CCMR2 |= (uint16_t)(TIM_CCMR2_OC3PE)
#define TIMER_ENABLE_PRELOAD_DUTY3() TIM1->CCMR1 |= (uint16_t)(TIM_CCMR1_OC2PE)
void mcpwm_foc_init(volatile mc_configuration *configuration) {
utils_sys_lock_cnt();
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_BDTRInitTypeDef TIM_BDTRInitStructure;
m_conf = configuration;
// Initialize variables
m_conf = configuration;
m_state = MC_STATE_OFF;
m_control_mode = CONTROL_MODE_NONE;
m_curr0_sum = 0;
m_curr1_sum = 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_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;
last_inj_adc_isr_duration = 0;
m_pos_pid_now = 0.0;
memset((void*)&m_motor_state, 0, sizeof(motor_state_t));
memset((void*)&m_samples, 0, sizeof(mc_sample_t));
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_CenterAligned2; // compare flag when upcounting
TIM_TimeBaseStructure.TIM_Period = SYSTEM_CORE_CLOCK / (int)m_conf->foc_f_sw;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 1; // Only generate update event on underflow
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 = MCPWM_DEAD_TIME_CYCLES;
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);
// 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);
// 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);
// Injected channels for current measurement at end of cycle
ADC_ExternalTrigInjectedConvConfig(ADC1, ADC_ExternalTrigInjecConv_T1_CC4);
ADC_ExternalTrigInjectedConvConfig(ADC2, ADC_ExternalTrigInjecConv_T8_CC2);
ADC_ExternalTrigInjectedConvEdgeConfig(ADC1, ADC_ExternalTrigInjecConvEdge_Falling);
ADC_ExternalTrigInjectedConvEdgeConfig(ADC2, ADC_ExternalTrigInjecConvEdge_Falling);
ADC_InjectedSequencerLengthConfig(ADC1, 2);
ADC_InjectedSequencerLengthConfig(ADC2, 2);
hw_setup_adc_channels();
// Interrupt
ADC_ITConfig(ADC1, ADC_IT_JEOC, ENABLE);
nvicEnableVector(ADC_IRQn, 4);
// 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_CenterAligned2;
TIM_TimeBaseStructure.TIM_Period = SYSTEM_CORE_CLOCK / (int)m_conf->foc_f_sw;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_RepetitionCounter = 1;
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_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(TIM1->ARR - 2, 5);
utils_sys_unlock_cnt();
// Calibrate current offset
ENABLE_GATE();
DCCAL_OFF();
do_dc_cal();
// Various time measurements
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM12, ENABLE);
// Time base configuration
TIM_TimeBaseStructure.TIM_Period = 0xFFFFFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = (uint16_t)(((SYSTEM_CORE_CLOCK / 2) / 10000000) - 1);
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM12, &TIM_TimeBaseStructure);
TIM_Cmd(TIM12, ENABLE);
// Start threads
timer_thd_stop = false;
chThdCreateStatic(timer_thread_wa, sizeof(timer_thread_wa), NORMALPRIO, timer_thread, NULL);
// WWDG configuration
RCC_APB1PeriphClockCmd(RCC_APB1Periph_WWDG, ENABLE);
WWDG_SetPrescaler(WWDG_Prescaler_1);
WWDG_SetWindowValue(255);
WWDG_Enable(100);
}
void mcpwm_foc_deinit(void) {
WWDG_DeInit();
timer_thd_stop = true;
while (timer_thd_stop) {
chThdSleepMilliseconds(1);
}
TIM_DeInit(TIM1);
TIM_DeInit(TIM8);
TIM_DeInit(TIM12);
ADC_DeInit();
DMA_DeInit(DMA2_Stream4);
nvicDisableVector(ADC_IRQn);
dmaStreamRelease(STM32_DMA_STREAM(STM32_DMA_STREAM_ID(2, 4)));
}
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(top - 2, 5, 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.TIM12->CNT = 0;
*/
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;
}
utils_truncate_number(¤t, m_conf->lo_current_min, m_conf->lo_current_max);
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;
}
utils_truncate_number(¤t, m_conf->lo_current_min, m_conf->lo_current_max);
m_control_mode = CONTROL_MODE_CURRENT_BRAKE;
m_iq_set = current;
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;
}
/**
* 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 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 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.
*/
float mcpwm_foc_get_phase(void) {
float angle = m_motor_state.phase * (180.0 / M_PI);
utils_norm_angle(&angle);
return angle;
}
/**
* Read the phase that the observer has calculated.
*
* @return
* The phase angle in degrees.
*/
float mcpwm_foc_get_phase_observer(void) {
float angle = m_phase_now_observer * (180.0 / M_PI);
utils_norm_angle(&angle);
return angle;
}
/**
* Read the phase from based on the encoder.
*
* @return
* The phase angle in degrees.
*/
float mcpwm_foc_get_phase_encoder(void) {
float angle = m_phase_now_encoder * (180.0 / M_PI);
utils_norm_angle(&angle);
return angle;
}
float mcpwm_foc_get_vd(void) {
return m_motor_state.vd;
}
float mcpwm_foc_get_vq(void) {
return m_motor_state.vq;
}
/**
* Measure encoder offset and direction.
*
* @param current
* The locking open loop current for the motor.
*
* @param offset
* The detected offset.
*
* @param ratio
* The ratio between electrical and mechanical revolutions
*
* @param direction
* The detected direction.
*/
void mcpwm_foc_encoder_detect(float current, bool print, float *offset, float *ratio, bool *inverted) {
mc_interface_lock();
m_phase_override = true;
m_id_set = current;
m_iq_set = 0.0;
m_control_mode = CONTROL_MODE_CURRENT;
m_state = MC_STATE_RUNNING;
// Disable timeout
systime_t tout = timeout_get_timeout_msec();
float tout_c = timeout_get_brake_current();
timeout_configure(60000, 0.0);
// Save configuration
float offset_old = m_conf->foc_encoder_offset;
float inverted_old = m_conf->foc_encoder_inverted;
float ratio_old = m_conf->foc_encoder_ratio;
m_conf->foc_encoder_offset = 0.0;
m_conf->foc_encoder_inverted = false;
m_conf->foc_encoder_ratio = 1.0;
// Find index
int cnt = 0;
while(!encoder_index_found()) {
for (float i = 0.0;i < 2.0 * M_PI;i += (2.0 * M_PI) / 500.0) {
m_phase_now_override = i;
chThdSleepMilliseconds(1);
}
cnt++;
if (cnt > 30) {
// Give up
break;
}
}
if (print) {
commands_printf("Index found");
}
// Rotate
for (float i = 0.0;i < 2.0 * M_PI;i += (2.0 * M_PI) / 500.0) {
m_phase_now_override = i;
chThdSleepMilliseconds(1);
}
if (print) {
commands_printf("Rotated for sync");
}
// Inverted and ratio
chThdSleepMilliseconds(1000);
float s_sum = 0.0;
float c_sum = 0.0;
for (int i = 0; i < 10; i++) {
float phase_old = m_phase_now_encoder;
float phase_ovr_tmp = m_phase_now_override;
for (float i = phase_ovr_tmp; i < phase_ovr_tmp + 0.8 * M_PI;
i += (2.0 * M_PI) / 500.0) {
m_phase_now_override = i;
chThdSleepMilliseconds(2);
}
chThdSleepMilliseconds(1000);
float diff = utils_angle_difference(
m_phase_now_encoder * (180.0 / M_PI),
phase_old * (180.0 / M_PI));
float s, c;
sincosf(diff * M_PI / 180.0, &s, &c);
s_sum += s;
c_sum += c;
if (print) {
commands_printf("%.2f", (double)diff);
}
}
float diff = atan2f(s_sum, c_sum) * 180.0 / M_PI;
*inverted = diff < 0.0;
*ratio = roundf((0.8 * 180.0) /
fabsf(diff));
m_conf->foc_encoder_inverted = *inverted;
m_conf->foc_encoder_ratio = *ratio;
if (print) {
commands_printf("Inversion and ratio detected");
}
// Rotate
for (float i = m_phase_now_override;i < 2.0 * M_PI;i += (2.0 * M_PI) / 500.0) {
m_phase_now_override = i;
chThdSleepMilliseconds(2);
}
if (print) {
commands_printf("Rotated for sync");
commands_printf("Enc: %.2f", (double)encoder_read_deg());
}
s_sum = 0.0;
c_sum = 0.0;
for (int i = 0;i < 5;i++) {
m_phase_now_override = (float)i * M_PI / 5.0;
chThdSleepMilliseconds(1000);
float s, c;
sincosf(m_phase_now_encoder - m_phase_now_override, &s, &c);
s_sum += s;
c_sum += c;
if (print) {
commands_printf("%.2f", (double)((m_phase_now_encoder - m_phase_now_override) * 180.0 / M_PI));
}
}
for (int i = 3;i >= -1;i--) {
m_phase_now_override = (float)i * M_PI / 5.0;
chThdSleepMilliseconds(1000);
float s, c;
sincosf(m_phase_now_encoder - m_phase_now_override, &s, &c);
s_sum += s;
c_sum += c;
if (print) {
commands_printf("%.2f", (double)((m_phase_now_encoder - m_phase_now_override) * 180.0 / M_PI));
}
}
*offset = atan2f(s_sum, c_sum) * 180.0 / M_PI;
if (print) {
commands_printf("Avg: %.2f", (double)*offset);
}
utils_norm_angle(offset);
if (print) {
commands_printf("Offset detected");
}
m_id_set = 0.0;
m_iq_set = 0.0;
m_phase_override = false;
m_control_mode = CONTROL_MODE_NONE;
m_state = MC_STATE_OFF;
stop_pwm_hw();
// Restore configuration
m_conf->foc_encoder_inverted = inverted_old;
m_conf->foc_encoder_offset = offset_old;
m_conf->foc_encoder_ratio = ratio_old;
// Enable timeout
timeout_configure(tout, tout_c);
mc_interface_unlock();
}
/**
* Lock the motor with a current and sample the voiltage and current to
* calculate the motor resistance.
*
* @param current
* The locking current.
*
* @param samples
* The number of samples to take.
*
* @return
* The calculated motor resistance.
*/
float mcpwm_foc_measure_resistance(float current, int samples) {
mc_interface_lock();
m_phase_override = true;
m_phase_now_override = 0.0;