Usleep replaced by clock_nasosleep.
[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      0       /*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 struct sigaction sighnd; /*struktura pro signal handler*/
57 struct rpi_in data;
58 struct rpi_state{
59         uint8_t test;
60         uint16_t pwm1, pwm2, pwm3;
61         uint16_t t_pwm1, t_pwm2, t_pwm3;
62         char commutate;
63         int duty;                       /* duty cycle of pwm */
64         uint16_t index_dist;            /* distance to index position */
65         unsigned char index_ok;
66         uint32_t tf_count;              /*number of transfer*/
67         int desired_pos;                /* desired position */
68 }rps;
69
70
71 /**
72  * \brief Initilizes GPCLK.
73  */
74 int clk_init()
75 {
76         initialise(); /*namapovani gpio*/
77         initClock(PLLD_500_MHZ, 10, 0);
78         gpioSetMode(4, FSEL_ALT0);
79         return 0;
80 }
81 /*
82  * \brief Terminates GPCLK.
83  */
84
85 inline void clk_disable(){
86         termClock(0);
87 }
88
89 /**
90  * \brief Signal handler pro Ctrl+C
91  */
92 void sighnd_fnc(){
93         spi_disable();
94         clk_disable();
95         /*muzeme zavrit semafor*/
96         sem_destroy(&thd_par_sem);
97         printf("\nprogram bezpecne ukoncen\n");
98         exit(0);
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=%d\n",(int32_t)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         set_priority(param);            /*set priority*/
231         while(1){
232                 printData();
233                 usleep(1000000);        /*1 Hz*/
234         }
235         return (void*)0;
236 }
237
238 inline
239 int sin_commutator(int duty){
240         #define DEGREE_60        715827883
241         #define DEGREE_120      1431655765
242         #define DEGREE_180      2147483648
243         #define DEGREE_240      2863311531
244         #define DEGREE_300      3579139413
245         uint32_t j,pos;
246         int32_t sin;
247         uint16_t pwm;
248         pos=rps.index_dist*4294967;
249         if (duty>=0){   /*clockwise rotation*/
250                 /* 1st phase */
251                 sin = pxmc_sin_fixed_inline(pos+DEGREE_240,10); /*10+1 bity*/ /*-120*/
252                 pwm=0;
253                 for(j=0;j!=11;j++){
254                         /* multiplicate as if maximum sinus value was unity */
255                         pwm+=(!(sin & 0x10000000))*(((1 << j) & sin)>>j)*(duty>>(10-j));
256                 }
257                 rps.pwm1=pwm;
258
259                 /* 2nd phase */
260                 sin = pxmc_sin_fixed_inline(pos+DEGREE_120,10); /*10+1 bity*/ /*-240*/
261                 pwm=0;
262                 for(j=0;j!=11;j++){
263                         /* multiplicate as if maximum sinus value was unity */
264                         pwm+=(!(sin & 0x10000000))*(((1 << j) & sin)>>j)*(duty>>(10-j));
265                 }
266                 rps.pwm2=pwm;
267
268                 /* 3rd phase */
269                 sin = pxmc_sin_fixed_inline(pos,10); /*10+1 bity*/
270                 pwm=0;
271                 for(j=0;j!=11;j++){
272                         /* multiplicate as if maximum sinus value was unity */
273                         pwm+=(!(sin & 0x10000000))*(((1 << j) & sin)>>j)*(duty>>(10-j));
274                 }
275                 rps.pwm3=pwm;
276         }else{
277                 duty=-duty;
278
279                 /* 1st phase */
280                 sin = pxmc_sin_fixed_inline(pos+DEGREE_60,10); /*10+1 bity*/ /*-300*/
281                 pwm=0;
282                 for(j=0;j!=11;j++){
283                         /* multiplicate as if maximum sinus value was unity */
284                         pwm+=(!(sin & 0x10000000))*(((1 << j) & sin)>>j)*(duty>>(10-j));
285                 }
286                 rps.pwm1=pwm;
287
288                 /* 2nd phase */
289                 sin = pxmc_sin_fixed_inline(pos+DEGREE_300,10); /*10+1 bity*/ /*-60-*/
290                 pwm=0;
291                 for(j=0;j!=11;j++){
292                         /* multiplicate as if maximum sinus value was unity */
293                         pwm+=(!(sin & 0x10000000))*(((1 << j) & sin)>>j)*(duty>>(10-j));
294                 }
295                 rps.pwm2=pwm;
296
297                 /* 3rd phase */
298                 sin = pxmc_sin_fixed_inline(pos+DEGREE_180,10); /*10+1 bity*/ /*-180*/
299                 pwm=0;
300                 for(j=0;j!=11;j++){
301                         /* multiplicate as if maximum sinus value was unity */
302                         pwm+=(!(sin & 0x10000000))*(((1 << j) & sin)>>j)*(duty>>(10-j));
303                 }
304                 rps.pwm3=pwm;
305         }
306         return 0;
307 }
308 /*
309  * \brief
310  * Test function to be placed in controll loop.
311  * Switches PWM's at point where they produce same force.
312  * This points are found thanks to IRC position,
313  */
314 inline
315 void simple_ind_dist_commutator(int duty){
316         if (duty>=0){ /* clockwise - so that position increase */
317                 /* pwm3 */
318                 if ((rps.index_dist>=45 && rps.index_dist<=373) ||
319                 (rps.index_dist>=1048 && rps.index_dist<=1377)){
320                         rps.pwm1=0;
321                         rps.pwm2=0;
322                         rps.pwm3=duty;
323                         /* pwm1 */
324                 }else if ((rps.index_dist>=373 && rps.index_dist<=711) ||
325                 (rps.index_dist>=1377 && rps.index_dist<=1711)){
326                         rps.pwm1=duty;
327                         rps.pwm2=0;
328                         rps.pwm3=0;
329                         /* pwm2 */
330                 }else if ((rps.index_dist>=0 && rps.index_dist<=45) ||
331                 (rps.index_dist>=711 && rps.index_dist<=1048) ||
332                 (rps.index_dist>=1711 && rps.index_dist<=1999)){
333                         rps.pwm1=0;
334                         rps.pwm2=duty;
335                         rps.pwm3=0;
336                 }
337         }else{  /*counter-clockwise - position decrease */
338                 /* pwm3 */
339                 if ((rps.index_dist>=544 && rps.index_dist<=881) ||
340                 (rps.index_dist>=1544 && rps.index_dist<=1878)){
341                         rps.pwm1=0;
342                         rps.pwm2=0;
343                         rps.pwm3=-duty;
344                         /* pwm1 */
345                 }else if ((rps.index_dist>=0 && rps.index_dist<=211) ||
346                 (rps.index_dist>=881 && rps.index_dist<=1210) ||
347                 (rps.index_dist>=1878 && rps.index_dist<=1999)){
348                         rps.pwm1=-duty;
349                         rps.pwm2=0;
350                         rps.pwm3=0;
351                         /* pwm2 */
352                 }else if ((rps.index_dist>=211 && rps.index_dist<=544) ||
353                 (rps.index_dist>=1210 && rps.index_dist<=1544)){
354                         rps.pwm1=0;
355                         rps.pwm2=-duty;
356                         rps.pwm3=0;
357                 }
358         }
359 }
360 /*
361  * \brief
362  * Test function to be placed in controll loop.
363  * Switches PWM's at point where they produce same force
364  */
365 inline void simple_hall_commutator(int duty){
366         if (duty>=0){ /* clockwise - so that position increase */
367                 /* pwm3 */
368                 if (data.hal2 && !data.hal3){
369                         rps.pwm1=0;
370                         rps.pwm2=0;
371                         rps.pwm3=duty;
372                         /* pwm1 */
373                 }else if (data.hal1 && !data.hal2){
374                         rps.pwm1=duty;
375                         rps.pwm2=0;
376                         rps.pwm3=0;
377                         /* pwm2 */
378                 }else if (!data.hal1 && data.hal3){
379                         rps.pwm1=0;
380                         rps.pwm2=duty;
381                         rps.pwm3=0;
382                 }
383         }else{  /*counter-clockwise - position decrease */
384                 /* pwm3 */
385                 if (!data.hal2 && data.hal3){
386                         rps.pwm1=0;
387                         rps.pwm2=0;
388                         rps.pwm3=-duty;
389                         /* pwm1 */
390                 }else if (!data.hal1 && data.hal2){
391                         rps.pwm1=-duty;
392                         rps.pwm2=0;
393                         rps.pwm3=0;
394                         /* pwm2 */
395                 }else if (data.hal1 && !data.hal3){
396                         rps.pwm1=0;
397                         rps.pwm2=-duty;
398                         rps.pwm3=0;
399                 }
400         }
401 }
402 /**
403  * Funkce pravidelne vycita data z motoru
404  */
405 inline void comIndDist(){
406         rps.index_dist=0x0FFF & (data.pozice_raw - data.index_position);
407         /*
408          * if distance is bigger than 2047, the distance underflown
409          * -> if 12th bit is set, substract 2096
410          */
411         rps.index_dist-=((rps.index_dist & 0x0800)>>11)*2096;
412 }
413 /*
414  * \brief
415  * Very simple PID regulator.
416  * Now only with P-part so that the error doesnt go to zero.
417  * TODO: add anti-wind up and I and D parts
418  */
419 inline void pid(){
420         int duty_tmp;
421         duty_tmp = PID_P*(rps.desired_pos - (int32_t)data.pozice);
422         if (duty_tmp>MAX_DUTY){
423                 rps.duty=MAX_DUTY;
424         }else if (duty_tmp<-MAX_DUTY){
425                 rps.duty=-MAX_DUTY;
426         }else{
427                 rps.duty = duty_tmp;
428         }
429 }
430 /*
431  * \brief
432  * Feedback loop.
433  */
434 void * read_data(void* param){
435         int i;
436         struct rpi_in pocatek;
437         struct timespec t;
438         int interval = 1000000; /* 1ms ~ 1kHz*/
439         uint8_t tx[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} ;
440         char first=1;
441         uint16_t last_index;                            /*we have index up-to date*/
442         set_priority(param);                            /*set priority*/
443         pocatek = spi_read(tx);
444         clock_gettime(CLOCK_MONOTONIC ,&t);
445         /* start after one second */
446         t.tv_sec++;
447                 while(1){
448                         /* wait until next shot */
449                         clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t, NULL);
450                         sem_wait(&thd_par_sem);         /*---take semaphore---*/
451                         prepare_tx(tx);                 /*save the data to send*/
452                         data = spi_read(tx);            /*exchange data*/
453                         /*subtract initiate postion */
454                         rps.tf_count++;
455                         substractOffset(&data,&pocatek);
456                         comIndDist();
457                         if (!rps.index_ok){
458                                 if (first){
459                                         last_index=data.index_position;
460                                         first=0;
461                                 }else if (last_index!=data.index_position){
462                                         rps.index_ok=1;
463                                 }
464                         }
465                         pid();
466                         if (rps.index_ok && rps.commutate){
467                                 /*simple_ind_dist_commutator(rps.duty);*/
468                                 sin_commutator(rps.duty);
469                         }else if(!rps.index_ok && rps.commutate){
470                                 simple_hall_commutator(rps.duty);
471                         }
472                         sem_post(&thd_par_sem);         /*--post semaphore---*/
473
474                         /* calculate next shot */
475                         t.tv_nsec += interval;
476
477                         while (t.tv_nsec >= NSEC_PER_SEC) {
478                                 t.tv_nsec -= NSEC_PER_SEC;
479                                 t.tv_sec++;
480                         }
481
482                 }
483 }
484
485 /**
486  * \brief Main function.
487  */
488
489 int main(){
490         unsigned int tmp;
491
492         /*nastaveni priorit vlaken*/
493         struct thread_param tsp;
494         tsp.sch_policy = SCHED_FIFO;
495
496         /*nastaveni signalu pro vypnuti pomoci Ctrl+C*/
497         sighnd.sa_handler=&sighnd_fnc;
498         sigaction(SIGINT, &sighnd, NULL );
499
500         clk_init();             /* inicializace gpio hodin */
501         spi_init();             /* iniicializace spi*/
502
503         /*semafor pro detekci zpracovani parametru vlaken*/
504         sem_init(&thd_par_sem,THREAD_SHARED,INIT_VALUE);
505
506         /*vlakna*/
507         pthread_t tid;                  /*identifikator vlakna*/
508         pthread_attr_t attr;            /*atributy vlakna*/
509         pthread_attr_init(&attr);       /*inicializuj implicitni atributy*/
510
511
512
513         /*ziskavani dat z motoru*//*vysoka priorita*/
514         tsp.sch_prior = PRIOR_HIGH;
515         pthread_create(&tid, &attr, read_data, (void*)&tsp);
516
517         /*vypisovani lokalni pozice*//*nizka priorita*/
518         tsp.sch_prior = PRIOR_LOW;
519         sem_wait(&thd_par_sem);
520         pthread_create(&tid, &attr, pos_monitor, (void*)&tsp);
521
522
523
524         /*
525          * Note:
526          * pri pouziti scanf("%u",&simple_hall_duty); dochazelo
527          * k preukladani hodnot na promenne test. Dost divne.
528          */
529         while (1){
530                 scanf("%u",&tmp);
531                 printf("volba=%u\n",tmp);
532                 switch (tmp){
533                 case 1:
534                         scanf("%u",&tmp);
535                         sem_wait(&thd_par_sem);
536                         rps.pwm1=tmp&0xFFF;
537                         sem_post(&thd_par_sem);
538                         break;
539                 case 2:
540                         scanf("%u",&tmp);
541                         sem_wait(&thd_par_sem);
542                         rps.pwm2=tmp&0xFFF;
543                         sem_post(&thd_par_sem);
544                         break;
545                 case 3:
546                         scanf("%u",&tmp);
547                         sem_wait(&thd_par_sem);
548                         rps.pwm3=tmp&0xFFF;
549                         sem_post(&thd_par_sem);
550                         break;
551                 case 4:
552                         scanf("%u",&tmp);
553                         sem_wait(&thd_par_sem);
554                         rps.test=tmp&0xFF;
555                         sem_post(&thd_par_sem);
556                         break;
557                 case 5:
558                         sem_wait(&thd_par_sem);
559                         rps.commutate=!rps.commutate;
560                         /* switch off pwms at the end of commutation */
561                         rps.pwm1&=rps.commutate*0xFFFF;
562                         rps.pwm2&=rps.commutate*0xFFFF;
563                         rps.pwm3&=rps.commutate*0xFFFF;
564                         sem_post(&thd_par_sem);
565                         break;
566                 case 6:
567                         scanf("%d",&tmp);
568                         sem_wait(&thd_par_sem);
569                         rps.duty=tmp;
570                         sem_post(&thd_par_sem);
571                         break;
572                 case 7:
573                         scanf("%d",&tmp);
574                         sem_wait(&thd_par_sem);
575                         rps.desired_pos=tmp;
576                         sem_post(&thd_par_sem);
577                         break;
578
579                 default:
580                         break;
581                 }
582
583         }
584         return 0;
585 }
586