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