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