]> rtime.felk.cvut.cz Git - fpga/rpi-motor-control.git/blob - pmsm-control/test_sw/main_pmsm.c
Simplified multiplication in phase duty computation.
[fpga/rpi-motor-control.git] / pmsm-control / test_sw / main_pmsm.c
1 /**
2  * \file main_pmsm.c
3  * \author Martin Prudek
4  * \brief Mainfile pro pmsm control.
5  */
6
7 #ifndef NULL
8 #define NULL (void*) 0
9 #endif /*NULL*/
10
11
12 #include <stdlib.h>     /*exit*/
13 #include <signal.h>     /*signal handler Ctrl+C*/
14 #include <stdio.h>      /*printf*/
15 #include <sched.h>      /*sheduler*/
16 #include <unistd.h>     /*usleep*/
17 #include <pthread.h>    /*threads*/
18 #include <time.h>       /*nanosleep*/
19
20 #include "rpin.h"       /*gpclk*/
21 #include "rp_spi.h"     /*spi*/
22 #include "misc.h"       /*structure for priorities*/
23 #include "pxmc_sin_fixed.h"     /*to test sin commutation */
24
25
26
27 #define PRUM_PROUD      2061
28 #define PRUM_SOUC       6183
29 #define MAX_DUTY        128
30 #define PID_P           0.1
31
32 #define PRIOR_KERN      50
33 #define PRIOR_HIGH      49
34 #define PRIOR_LOW       20
35
36 #define THREAD_SHARED   0
37 #define INIT_VALUE      1       /*init value for semaphor*/
38
39
40 #define NSEC_PER_SEC    (1000000000) /* The number of nsecs per sec. */
41
42
43
44 struct rpi_in data;
45 struct rpi_state{
46         uint8_t test;
47         uint16_t pwm1, pwm2, pwm3;
48         uint16_t t_pwm1, t_pwm2, t_pwm3;
49         char commutate;
50         int duty;                       /* duty cycle of pwm */
51         uint16_t index_dist;            /* distance to index position */
52         unsigned char index_ok;
53         uint32_t tf_count;              /*number of transfer*/
54         int desired_pos;                /* desired position */
55 }rps;
56
57
58 /**
59  * \brief Initilizes GPCLK.
60  */
61 int clk_init()
62 {
63         initialise(); /*namapovani gpio*/
64         initClock(PLLD_500_MHZ, 10, 0);
65         gpioSetMode(4, FSEL_ALT0);
66         return 0;
67 }
68 /*
69  * \brief Terminates GPCLK.
70  */
71
72 inline void clk_disable(){
73         termClock(0);
74 }
75
76 /**
77  * \brief Signal handler pro Ctrl+C
78  */
79 void appl_stop(){
80         spi_disable();
81         clk_disable();
82         /*muzeme zavrit semafor*/
83         sem_destroy(&thd_par_sem);
84         printf("\nprogram bezpecne ukoncen\n");
85 }
86
87 void substractOffset(struct rpi_in* data, struct rpi_in* offset){
88         data->pozice_raw=data->pozice;
89         data->pozice-=offset->pozice;
90         return;
91 }
92 /*
93  * pocita procentualni odchylku od prumerneho proudu
94  */
95 float diff_p(float value){
96         return ((float)value-PRUM_PROUD)*100/PRUM_PROUD;
97 }
98 /*
99  * pocita procentualni odchylku od prumerneho souctu proudu
100  */
101 float diff_s(float value){
102         return ((float)value-PRUM_SOUC)*100/PRUM_SOUC;
103 }
104 /*
105  * tiskne potrebna data
106  */
107 void printData(){
108         struct rpi_in data_p;
109         struct rpi_state s;     /*state*/
110         float cur0, cur1, cur2;
111         int i;
112         /* copy the data */
113         sem_wait(&thd_par_sem);
114         data_p = data;
115         s=rps;
116         sem_post(&thd_par_sem);
117
118         if (data_p.adc_m_count){
119                 cur0=data_p.ch0/data_p.adc_m_count;
120                 cur1=data_p.ch1/data_p.adc_m_count;
121                 cur2=data_p.ch2/data_p.adc_m_count;
122         }
123         for (i = 0; i < 16; i++) {
124                         if (!(i % 6))
125                                 puts("");
126                         printf("%.2X ", data_p.debug_rx[i]);
127         }
128         puts("");
129         printf("\npozice=%d\n",(int32_t)data_p.pozice);
130         printf("chtena pozice=%d\n",s.desired_pos);
131         printf("transfer count=%u\n",s.tf_count);
132         printf("raw_pozice=%u\n",data_p.pozice_raw);
133         printf("raw_pozice last12=%u\n",(data_p.pozice_raw&0x0FFF));
134         printf("index position=%u\n",data_p.index_position);
135         printf("hal1=%d, hal2=%d, hal3=%d\n",data_p.hal1,data_p.hal2,data_p.hal3);
136         printf("en1=%d, en2=%d, en3=%d (Last sent)\n",!!(0x40&s.test),!!(0x20&s.test),!!(0x10&s.test));
137         printf("shdn1=%d, shdn2=%d, shdn3=%d (L.s.)\n",!!(0x08&s.test),!!(0x04&s.test),!!(0x02&s.test));
138         printf("PWM1=%u(L.s.)\n",s.pwm1);
139         printf("PWM2=%u(L.s.)\n",s.pwm2);
140         printf("PWM3=%u(L.s.)\n",s.pwm3);
141         printf("distance to index=%u\n",s.index_dist);
142         printf("T_PWM1=%u T_PWM2=%u T_PWM3=%u\n",s.t_pwm1,s.t_pwm2, s.t_pwm3);
143         printf("Pocet namerenych proudu=%u\n",data_p.adc_m_count);
144         printf("(pwm1) (ch1)=%d (avg=%4.0f) (%2.2f%%)\n",data_p.ch1,cur1,diff_p(cur1));
145         printf("(pwm2) (ch2)=%d (avg=%4.0f)(%2.2f%%)\n",data_p.ch2,cur2,diff_p(cur2));
146         printf("(pwm3) (ch0)=%d (avg=%4.0f)(%2.2f%%)\n",data_p.ch0,cur0,diff_p(cur0));
147         printf("soucet prumeru=%5.0f (%2.2f%%)\n",cur0+cur1+cur2,diff_s(cur0+cur1+cur2));
148         printf("duty=%d\n",s.duty);
149         if (s.index_ok) printf("index ok\n");
150         if (s.commutate) printf("commutation in progress\n");
151 }
152 void prepare_tx(uint8_t * tx){
153
154         /*Data format:
155          * tx[4] - bity 95 downto 88 - bits that are sent first
156          * tx[5] - bity 87 downto 80
157          * tx[6] - bity 79 downto 72
158          * tx[7] - bity 71 downto 64
159          * tx[8] - bity 63 downto 56
160          * tx[9] - bity 55 downto 48
161          * tx[10] - bity 47 downto 40
162          * tx[11] - bity 39 downto 32
163          * tx[12] - bity 31 downto 24
164          * tx[13] - bity 23 downto 16
165          * tx[14] - bity 15 downto 8
166          * tx[15] - bity 7 downto 0
167          *
168          * bit 95 - ADC reset
169          * bit 94 - enable PWM1
170          * bit 93 - enable PWM2
171          * bit 92 - enable PWM3
172          * bit 91 - shutdown1
173          * bit 90 - shutdown2
174          * bit 89 - shutdown3
175          *      .
176          *      .
177          *      Unused
178          *      .
179          *      .
180          * bits 47 .. 32 - match PWM1
181          * bits 31 .. 16 - match PWM2
182          * bits 15 .. 0  - match PWM3
183          */
184
185
186         uint16_t tmp;
187
188         /* keep the 11-bit cap*/
189
190         if (rps.pwm1>2047) rps.pwm1=2047;
191         if (rps.pwm2>2047) rps.pwm2=2047;
192         if (rps.pwm3>2047) rps.pwm3=2047;
193
194         tx[0]=rps.test; /*bit 94 - enable PWM1*/
195
196         /*now we have to switch the bytes due to endianess */
197         /* ARMv6 & ARMv7 instructions are little endian */
198         /*pwm1*/
199         tx[10]=((uint8_t*)&rps.pwm1)[1]; /*MSB*/
200         tx[11]=((uint8_t*)&rps.pwm1)[0]; /*LSB*/
201
202         /*pwm2*/
203         tx[12]=((uint8_t*)&rps.pwm2)[1]; /*MSB*/
204         tx[13]=((uint8_t*)&rps.pwm2)[0]; /*LSB*/
205
206         /*pwm3*/
207         tx[14]=((uint8_t*)&rps.pwm3)[1]; /*MSB*/
208         tx[15]=((uint8_t*)&rps.pwm3)[0]; /*LSB*/
209
210
211 }
212 /**
213  * Funkce pravidelne vypisuje posledni zjistenou pozici lokalniho motoru
214  */
215 void * pos_monitor(void* param){
216         while(1){
217                 printData();
218                 usleep(1000000);        /*1 Hz*/
219         }
220         return (void*)0;
221 }
222 /*
223  * \brief
224  * Multiplication of 11 bit
225  * Zaporne vysledky prvede na nulu.
226  */
227 inline uint16_t mult_cap(int32_t s,int d){
228         int j;
229         int res=0;
230         for(j=0;j!=11;j++){
231                 /* multiplicate as if maximum sinus value was unity */
232                 res+=(!(s & 0x10000000))*(((1 << j) & s)>>j)*(d>>(10-j));
233         }
234         return res;
235 }
236 inline
237 int sin_commutator(int duty){
238         #define DEGREE_60        715827883
239         #define DEGREE_120      1431655765
240         #define DEGREE_180      2147483648
241         #define DEGREE_240      2863311531
242         #define DEGREE_300      3579139413
243         uint32_t j,pos;
244         int32_t sin;
245         pos=rps.index_dist;
246         int32_t pwm;
247         /*aby prictene uhly mohla byt kulata cisla, musime index posunout*/
248         pos+=38;
249         /*use it as cyclic 32-bit logic*/
250         pos*=4294967;
251         if (duty>=0){   /*clockwise rotation*/
252                 /* 1st phase */
253                 sin = pxmc_sin_fixed_inline(pos+DEGREE_240,10); /*10+1 bity*/ /*-120*/
254                 pwm=sin*duty/1024;
255                 if (pwm<0) pwm=0;
256                 rps.pwm1=(uint16_t)pwm;
257
258                 /* 2nd phase */
259                 sin = pxmc_sin_fixed_inline(pos+DEGREE_120,10); /*10+1 bity*/ /*-240*/
260                 pwm=sin*duty/1024;
261                 if (pwm<0) pwm=0;
262                 rps.pwm2=(uint16_t)pwm;
263
264                 /* 3rd phase */
265                 sin = pxmc_sin_fixed_inline(pos,10); /*10+1 bity*/
266                 pwm=sin*duty/1024;
267                 if (pwm<0) pwm=0;
268                 rps.pwm3=(uint16_t)pwm;
269         }else{
270                 duty=-duty;
271
272                 /* 1st phase */
273                 sin = pxmc_sin_fixed_inline(pos+DEGREE_60,10); /*10+1 bity*/ /*-300*/
274                 pwm=sin*duty/1024;
275                 if (pwm<0) pwm=0;
276                 rps.pwm1=(uint16_t)pwm;
277
278                 /* 2nd phase */
279                 sin = pxmc_sin_fixed_inline(pos+DEGREE_300,10); /*10+1 bity*/ /*-60-*/
280                 pwm=sin*duty/1024;
281                 if (pwm<0) pwm=0;
282                 rps.pwm2=(uint16_t)pwm;
283
284                 /* 3rd phase */
285                 sin = pxmc_sin_fixed_inline(pos+DEGREE_180,10); /*10+1 bity*/ /*-180*/
286                 pwm=sin*duty/1024;
287                 if (pwm<0) pwm=0;
288                 rps.pwm3=(uint16_t)pwm;
289         }
290         return 0;
291 }
292 /*
293  * \brief
294  * Test function to be placed in controll loop.
295  * Switches PWM's at point where they produce same force.
296  * This points are found thanks to IRC position,
297  */
298 inline
299 void simple_ind_dist_commutator(int duty){
300         if (duty>=0){ /* clockwise - so that position increase */
301                 /* pwm3 */
302                 if ((rps.index_dist>=45 && rps.index_dist<=373) ||
303                 (rps.index_dist>=1048 && rps.index_dist<=1377)){
304                         rps.pwm1=0;
305                         rps.pwm2=0;
306                         rps.pwm3=duty;
307                         /* pwm1 */
308                 }else if ((rps.index_dist>=373 && rps.index_dist<=711) ||
309                 (rps.index_dist>=1377 && rps.index_dist<=1711)){
310                         rps.pwm1=duty;
311                         rps.pwm2=0;
312                         rps.pwm3=0;
313                         /* pwm2 */
314                 }else if ((rps.index_dist>=0 && rps.index_dist<=45) ||
315                 (rps.index_dist>=711 && rps.index_dist<=1048) ||
316                 (rps.index_dist>=1711 && rps.index_dist<=1999)){
317                         rps.pwm1=0;
318                         rps.pwm2=duty;
319                         rps.pwm3=0;
320                 }
321         }else{  /*counter-clockwise - position decrease */
322                 /* pwm3 */
323                 if ((rps.index_dist>=544 && rps.index_dist<=881) ||
324                 (rps.index_dist>=1544 && rps.index_dist<=1878)){
325                         rps.pwm1=0;
326                         rps.pwm2=0;
327                         rps.pwm3=-duty;
328                         /* pwm1 */
329                 }else if ((rps.index_dist>=0 && rps.index_dist<=211) ||
330                 (rps.index_dist>=881 && rps.index_dist<=1210) ||
331                 (rps.index_dist>=1878 && rps.index_dist<=1999)){
332                         rps.pwm1=-duty;
333                         rps.pwm2=0;
334                         rps.pwm3=0;
335                         /* pwm2 */
336                 }else if ((rps.index_dist>=211 && rps.index_dist<=544) ||
337                 (rps.index_dist>=1210 && rps.index_dist<=1544)){
338                         rps.pwm1=0;
339                         rps.pwm2=-duty;
340                         rps.pwm3=0;
341                 }
342         }
343 }
344 /*
345  * \brief
346  * Test function to be placed in controll loop.
347  * Switches PWM's at point where they produce same force
348  */
349 inline void simple_hall_commutator(int duty){
350         if (duty>=0){ /* clockwise - so that position increase */
351                 /* pwm3 */
352                 if (data.hal2 && !data.hal3){
353                         rps.pwm1=0;
354                         rps.pwm2=0;
355                         rps.pwm3=duty;
356                         /* pwm1 */
357                 }else if (data.hal1 && !data.hal2){
358                         rps.pwm1=duty;
359                         rps.pwm2=0;
360                         rps.pwm3=0;
361                         /* pwm2 */
362                 }else if (!data.hal1 && data.hal3){
363                         rps.pwm1=0;
364                         rps.pwm2=duty;
365                         rps.pwm3=0;
366                 }
367         }else{  /*counter-clockwise - position decrease */
368                 /* pwm3 */
369                 if (!data.hal2 && data.hal3){
370                         rps.pwm1=0;
371                         rps.pwm2=0;
372                         rps.pwm3=-duty;
373                         /* pwm1 */
374                 }else if (!data.hal1 && data.hal2){
375                         rps.pwm1=-duty;
376                         rps.pwm2=0;
377                         rps.pwm3=0;
378                         /* pwm2 */
379                 }else if (data.hal1 && !data.hal3){
380                         rps.pwm1=0;
381                         rps.pwm2=-duty;
382                         rps.pwm3=0;
383                 }
384         }
385 }
386 /**
387  * \brief
388  * Computation of distance to index.
389  *
390  * K dispozici je 12-bit index, to umoznuje ulozit 4096 ruznych bodu
391  * Je nutne vyjadrit 1999 bodu proti i posmeru h.r. od indexu -
392  *      to je 3999 bodu
393  *      =>12 bitu je dostacujicich, pokud nikdy nedojde ke ztrate
394  *              signalu indexu
395  */
396 void comIndDist(){
397         uint16_t pos = 0x0FFF & data.pozice_raw;
398         uint16_t dist;
399         uint16_t index = data.index_position;
400
401         if (index<1999){                /*index e<0,1998> */
402                 if (pos<index){                 /*pozice e<0,index-1> */
403                         /*proti smeru h.r. od indexu*/
404                         dist=pos+2000-index;
405                 }else if (pos<=index+1999){     /*pozice e<index,index+1999> */
406                         /*po smeru h.r. od indexu*/
407                         dist=pos-index;
408                 }else if (pos<index+2096){      /*pozice e<index+2000,index+2095> */
409                         goto index_lost;
410                 }else{                          /*pozice e<index+2096,4095> */
411                         /*proti smeru h.r. od indexu - podtecena pozice*/
412                         dist=pos-index-2096;
413                 }
414         }else if (index<=2096){         /*index e<1999,2096>*/
415                 if (pos<index-1999){            /*pozice e<0,index-2000> */
416                         goto index_lost;
417                 }else if (pos<index){           /*pozice e<index-1999,index-1> */
418                         /*proti smeru h.r. od indexu*/
419                         dist=pos+2000-index;
420                 }else if (pos<=index+1999){     /*pozice e<index,index+1999> */
421                         /*po smeru h.r. od indexu*/
422                         dist=pos-index;
423                 }else {                         /*pozice e<index+2000,4095> */
424                         goto index_lost;
425                 }
426         }else{                          /*index e<2097,4095> */
427                 if (pos<=index-2097){           /*pozice e<0,index-2097> */
428                         /*po smeru h.r. od indexu - pretecena pozice*/
429                         dist=4096+pos-index;
430                 }else if (pos<index-1999){      /*pozice e<index-2096,index-2000> */
431                         goto index_lost;
432                 }else if (pos<index){           /*pozice e<index-1999,index-1> */
433                         /*proti smeru h.r. od indexu*/
434                         dist=pos+2000-index;
435                 }else{                          /*pozice e<index,4095> */
436                         /*po smeru h.r. od indexu*/
437                         dist=pos-index;
438                 }
439         }
440
441         rps.index_dist = dist;
442         return;
443
444         index_lost:
445                 rps.index_ok=0;
446                 return;
447 }
448 /*
449  * \brief
450  * Very simple PID regulator.
451  * Now only with P-part so that the error doesnt go to zero.
452  * TODO: add anti-wind up and I and D parts
453  */
454 inline void pid(){
455         int duty_tmp;
456         duty_tmp = PID_P*(rps.desired_pos - (int32_t)data.pozice);
457         if (duty_tmp>MAX_DUTY){
458                 rps.duty=MAX_DUTY;
459         }else if (duty_tmp<-MAX_DUTY){
460                 rps.duty=-MAX_DUTY;
461         }else{
462                 rps.duty = duty_tmp;
463         }
464 }
465 /*
466  * \brief
467  * Feedback loop.
468  */
469 void * read_data(void* param){
470         int i;
471         struct rpi_in pocatek;
472         struct timespec t;
473         int interval = 1000000; /* 1ms ~ 1kHz*/
474         uint8_t tx[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} ;
475         char first=1;
476         uint16_t last_index;                            /*we have index up-to date*/
477         pocatek = spi_read(tx);
478         clock_gettime(CLOCK_MONOTONIC ,&t);
479         /* start after one second */
480         t.tv_sec++;
481                 while(1){
482                         /* wait until next shot */
483                         clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t, NULL);
484                         sem_wait(&thd_par_sem);         /*---take semaphore---*/
485                         prepare_tx(tx);                 /*save the data to send*/
486                         data = spi_read(tx);            /*exchange data*/
487                         /*subtract initiate postion */
488                         rps.tf_count++;
489                         substractOffset(&data,&pocatek);
490                         comIndDist();
491                         if (!rps.index_ok){
492                                 if (first){
493                                         last_index=data.index_position;
494                                         first=0;
495                                 }else if (last_index!=data.index_position){
496                                         rps.index_ok=1;
497                                 }
498                         }
499                         pid();
500                         if (rps.index_ok && rps.commutate){
501                                 /*simple_ind_dist_commutator(rps.duty);*/
502                                 sin_commutator(rps.duty);
503                         }else if(!rps.index_ok && rps.commutate){
504                                 simple_hall_commutator(rps.duty);
505                         }
506                         sem_post(&thd_par_sem);         /*--post semaphore---*/
507
508                         /* calculate next shot */
509                         t.tv_nsec += interval;
510
511                         while (t.tv_nsec >= NSEC_PER_SEC) {
512                                 t.tv_nsec -= NSEC_PER_SEC;
513                                 t.tv_sec++;
514                         }
515
516                 }
517 }
518
519
520 /**
521  * \brief
522  * Commands detection.
523  */
524 void poll_cmd(){
525         unsigned int tmp;
526         /*
527          * Note:
528          * pri pouziti scanf("%u",&simple_hall_duty); dochazelo
529          * k preukladani hodnot na promenne test. Dost divne.
530          */
531         while (1){
532                 scanf("%u",&tmp);
533                 printf("volba=%u\n",tmp);
534                 switch (tmp){
535                 case 1:
536                         scanf("%u",&tmp);
537                         sem_wait(&thd_par_sem);
538                         rps.pwm1=tmp&0xFFF;
539                         sem_post(&thd_par_sem);
540                         break;
541                 case 2:
542                         scanf("%u",&tmp);
543                         sem_wait(&thd_par_sem);
544                         rps.pwm2=tmp&0xFFF;
545                         sem_post(&thd_par_sem);
546                         break;
547                 case 3:
548                         scanf("%u",&tmp);
549                         sem_wait(&thd_par_sem);
550                         rps.pwm3=tmp&0xFFF;
551                         sem_post(&thd_par_sem);
552                         break;
553                 case 4:
554                         scanf("%u",&tmp);
555                         sem_wait(&thd_par_sem);
556                         rps.test=tmp&0xFF;
557                         sem_post(&thd_par_sem);
558                         break;
559                 case 5:
560                         sem_wait(&thd_par_sem);
561                         rps.commutate=!rps.commutate;
562                         /* switch off pwms at the end of commutation */
563                         rps.pwm1&=rps.commutate*0xFFFF;
564                         rps.pwm2&=rps.commutate*0xFFFF;
565                         rps.pwm3&=rps.commutate*0xFFFF;
566                         sem_post(&thd_par_sem);
567                         break;
568                 case 6:
569                         scanf("%d",&tmp);
570                         sem_wait(&thd_par_sem);
571                         rps.duty=tmp;
572                         sem_post(&thd_par_sem);
573                         break;
574                 case 7:
575                         scanf("%d",&tmp);
576                         sem_wait(&thd_par_sem);
577                         rps.desired_pos=tmp;
578                         sem_post(&thd_par_sem);
579                         break;
580
581                 default:
582                         break;
583                 }
584
585         }
586         return ;
587 }
588 /**
589  * \brief Main function.
590  */
591
592 int main(){
593         pthread_t base_thread_id;
594         clk_init();             /* inicializace gpio hodin */
595         spi_init();             /* iniicializace spi*/
596
597         /*semafor pro detekci zpracovani parametru vlaken*/
598         sem_init(&thd_par_sem,THREAD_SHARED,INIT_VALUE);
599         setup_environment();
600
601         base_thread_id=pthread_self();
602
603         /*main control loop*/
604         create_rt_task(&base_thread_id,PRIOR_HIGH,read_data,NULL);
605
606         /*monitor of current state*/
607         create_rt_task(&base_thread_id,PRIOR_LOW,pos_monitor,NULL);
608
609         /*wait for commands*/
610         poll_cmd();
611
612         return 0;
613 }