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