달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2016. 2. 8. 02:58

PID 테스트 시작 작품/쿼드콥터2016. 2. 8. 02:58

PID테스트하기 위한 개발환경 구축

PID테스트를 시작하기 시작하였다. 

우선 쿼드콥터를 제어하기위해 개발환경을 나름 최적으로 만들어야 했다.

우선 이때까지 아두이노 IDE를 쓰다가 그 불편함 때문에 visual studio에서 아두이노로 바로 업로드 할 수 있게 하였다.

그 프로그램은 visualmicro라고 하는 것인데 이것을 통해서 visual studio의 장점을 활용하면서 arduino의 코드를 디버깅 할 수 있게 되었다.


다음으로 PID제어를 할 수 있도록 드론을 지지대에 묶었고 긴 USB케이블로 노트북과 연결하여 시리얼 모니터 창으로 값들을 디버깅 할 수 있도록 하였다.

물론 조종은 무선 조종기로 throttle과 roll, pitch를 조종하도록 하였다.

yaw값은 일단은 조종에서 빼고 처음에 향하는 방향을 초깃값으로 설정하도록 하였다.




그리고 드론이 잘 못된 제어로 갑자기 확 쎄지거나 회전해서 선이 꼬여버리면 큰일 이기 때문에 그것을 방지 할 수 있게 안전 수단을 만들었다.

첫 번째로는 Throttle이 제일 아래로 되어 있으면 PID제어에 관계없이 모터의 모든 값을 0으로 되게 하였다.

두 번째로는 yaw키는 일단은 쓰지 않기 때문에 yaw 조종값이 제일 크게 올라가면 모든 모터 값이 0이 되도록 하였다.

이렇게 함으로써 소프트웨어적으로 긴급상황에 대처할 수 있게 하였다.

세 번째로는 배터리와 드론사이에 길게 선을 빼서 스위치를 달았다.

그래서 이 스위치를 켜면 드론에 전원이 공급되고 스위치를 끄면 배터리를 뗀것 같은 효과를 주어서 하드웨어적으로 긴급상황에 대처할 수 있도록 하였다.




PID테스트 

다음 코드를 이용하여 PID테스트를 해보았다.

나름 균형을 잡고 있는 것 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
#include "Servo.h"
 
/////////////////BLDC Motor/////////////////
#define MAX_THROTTLE 180
#define MIN_THROTTLE 0
#define MAX_PWM 150
#define MIN_PWM 0
#define MOTOR1  //motor pin number
#define MOTOR2  //motor pin number
#define MOTOR3 44  //motor pin number
#define MOTOR4 45  //motor pin number
 
int motor1Power, motor3Power; // Motors on the X axis
//=>; changing their speeds will affect the pitch
int motor2Power, motor4Power; // Motors on the Y axis
//=>; changing their speeds will affect the roll
 
Servo motor1;
Servo motor2;
Servo motor3;
Servo motor4;
////////////////////////////////////////////
 
 
/////////////////IMU Sensor/////////////////
 typedef union {
    signed short value;
    unsigned char byte[2];
} S2BYTE;
 
S2BYTE data_word;
 
unsigned char SBuf[100];
int SCnt = 0;
double  DegRoll, DegPitch, DegYaw;
////////////////////////////////////////////
 
 
/////////////////PID Conrtroll/////////////////
#define MINhover 0
#define INIThover  20
 
#define INITROLLKp 0.48//0.19//0.29
#define INITROLLKi 0.000850//0.000850//0.000287 
#define INITROLLKd 33
 
#define INITPITCHKp 0.29
#define INITPITCHKi 0.000287 
#define INITPITCHKd 33
 
#define INITYAWKp 0.29  
#define INITYAWKi 0.000287 
#define INITYAWKd 33
 
#define MAXSPEED  3
#define MINSPEED  100
 
#define INITROLLSETPOINT -0.60
#define INITPITCHSETPOINT -0.67
 
 
double roll_setpoint = INITROLLSETPOINT, pitch_setpoint = INITPITCHSETPOINT, yaw_setpoint = 0;
int hover = INIThover;
double roll_Kp = INITROLLKp, roll_Ki = INITROLLKi, roll_Kd = INITROLLKd;
double pitch_Kp = INITPITCHKp, pitch_Ki = INITPITCHKi, pitch_Kd = INITPITCHKd;
double yaw_Kp = INITYAWKp, yaw_Ki = INITYAWKi, yaw_Kd = INITYAWKd;
double roll_p, roll_i, roll_d, roll_val;
double pitch_p, pitch_i, pitch_d, pitch_val;
double yaw_p, yaw_i, yaw_d, yaw_val;
int rollControll, pitchControll, yawControll;
 
int initial = 0;
////////////////////////////////////////////
 
/////////////////Serial Monitor/////////////////
int Serial_print_sig = 1;
int roll_print = 1, pitch_print = 0, yaw_print = 0, hover_print = 0;
////////////////////////////////////////////
 
////////////////Wireless Controller///////////////////
#define CH1 // yaw
#define CH2 //pitch
#define CH3 //hover
#define CH4 //roll
 
#define CH1_MIN 1292//200 1264
#define CH1_MID 1464
#define CH1_MAX 1632//168
 
#define CH2_MIN 1224//304 1176
#define CH2_MID 1480
#define CH2_MAX 1736//256
 
#define CH3_MIN 1028
#define CH3_MID 1448
#define CH3_MAX 1808
 
#define CH4_MIN 1296//208 1264
#define CH4_MID 1472
#define CH4_MAX 1648//176
 
#define CUTFORZERO 3
#define DEGRANGE  45
#define TROTTLERANGE  150
#define WFLYOFFSET 18
#define CHENELNUM 4
#define CHECKINGNUM 4
 
volatile int  CH1_prev_time, CH1_pwm_value;
volatile int  CH2_prev_time, CH2_pwm_value;
volatile int  CH3_prev_time, CH3_pwm_value;
volatile int  CH4_prev_time, CH4_pwm_value;
int CH1_val = 0, CH2_val = 0, CH3_val = 0, CH4_val = 0;
int controll_val[CHENELNUM];
int* ptr;
/////////////////////////////////////////////////////////////////////
 
//---------------------------------------------------------------------//
//
//                              funtions
//
//--------------------------------------------------------------------//
 
//----------------------------------------------------------------//
//                      BLDC Motor
//---------------------------------------------------------------//
//esc占쏙옙占쏙옙 占싹깍옙
void callibration(void)
{
 
    Serial.println("Calibrate ESC? 'y' or 'n'.");
 
    while (!Serial.available());
    char cali = Serial.read();
    if (cali == 'y'){
        Serial.println("send max throttle");
 
        motor1.attach(MOTOR1);
        motor2.attach(MOTOR2);
        motor3.attach(MOTOR3);
        motor4.attach(MOTOR4);
        motor1.write(MAX_THROTTLE);
        motor2.write(MAX_THROTTLE);
        motor3.write(MAX_THROTTLE);
        motor4.write(MAX_THROTTLE);
 
        delay(5000);
 
        Serial.println("send min throttle");
        motor1.attach(MOTOR1);
        motor2.attach(MOTOR2);
        motor3.attach(MOTOR3);
        motor4.attach(MOTOR4);
        motor1.write(MIN_THROTTLE);
        motor2.write(MIN_THROTTLE);
        motor3.write(MIN_THROTTLE);
        motor4.write(MIN_THROTTLE);
 
        delay(2000);
 
        Serial.println("callibration complete");
 
    }
    else if (cali == 'n'){
        motor1.attach(MOTOR1);
        motor2.attach(MOTOR2);
        motor3.attach(MOTOR3);
        motor4.attach(MOTOR4);
        motor1.write(MIN_THROTTLE);
        motor2.write(MIN_THROTTLE);
        motor3.write(MIN_THROTTLE);
        motor4.write(MIN_THROTTLE);
 
    }
    Serial.println("If you want Program keep going. Press any key.");
    while (!Serial.available());
}
int motorBegin(void)
{
    int count = 0, throttle;
 
 
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
 
    delay(2000);
 
    while (count <5){
        vlaueable_wfly(&controll_val[0]);
        throttle = controll_val[2];
        count++;
    }
 
    do{
        vlaueable_wfly(&controll_val[0]);
        throttle = controll_val[2];
 
 
 
        if (throttle < 10){//no callibration
 
            Serial.println("no callibration.");
 
            motor1.write(MIN_THROTTLE);
            motor2.write(MIN_THROTTLE);
            motor3.write(MIN_THROTTLE);
            motor4.write(MIN_THROTTLE);
 
            delay(2000);
 
            Serial.println("program start!");
 
            delay(2000);
 
            return 0;
 
        }
        else if (throttle > 140){//yes callibration
            Serial.print("you send MAX_THROTTLE.   "); Serial.print("callibration begin.    "); Serial.println("wait 4 seconds");
 
            motor1.write(MAX_THROTTLE);
            motor2.write(MAX_THROTTLE);
            motor3.write(MAX_THROTTLE);
            motor4.write(MAX_THROTTLE);
 
            delay(4000);
 
            Serial.println("send min throttle for caliibraion.");
 
            while (throttle > 10){//wait until MIN_THROTTLE 
                vlaueable_wfly(&controll_val[0]);
                throttle = controll_val[2];
            }
 
            Serial.print("you send MIN_THROTTLE.    ");
 
            motor1.write(MIN_THROTTLE);
            motor2.write(MIN_THROTTLE);
            motor3.write(MIN_THROTTLE);
            motor4.write(MIN_THROTTLE);
 
            Serial.print("calibration complete.     ");
            Serial.println("program start!");
 
            delay(2000);
 
            return 1;
        }
    } while (1);
}
//占쏙옙占쏘값占쏙옙 占쌨어서 占쏙옙占쏙옙 占쏙옙占쏙옙
void run_motors(int throttle, int rollOffset, int pitchOffset, int yawOffset)
{
    //emergency
    if (controll_val[0> 30 || throttle < 5){
        throttle = 0;
        rollOffset = 0;
        pitchOffset= 0;
        yawOffset = 0;
    }
 
    //Roll control
    motor1Power = throttle + rollOffset / 2;
    motor2Power = throttle + rollOffset / 2;
    motor4Power = throttle - rollOffset / 2;
    motor3Power = throttle - rollOffset / 2;
 
    //Pitch control
    motor4Power = motor4Power + pitchOffset / 2;
    motor1Power = motor1Power + pitchOffset / 2;
    motor3Power = motor3Power - pitchOffset / 2;
    motor2Power = motor2Power - pitchOffset / 2;
 
    /* //yaw control
    motor1Power = motor1Power - yawOffset;
    motor3Power = motor3Power - yawOffset;
    motor2Power = motor2Power + yawOffset;
    motor4Power = motor4Power + yawOffset;
    */
 
    limit_max_min(&motor1Power);
    limit_max_min(&motor2Power);
    limit_max_min(&motor3Power);
    limit_max_min(&motor4Power);
 
    motor1.write(motor1Power); motor3.write(motor3Power);
    motor2.write(motor2Power); motor4.write(motor4Power);
 
    /*
    Serial.print(motor1Power); Serial.print(", ");
    Serial.print(motor2Power); Serial.print(", ");
    Serial.print(motor3Power); Serial.print(", ");
    Serial.print(motor4Power); Serial.println(" ");
    */
}
 
void limit_max_min(int* pwm)//modify
{
    if (*pwm>MAX_PWM)
        *pwm = MAX_PWM;
    else if (*pwm<MIN_PWM)
        *pwm = MIN_PWM;
}
//---------------------------------------------------------//
//                     IMU Sensor
//--------------------------------------------------------//
//占쏙옙占쏙옙占쏙옙占쏙옙 占싻어서 roll,pitch,yaw 占쏙옙占쏙옙 占싯아놂옙占쏙옙.
int recieve_data(void)
{
    static int step_ = 0, check_all_recieve = 0;
    unsigned char data1byte;
    int n;
 
    data1byte = Serial1.read();
 
    switch (step_)
    {
    case 0:
        if (data1byte == 0x55) { step_ = 1, check_all_recieve = 0; }
        break;
 
    case 1:
        if (data1byte == 0x55) { step_ = 2;  SCnt = 0; }
        else step_ = 0;
        break;
 
    case 2:
        SBuf[SCnt++= (unsigned char)data1byte;
        if (SCnt == 8)  // roll(2byte),pitch(2byte),yaw(2byte),checksum(2byte) 
        {
            step_ = 0;
            SCnt = 0;
            check_all_recieve = 1;
        }
        break;
 
    default:
        break;
    }
 
    return check_all_recieve;
}
 
static int trans_data_to_degree(unsigned char *sdata)  // sdata : roll(2)+pitch(2)+yaw(2)+chk(2)
{
    int n;
    unsigned short chk = 0;
 
    ///////////// checksum /////////////////
    chk = 0x55 + 0x55;
    for (n = 0; n<6; n++) chk += sdata[n];
    if (chk != get_data_word(&sdata[6]))
    {
        Serial.print("checksum error!");
        return 0//   
    }
    ////////////////////////////////////////
 
    DegRoll = get_data_word(&sdata[0]) / 100.;
    DegPitch = get_data_word(&sdata[2]) / 100. * -1;
    DegYaw = get_data_word(&sdata[4]) / 100.;
 
    return 1;
}
 
static signed short get_data_word(unsigned char *dat)
{
    // little endian..
    data_word.byte[0= dat[1];
    data_word.byte[1= dat[0];
 
    return data_word.value;
}
 
//-----------------------------------------------------------//
//                     PID Conrtroll
//----------------------------------------------------------//
//占쏙옙占쏙옙 占쏙옙占쏙옙 占쌨아쇽옙 PID占쏙옙占쏘값 占쏙옙占?double roll_pid(double setpoint, double degree)
{
    double val_out;
    static double roll_p_err_prv, roll_p_err, roll_i_err, roll_d_err;
 
    roll_p_err = setpoint - degree;
    roll_i_err += roll_p_err;
    roll_d_err = roll_p_err - roll_p_err_prv;
 
    roll_p_err_prv = roll_p_err;
    val_out = (roll_Kp*roll_p_err) + (roll_Ki*roll_i_err) + (roll_Kd*roll_d_err);
 
    roll_p = roll_Kp*roll_p_err;
    roll_i = roll_Ki*roll_i_err;
    roll_d = roll_Kd*roll_d_err;
    roll_val = val_out;
 
    return val_out;
}
 
double pitch_pid(double setpoint, double degree)
{
    double val_out;
    static double pitch_p_err_prv, pitch_p_err, pitch_i_err, pitch_d_err;
 
    pitch_p_err = setpoint - degree;
    pitch_i_err += pitch_p_err;
    pitch_d_err = pitch_p_err - pitch_p_err_prv;
 
    pitch_p_err_prv = pitch_p_err;
    val_out = (pitch_Kp*pitch_p_err) + (pitch_Ki*pitch_i_err) + (pitch_Kd*pitch_d_err);
 
    pitch_p = pitch_Kp*pitch_p_err;
    pitch_i = pitch_Ki*pitch_i_err;
    pitch_d = pitch_Kd*pitch_d_err;
    pitch_val = val_out;
 
    return val_out;
}
 
double yaw_pid(double setpoint, double degree)
{
    double val_out;
    static double yaw_p_err_prv, yaw_p_err, yaw_i_err, yaw_d_err;
 
    yaw_p_err = setpoint - degree;
    yaw_i_err += yaw_p_err;
    yaw_d_err = yaw_p_err - yaw_p_err_prv;
 
    yaw_p_err_prv = yaw_p_err;
    val_out = (yaw_Kp*yaw_p_err) + (yaw_Ki*yaw_i_err) + (yaw_Kd*yaw_d_err);
 
    yaw_p = yaw_Kp*yaw_p_err;
    yaw_i = yaw_Ki*yaw_i_err;
    yaw_d = yaw_Kd*yaw_d_err;
    yaw_val = val_out;
 
    return val_out;
}
 
//---------------------------------------------------------//
//                      Serial Monitor
//----------------------------------------------------------//
void from_computer(void)
{
    char c = Serial.read();
 
    //roll debuging
    if (c == 'q'){
        roll_Kp += 0.01;
        Serial.print("roll_Kp = "); Serial.println(roll_Kp);
    }
    else if (c == 'w'){
        roll_Kp -= 0.01;
        Serial.print("roll_Kp = "); Serial.println(roll_Kp);
    }
    else if (c == 'e'){
        roll_Kp = INITROLLKp;
        Serial.print("roll_Kp = "); Serial.println(roll_Kp);
    }
    else if (c == 'a'){
        roll_Ki += 0.000001;
        Serial.print("roll_Ki = "); Serial.println(roll_Ki * 10000);
    }
    else if (c == 's'){
        roll_Ki -= 0.000001;
        Serial.print("roll_Ki = "); Serial.println(roll_Ki * 10000);
    }
    else if (c == 'd'){
        roll_Ki = INITROLLKi;
        Serial.print("roll_Ki = "); Serial.println(roll_Ki * 10000);
    }
    else if (c == 'z'){
        roll_Kd += 1;
        Serial.print("roll_Kd = "); Serial.println(roll_Kd);
    }
    else if (c == 'x'){
        roll_Kd -= 1;
        Serial.print("roll_Kd = "); Serial.println(roll_Kd);
    }
    else if (c == 'c'){
        roll_Kd = INITROLLKd;
        Serial.print("roll_Kd = "); Serial.println(roll_Kd);
    }
 
 
 
    //pitch debuging
    else if (c == 'r'){
        pitch_Kp += 0.01;
        Serial.print("pitch_Kp = "); Serial.println(pitch_Kp);
    }
    else if (c == 't'){
        pitch_Kp -= 0.01;
        Serial.print("pitch_Kp = "); Serial.println(pitch_Kp);
    }
    else if (c == 'y'){
        pitch_Kp = INITPITCHKp;
        Serial.print("pitch_Kp = "); Serial.println(pitch_Kp);
    }
    else if (c == 'f'){
        pitch_Ki += 0.000001;
        Serial.print("pitch_Ki = "); Serial.println(pitch_Ki * 10000);
    }
    else if (c == 'g'){
        pitch_Ki -= 0.000001;
        Serial.print("pitch_Ki = "); Serial.println(pitch_Ki * 10000);
    }
    else if (c == 'h'){
        pitch_Ki = INITPITCHKi;
        Serial.print("pitch_Ki = "); Serial.println(pitch_Ki * 10000);
    }
    else if (c == 'v'){
        pitch_Kd += 1;
        Serial.print("pitch_Kd = "); Serial.println(pitch_Kd);
    }
    else if (c == 'b'){
        pitch_Kd -= 1;
        Serial.print("pitch_Kd = "); Serial.println(pitch_Kd);
    }
    else if (c == 'n'){
        pitch_Kd = INITPITCHKd;
        Serial.print("pitch_Kd = "); Serial.println(pitch_Kd);
    }
 
    //yaw debuging
    else if (c == 'u'){
        yaw_Kp += 0.01;
        Serial.print("yaw_Kp = "); Serial.println(yaw_Kp);
    }
    else if (c == 'i'){
        yaw_Kp -= 0.01;
        Serial.print("yaw_Kp = "); Serial.println(yaw_Kp);
    }
    else if (c == 'o'){
        yaw_Kp = INITYAWKp;
        Serial.print("yaw_Kp = "); Serial.println(yaw_Kp);
    }
    else if (c == 'j'){
        yaw_Ki += 0.000001;
        Serial.print("yaw_Ki = "); Serial.println(yaw_Ki * 10000);
    }
    else if (c == 'k'){
        yaw_Ki -= 0.000001;
        Serial.print("yaw_Ki = "); Serial.println(yaw_Ki * 10000);
    }
    else if (c == 'l'){
        yaw_Ki = INITYAWKi;
        Serial.print("yaw_Ki = "); Serial.println(yaw_Ki * 10000);
    }
    else if (c == 'm'){
        yaw_Kd += 1;
        Serial.print("yaw_Kd = "); Serial.println(yaw_Kd);
    }
    else if (c == ','){
        yaw_Kd -= 1;
        Serial.print("yaw_Kd = "); Serial.println(yaw_Kd);
    }
    else if (c == '.'){
        yaw_Kd = INITYAWKd;
        Serial.print("yaw_Kd = "); Serial.println(yaw_Kd);
    }
 
    else if (c == 'p'){
        Serial_print_sig = !(Serial_print_sig);
    }
    else if (c == '/'){
        roll_print = !(roll_print);
    }
    else if (c == '*'){
        pitch_print = !(pitch_print);
    }
    else if (c == '-'){
        yaw_print = !(yaw_print);
    }
    else if (c == '+'){
        hover_print = !(hover_print);
    }
 
}
 
 
void Serial_Monitor(void)
{
    if (Serial_print_sig == 1){
        if (roll_print == 1){
            Serial.print("Roll=> "); Serial.print(DegRoll); Serial.print(", "); Serial.print(roll_p); Serial.print(", "); Serial.print(roll_i); Serial.print(", "); Serial.print(roll_d); Serial.print(", "); Serial.print(roll_val); Serial.print(", "); Serial.print(motor2Power); Serial.print(", "); Serial.println(motor4Power);
        }
        else if (pitch_print == 1){
            Serial.print("Pitch=> "); Serial.print(DegPitch); Serial.print(", "); Serial.print(pitch_p); Serial.print(", "); Serial.print(pitch_i); Serial.print(", "); Serial.print(pitch_d); Serial.print(", "); Serial.print(pitch_val); Serial.print(", "); Serial.print(motor1Power); Serial.print(", "); Serial.println(motor3Power);
        }
        else if (yaw_print == 1){
            Serial.print("Yaw=> "); Serial.print(DegYaw); Serial.print(", "); Serial.print(yaw_p); Serial.print(", "); Serial.print(yaw_i); Serial.print(", "); Serial.print(yaw_d); Serial.print(", "); Serial.println(yaw_val);
        }
    }
 
    if (Serial_print_sig == 0){
        if (hover_print == 1){
            Serial.print("hover = "); Serial.println(hover);
            hover_print = 0;
        }
        else if (roll_print == 1){
            Serial.print("roll_Kp = "); Serial.print(roll_Kp); Serial.print(", roll_Ki = "); Serial.print(roll_Ki * 10000); Serial.print(", roll_Kd = "); Serial.println(roll_Kd);
            roll_print = 0;
        }
        else if (pitch_print == 1){
            Serial.print("pitch_Kp = "); Serial.print(pitch_Kp); Serial.print(", pitch_Ki = "); Serial.print(pitch_Ki * 10000); Serial.print(", pitch_Kd = "); Serial.println(pitch_Kd);
            pitch_print = 0;
        }
        else if (yaw_print == 1){
            Serial.print("yaw_Kp = "); Serial.print(yaw_Kp); Serial.print(", yaw_Ki = "); Serial.print(yaw_Ki * 10000); Serial.print(", yaw_Kd = "); Serial.println(yaw_Kd);
            yaw_print = 0;
        }
    }
}
 
//-----------------------------------------------------------------//
//                    Wireless Controller
//-----------------------------------------------------------------//                    
void wirelessControllerBegin()
{
    attachInterrupt(CH1, rising1, RISING);
    attachInterrupt(CH2, rising2, RISING);
    attachInterrupt(CH3, rising3, RISING);
    attachInterrupt(CH4, rising4, RISING);
}
void rising1()
{
    attachInterrupt(CH1, falling1, FALLING);
    CH1_prev_time = micros();
}
 
void falling1()
{
    attachInterrupt(CH1, rising1, RISING);
    CH1_pwm_value = micros() - CH1_prev_time;
}
 
void rising2()
{
    attachInterrupt(CH2, falling2, FALLING);
    CH2_prev_time = micros();
}
 
void falling2()
{
    attachInterrupt(CH2, rising2, RISING);
    CH2_pwm_value = micros() - CH2_prev_time;
}
 
void rising3()
{
    attachInterrupt(CH3, falling3, FALLING);
    CH3_prev_time = micros();
}
 
void falling3()
{
    attachInterrupt(CH3, rising3, RISING);
    CH3_pwm_value = micros() - CH3_prev_time;
}
 
void rising4()
{
    attachInterrupt(CH4, falling4, FALLING);
    CH4_prev_time = micros();
}
 
void falling4()
{
    attachInterrupt(CH4, rising4, RISING);
    CH4_pwm_value = micros() - CH4_prev_time;
}
 
 
void vlaueable_wfly(int* storage)
{
    int temp_storage[4];
 
    //---------------CH1------------------------
    if (CH1_pwm_value>CH1_val + WFLYOFFSET | CH1_pwm_value<CH1_val - WFLYOFFSET)
        CH1_val = CH1_pwm_value;
 
    temp_storage[0= map(CH1_val, CH1_MIN, CH1_MAX, (DEGRANGE*-1), DEGRANGE);
 
    catch_jumping_error(&temp_storage[0], &storage[0], CH1);
 
    if (storage[0>= (CUTFORZERO*-1& storage[0<= CUTFORZERO)
        storage[0= 0;
 
    //----------------CH2----------------------
    if (CH2_pwm_value>CH2_val + WFLYOFFSET | CH2_pwm_value<CH2_val - WFLYOFFSET)
        CH2_val = CH2_pwm_value;
 
    temp_storage[1= -* map(CH2_val, CH2_MIN, CH2_MAX, (DEGRANGE*-1), DEGRANGE);
 
    catch_jumping_error(&temp_storage[1], &storage[1], CH2);
 
    if (storage[1>= (CUTFORZERO*-1& storage[1<= CUTFORZERO)
        storage[1= 0;
 
    //----------------CH3----------------------
    if (CH3_pwm_value>CH3_val + WFLYOFFSET | CH3_pwm_value<CH3_val - WFLYOFFSET)
        CH3_val = CH3_pwm_value;
 
    temp_storage[2= map(CH3_val, CH3_MIN, CH3_MAX, 0, TROTTLERANGE);
 
    catch_jumping_error(&temp_storage[2], &storage[2], CH3);
    //-----------------CH4----------------------
    if (CH4_pwm_value>CH4_val + WFLYOFFSET | CH4_pwm_value<CH4_val - WFLYOFFSET)
        CH4_val = CH4_pwm_value;
 
    temp_storage[3= -* map(CH4_val, CH4_MIN, CH4_MAX, (DEGRANGE*-1), DEGRANGE);
 
    catch_jumping_error(&temp_storage[3], &storage[3], CH4);
 
    if (storage[3>= (CUTFORZERO*-1& storage[3<= CUTFORZERO)
        storage[3= 0;
 
    /*
    Serial.print(controll_val[0]);Serial.print(", ");
    Serial.print(controll_val[1]);Serial.print(", ");
    Serial.print(controll_val[2]);Serial.print(", ");
    Serial.print(controll_val[3]);Serial.print(", ");
    Serial.println("");
    */
}
 
void catch_jumping_error(int * temp_val, int * val, int ch_num)
{
    static int checkArray[CHENELNUM][CHECKINGNUM];
    int sum = 0;
 
    checkArray[ch_num][0= *temp_val;
 
 
    //equal??
    for (int i = 0; i<CHECKINGNUM; i++)
        sum += checkArray[ch_num][i];
 
    if (*temp_val == sum / CHECKINGNUM)
        *val = *temp_val;
 
    //shift
    for (int i = CHECKINGNUM - 1; i >= 0; i--)
        checkArray[ch_num][i + 1= checkArray[ch_num][i];
 
 
 
 
}
 
//---------------------------------------------------------------------//
//
//                                main
//
//--------------------------------------------------------------------//
void setup() {
    Serial.begin(115200);
    Serial1.begin(115200);
    //callibration();
    wirelessControllerBegin();
    motorBegin();
}
 
void loop() {
 
    if (Serial1.available()) //占쏙옙占쏙옙占쏙옙 占쌨깍옙.
    {
        if (recieve_data() == 1){  //占쏙옙占쏙옙占쏙옙 占쏙옙 占쏙옙占쏙옙?
 
            vlaueable_wfly(&controll_val[0]); //占쏙옙占쏙옙占쏙옙
 
            
 
            if (trans_data_to_degree(SBuf) == 1//占쏙옙占쏙옙占쏙옙. 
            {
                if (initial == 0){
                    yaw_setpoint = DegYaw;
                    initial = 1;
                    //Serial.println(yaw_setpoint);
                }
 
                //PID
                rollControll = roll_pid(controll_val[3], DegRoll);
                pitchControll = pitch_pid(controll_val[1], DegPitch);
                yawControll = yaw_pid(yaw_setpoint, DegYaw);
 
                
 
                //Run motor
                run_motors(controll_val[2], rollControll, pitchControll, yawControll);  
 
                if (Serial.available()){ //占쏙옙占쏙옙韜占?
                    from_computer(); //占쌉력받깍옙.
                }
 
                Serial_Monitor(); //Debugging
            }
        }
 
    }
 
 
 
 
 
}
 
 
cs


    



참고

-visualmicro 개발 환경 구축 방법

http://talkingaboutme.tistory.com/206

:
Posted by youjin.A
2016. 2. 8. 02:58

센서값 보정 작품/쿼드콥터2016. 2. 8. 02:58

하드웨어를 다시 만들었기 때문에 센서가 기체에 얼마만큼 기울어져 있는가를 다시 측정 해야했다.

그래서 테스트 해보았는데.. 센서값이 희안하게 조금씩 증가하기도 하고... 뭔가가 반응이 느린것 같았다.

그래서 센서가 기울어진 정도를 측정 했을때 값이 이상하게 나왔다.


test1

test2

test3

test4


roll이든 pitch든 실제 IMU의 측정값인 alpha값이 어느 정도 오차 범위에서 비슷 하게 나와야 하는데 1테스당 5번 시행해서 1개씩 너무 오차가 크게 달랐다.

그래서 오차가 적은 test2의 결과를 받아들여 초기 roll의 setpoint는 -0.60으로 하고 pitch의 setpoint는 -0.67로 하였다.


보정하는데 쓴 코드는 아래에 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/////////////////IMU Sensor/////////////////
//IMU Sensor variable
typedef union {
    signed short value;
    unsigned char byte[2];
} S2BYTE;
 
S2BYTE data_word;
 
unsigned char SBuf[100];
int SCnt = 0;
double  DegRoll, DegPitch, DegYaw;
double roll_alpha1[5], roll_alpha2[5], roll_beta[5];
double pitch_alpha1[5], pitch_alpha2[5], pitch_beta[5];
double roll_mean, pitch_mean;
int count = 0, n=0;
////////////////////////////////////////////
 
int receieve_y_from_computer(void)
{
    if (Serial.available()){
        char c = Serial.read();
        if (c == 'y'){
            Serial.println("recieve 'y'.");
            return 1;
        }
    }
 
    return 0;
}
 
 
//센서값을 읽어서 roll,pitch,yaw 값을 알아낸다.
int recieve_data(void)
{
    static int step_ = 0, check_all_recieve = 0;
    unsigned char data1byte;
    int n;
 
    data1byte = Serial1.read();
 
    switch (step_)
    {
    case 0:
        if (data1byte == 0x55) { step_ = 1, check_all_recieve = 0; }
        break;
 
    case 1:
        if (data1byte == 0x55) { step_ = 2;  SCnt = 0; }
        else step_ = 0;
        break;
 
    case 2:
        SBuf[SCnt++= (unsigned char)data1byte;
        if (SCnt == 8)  // roll(2byte),pitch(2byte),yaw(2byte),checksum(2byte) 
        {
            step_ = 0;
            SCnt = 0;
            check_all_recieve = 1;
        }
        break;
 
    default:
        break;
    }
 
    return check_all_recieve;
}
 
 
static int trans_data_to_degree(unsigned char *sdata)  // sdata : roll(2)+pitch(2)+yaw(2)+chk(2)
{
    int n;
    unsigned short chk = 0;
 
    ///////////// checksum /////////////////
    chk = 0x55 + 0x55;
    for (n = 0; n<6; n++) chk += sdata[n];
    if (chk != get_data_word(&sdata[6]))
    {
        Serial.println("checksum error!");
        return 0//   
    }
    ////////////////////////////////////////
 
    DegRoll = get_data_word(&sdata[0]) / 100.;
    DegPitch = get_data_word(&sdata[2]) / 100. * -1;
    DegYaw = get_data_word(&sdata[4]) / 100.;
 
    return 1;
}
 
static signed short get_data_word(unsigned char *dat)
{
    // little endian..
    data_word.byte[0= dat[1];
    data_word.byte[1= dat[0];
 
    return data_word.value;
}
 
 
 
void setup() {
 
    Serial.begin(115200);
    Serial1.begin(57600);
 
 
}
 
void loop() {
 
    if (Serial1.available()){
        if (recieve_data() == 1)  //roll(2byte),pitch(2byte),yaw(2byte),checksum(2byte) 모든 데이터 받았음
        {
            if (trans_data_to_degree(SBuf) == 1//센서값을 읽어서 roll,pitch,yaw 값을 알아낸다. 
            {
                if (count == 0){
 
                    if (receieve_y_from_computer() == 1)
                    {
                        Serial.print("n = "); Serial.println(n);
 
                        roll_alpha1[n] = DegRoll; 
                        pitch_alpha1[n] = DegPitch;
                        Serial.print("roll_alpha1=  "); Serial.print(roll_alpha1[n]); 
                        Serial.print(" , pitch_alpha1= "); Serial.println(pitch_alpha1[n]);
                        count++;
                    }
                }
 
                Serial.println(DegPitch);
 
            
                if (count == 1){
                    if (receieve_y_from_computer() == 1)
                    {
                        roll_alpha2[n] = DegRoll; 
                        pitch_alpha2[n] = DegPitch;
                        Serial.print("roll_alpha2=  "); Serial.print(roll_alpha2[n]); 
                        Serial.print(" , pitch_alpha2= "); Serial.println(pitch_alpha2[n]);
                        count++;
                    }
                }
 
                if (count == 2){
                    if (receieve_y_from_computer() == && count == 2)
                    {
                        roll_beta[n] = (roll_alpha1[n] + roll_alpha2[n]) / 2;
                        pitch_beta[n] = (pitch_alpha1[n] + pitch_alpha2[n]) / 2;
 
                        Serial.print("roll_beta=  "); Serial.print(roll_beta[n]); 
                        Serial.print(" , pitch_beta= "); Serial.println(pitch_beta[n]);
                        Serial.println("");
                    
                        count = 0;
                        n++;
                    }
                }
 
 
 
            }
        }
    }
 
 
    if (n >= 5)
    {
        Serial.print("roll_alpha1 = ");
        for (int i = 0; i < 5; i++){
            Serial.print(roll_alpha1[i]);
            Serial.print(" ,  ");
        }
        Serial.println("");
 
        Serial.print("roll_alpha2 = ");
        for (int i = 0; i < 5; i++){
            Serial.print(roll_alpha2[i]);
            Serial.print(" ,  ");
        }
        Serial.println("");
 
        Serial.print("roll_beta = ");
        for (int i = 0; i < 5; i++){
            Serial.print(roll_beta[i]);
            Serial.print(" ,  ");
        }
        Serial.println("");
 
        Serial.print("pitch_alpha1 = ");
        for (int i = 0; i < 5; i++){
            Serial.print(pitch_alpha1[i]);
            Serial.print(" ,  ");
        }
        Serial.println("");
 
        Serial.print("pitch_alpha2 = ");
        for (int i = 0; i < 5; i++){
            Serial.print(pitch_alpha2[i]);
            Serial.print(" ,  ");
        }
        Serial.println("");
 
        Serial.print("pitch_beta = ");
        for (int i = 0; i < 5; i++){
            Serial.print(pitch_beta[i]);
            Serial.print(" ,  ");
        }
        Serial.println("");
 
        Serial.println("");
        Serial.println("");
 
        for (int i = 0; i < 5; i++)
        {
            roll_mean += roll_beta[i];
            pitch_mean += pitch_beta[i];
        }
        roll_mean = roll_mean / 5.0;
        pitch_mean = pitch_mean / 5.0;
 
        Serial.print("roll_mean = "); Serial.println(roll_mean);
        Serial.print("pitch_mean = "); Serial.println(pitch_mean);
        n = 0;
    }
}
cs


근데 밤새서 왜 센서가 이런가에대해서 열받고 씨름하고 있었는데 또 해보니까 잘 되었다...뭐지..??

:
Posted by youjin.A
2016. 2. 8. 02:58

쿼드콥터 하드웨어 완성! 작품/쿼드콥터2016. 2. 8. 02:58

하드웨어 조립

아두이노 우노에서 아두이노 메가로 갈아타면서 결국 하드웨어를 처음부터 다시 만들게되었다

우선은 센서와 조종수신부와 MCU등을 연결할 보드부터 만들어야 했다.

보드의 배면도는 다음과 같다.

다음 배면도는 리포배터리를 연결했을 때라도 드론의 동작은 ON/OFF 할 수 있도록 스위치를 연결한 것이다.

그리고 카메라와 카메라 송신기도 5V가 아니라 12V였기때문에 수정을 하였다.


처음에는 다시 만들어야한다는 사실에 멘붕이 왔지만.. 결극 더 나은 하드웨어가 나오게되었다~

그 전 버전의 쿼드콥터는 제어하기 더 쉬울거라는 이유때문에 +형태로 만들었었는데 ...

이번에 하드웨어를 다시 만들게 되면서 카메라를 다는 문제까지 고려하게 되었고 결국 더 간지~>< 나는 x자 형태로 만들었다.

일단 PID제어 테스트를 하기전에 모든 하드웨어를 다 얹어서 해야했기 때문에 무선조종기 수신부랑 카메라랑 카메라 무선 송신기까지 모두 달아놓을 상태이다.

 

위에서 본 모습


옆에서 본 모습


앞에서 본 모습

이렇게 하드웨어를 다 만들고 배터리를 연결해서 테스트를 하려고 했는데..

얼마 지나지 않아 아두이노 메가2560에 레귤레이터가 달려 있는 것 같은 부분으 뜨거워졌다.

처음에는 아두이노 메가2560의 Vin에 12넣는 것이 잘 못 되었나 싶어서 테스터기로 Vin단자와 레귤레이터가 연결되어 있는지

확인해 보았는데 연결되어 있었고, 12V가 들어가는 게 확실한 다른 전원 입력부에 파워서플라이고 12V를 줬는데 마찬가지로 같은 부분이 뜨거워졌다.

그래서 방열판을 잘라서 그 부분에다가 붙였더니 괜찮아 졌다.




조립 후 테스트

하드웨어가 제대로 동작하는지 테스트를 해봤는데 잘 되었다.

원래는 컴퓨터 Serial모니터 상에서 드론의 callibration을 했는데 이제는 조종기에서 바로 할 수 있도록 하였다.

조종기의 throttle을 위로 올린 상태에서 드론의 배터리를 연결하고

기다리다가 "띠띠"소리가 나면 throttle을 아래로 내리고 "띠리리"소리가 나면 callibration이 다 된것이다. 

위 동영상에 대한 코드는 아래에~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
#include "Servo.h"
 
/////////////////BLDC Motor/////////////////
#define MAX_THROTTLE 180
#define MIN_THROTTLE 0
#define MAX_PWM 150
#define MIN_PWM 0
#define MOTOR1  //motor pin number
#define MOTOR2  //motor pin number
#define MOTOR3 44  //motor pin number
#define MOTOR4 45  //motor pin number
 
int motor1Power, motor3Power; // Motors on the X axis
//=>; changing their speeds will affect the pitch
int motor2Power, motor4Power; // Motors on the Y axis
//=>; changing their speeds will affect the roll
  
Servo motor1;
Servo motor2;
Servo motor3;
Servo motor4;
////////////////////////////////////////////
 
 
/////////////////IMU Sensor/////////////////
//IMU Sensor variable
typedef union {
  signed short value;
  unsigned char byte[2];
} S2BYTE;
 
S2BYTE data_word;
 
unsigned char SBuf[100];
int SCnt=0;
double  DegRoll, DegPitch, DegYaw;
////////////////////////////////////////////
 
 
/////////////////PID Conrtroll/////////////////
#define MINhover 0
#define INIThover  20
 
#define INITROLLKp 0.38
#define INITROLLKi 0.000287 
#define INITROLLKd 33
 
#define INITPITCHKp 0.29
#define INITPITCHKi 0.000287 
#define INITPITCHKd 33
 
#define INITYAWKp 0.29 //0.38
#define INITYAWKi 0.000287 
#define INITYAWKd 33
 
#define MAXSPEED  3
#define MINSPEED  100
 
#define INITROLLSETPOINT -1.532
#define INITPITCHSETPOINT -0.516
 
 
double roll_setpoint = INITROLLSETPOINT, pitch_setpoint = INITPITCHSETPOINT, yaw_setpoint = 0;
int hover = INIThover;
double roll_Kp = INITROLLKp, roll_Ki = INITROLLKi, roll_Kd = INITROLLKd;
double pitch_Kp = INITPITCHKp, pitch_Ki = INITPITCHKi, pitch_Kd = INITPITCHKd;
double yaw_Kp = INITYAWKp, yaw_Ki = INITYAWKi, yaw_Kd = INITYAWKd;
double roll_p, roll_i, roll_d, roll_val;
double pitch_p, pitch_i, pitch_d, pitch_val;
double yaw_p, yaw_i, yaw_d, yaw_val;
int rollControll, pitchControll, yawControll;
 
int initial = 0;
////////////////////////////////////////////
 
/////////////////Serial Monitor/////////////////
int Serial_print_sig=1;
int roll_print = 1, pitch_print =0, yaw_print=0, hover_print=0;
////////////////////////////////////////////
 
////////////////Wireless Controller///////////////////
#define CH1 // yaw
#define CH2 //pitch
#define CH3 //hover
#define CH4 //roll
 
#define CH1_MIN 1292//200 1264
#define CH1_MID 1464
#define CH1_MAX 1632//168
 
#define CH2_MIN 1224//304 1176
#define CH2_MID 1480
#define CH2_MAX 1736//256
 
#define CH3_MIN 1028
#define CH3_MID 1448
#define CH3_MAX 1808
 
#define CH4_MIN 1296//208 1264
#define CH4_MID 1472
#define CH4_MAX 1648//176
 
#define CUTFORZERO 3
#define DEGRANGE  45
#define TROTTLERANGE  150
#define WFLYOFFSET 18
#define CHENELNUM 4
#define CHECKINGNUM 4
 
volatile int  CH1_prev_time, CH1_pwm_value;
volatile int  CH2_prev_time, CH2_pwm_value;
volatile int  CH3_prev_time, CH3_pwm_value;
volatile int  CH4_prev_time, CH4_pwm_value;
int CH1_val=0, CH2_val=0, CH3_val=0, CH4_val=0;
int controll_val[4];
int* ptr;
/////////////////////////////////////////////////////////////////////
 
//---------------------------------------------------------------------//
//
//                              funtions
//
//--------------------------------------------------------------------//
 
//----------------------------------------------------------------//
//                      BLDC Motor
//---------------------------------------------------------------//
//esc조절 하기
void callibration(void)
{
  
  Serial.println("Calibrate ESC? 'y' or 'n'.");
    
  while (!Serial.available());
  char cali = Serial.read();
  if(cali == 'y'){  
   Serial.println("send max throttle");
    
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MAX_THROTTLE);
    motor2.write(MAX_THROTTLE);
    motor3.write(MAX_THROTTLE);
    motor4.write(MAX_THROTTLE);
   
    delay(5000);
 
    Serial.println("send min throttle");
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
    motor4.write(MIN_THROTTLE);
 
    delay(2000);
    
    Serial.println("callibration complete");
    
  }else if(cali == 'n'){
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
    motor4.write(MIN_THROTTLE);
   
  }
  Serial.println("If you want Program keep going. Press any key.");
  while (!Serial.available());
}
int motorBegin(void)
  int count=0, throttle;
   
  
  motor1.attach(MOTOR1);
  motor2.attach(MOTOR2);
  motor3.attach(MOTOR3);
  motor4.attach(MOTOR4);
 
  delay(2000);
 
  while(count <5){
    vlaueable_wfly(&controll_val[0]);
    throttle = controll_val[2];
    count++
  }
 
  do{
    vlaueable_wfly(&controll_val[0]);
    throttle = controll_val[2];
      
     
    
    if(throttle < 10){//no callibration
 
      Serial.println("no callibration.");
      
      motor1.write(MIN_THROTTLE);
      motor2.write(MIN_THROTTLE);
      motor3.write(MIN_THROTTLE);
      motor4.write(MIN_THROTTLE);
  
      delay(2000);
 
      Serial.println("program start!");
 
      delay(2000);
      
      return 0;
         
    }else if(throttle > 140){//yes callibration
      Serial.print("you send MAX_THROTTLE.   ");Serial.print("callibration begin.    "); Serial.println("wait 4 seconds");
      
       motor1.write(MAX_THROTTLE);
       motor2.write(MAX_THROTTLE);
       motor3.write(MAX_THROTTLE);
       motor4.write(MAX_THROTTLE);
 
       delay(4000);
 
      Serial.println("send min throttle for caliibraion.");
      
        while(throttle > 10){//wait until MIN_THROTTLE 
          vlaueable_wfly(&controll_val[0]);
          throttle = controll_val[2];
        }
        
      Serial.print("you send MIN_THROTTLE.    ");
         
       motor1.write(MIN_THROTTLE);
       motor2.write(MIN_THROTTLE);
       motor3.write(MIN_THROTTLE);
       motor4.write(MIN_THROTTLE);
 
      Serial.print("calibration complete.     ");
      Serial.println("program start!");
 
      delay(2000);
 
       return 1;
    }
  }while(1);
}
//제어값을 받어서 모터 구동
void run_motors(int throttle, int rollOffset, int pitchOffset, int yawOffset)
{
  //Roll control
  motor1Power = throttle + rollOffset/2;
  motor2Power = throttle + rollOffset/2;
  motor4Power = throttle - rollOffset/2;
  motor3Power = throttle - rollOffset/2;
 
  //Pitch control
  motor4Power = motor4Power + pitchOffset/2;
  motor1Power = motor1Power + pitchOffset/2;
  motor3Power = motor3Power - pitchOffset/2;  
  motor2Power = motor2Power - pitchOffset/2;
 
 /* //yaw control
  motor1Power = motor1Power - yawOffset;
  motor3Power = motor3Power - yawOffset;
  motor2Power = motor2Power + yawOffset;
  motor4Power = motor4Power + yawOffset;
  */
  
  limit_max_min(&motor1Power);
  limit_max_min(&motor2Power);
  limit_max_min(&motor3Power);
  limit_max_min(&motor4Power);
 
  motor1.write(motor1Power);motor3.write(motor3Power);
  motor2.write(motor2Power);motor4.write(motor4Power);
}
 
void limit_max_min(int* pwm)//modify
{
  if(*pwm>MAX_PWM)
  *pwm = MAX_PWM;
  else if(*pwm<MIN_PWM)
  *pwm = MIN_PWM;
}
//---------------------------------------------------------//
//                     IMU Sensor
//--------------------------------------------------------//
//센서값을 읽어서 roll,pitch,yaw 값을 알아낸다.
int recieve_data(void)
{
    static int step_=0, check_all_recieve=0;
    unsigned char data1byte;
    int n;
 
    data1byte = Serial1.read();
    
    switch(step_)
    {
        case 0:
           if(data1byte==0x55) {step_=1, check_all_recieve=0;}
        break;
 
        case 1:
           if(data1byte==0x55) { step_=2;  SCnt=0;}
           else step_=0;
        break;
 
        case 2:
           SBuf[SCnt++= (unsigned char)data1byte;
           if(SCnt==8)  // roll(2byte),pitch(2byte),yaw(2byte),checksum(2byte) 
             {   
                step_=0;
                SCnt=0;
                check_all_recieve = 1;
             }
        break;
 
        default:
        break;
     }
   
    return check_all_recieve;
}
 
static int trans_data_to_degree(unsigned char *sdata)  // sdata : roll(2)+pitch(2)+yaw(2)+chk(2)
{
  int n;
  unsigned short chk=0;
 
  ///////////// checksum /////////////////
  chk=0x55+0x55;
  for(n=0;n<6;n++) chk+=sdata[n]; 
  if(chk != get_data_word(&sdata[6])) 
  {
    Serial.print("checksum error!");
    return 0//   
  }
  ////////////////////////////////////////
 
  DegRoll  = get_data_word(&sdata[0]) / 100.;
  DegPitch = get_data_word(&sdata[2]) / 100. * -1;
  DegYaw   = get_data_word(&sdata[4]) / 100.;
 
  return 1;
}
 
static signed short get_data_word(unsigned char *dat)
{
  // little endian..
  data_word.byte[0]=dat[1];  
  data_word.byte[1]=dat[0];  
 
  return data_word.value;
}
 
//-----------------------------------------------------------//
//                     PID Conrtroll
//----------------------------------------------------------//
//각도 값을 받아서 PID제어값 출력
double roll_pid(double setpoint, double degree)
{
    double val_out;
    static double roll_p_err_prv, roll_p_err, roll_i_err, roll_d_err;
 
    roll_p_err = setpoint-degree;
    roll_i_err += roll_p_err;
    roll_d_err = roll_p_err - roll_p_err_prv;
    
    roll_p_err_prv = roll_p_err;
    val_out = (roll_Kp*roll_p_err) + (roll_Ki*roll_i_err) + (roll_Kd*roll_d_err);
 
    roll_p = roll_Kp*roll_p_err;
    roll_i = roll_Ki*roll_i_err;
    roll_d = roll_Kd*roll_d_err;
    roll_val = val_out;
    
    return val_out;
}
 
double pitch_pid(double setpoint, double degree)
{
    double val_out;
    static double pitch_p_err_prv, pitch_p_err, pitch_i_err, pitch_d_err;
 
    pitch_p_err = setpoint-degree;
    pitch_i_err += pitch_p_err;
    pitch_d_err = pitch_p_err - pitch_p_err_prv;
    
    pitch_p_err_prv = pitch_p_err;
    val_out = (pitch_Kp*pitch_p_err) + (pitch_Ki*pitch_i_err) + (pitch_Kd*pitch_d_err);
    
    pitch_p = pitch_Kp*pitch_p_err;
    pitch_i = pitch_Ki*pitch_i_err;
    pitch_d = pitch_Kd*pitch_d_err;
    pitch_val = val_out;
    
    return val_out;
}
 
double yaw_pid(double setpoint, double degree)
{
    double val_out;
    static double yaw_p_err_prv, yaw_p_err, yaw_i_err, yaw_d_err;
 
    yaw_p_err = setpoint-degree;
    yaw_i_err += yaw_p_err;
    yaw_d_err = yaw_p_err - yaw_p_err_prv;
    
    yaw_p_err_prv = yaw_p_err;
    val_out = (yaw_Kp*yaw_p_err) + (yaw_Ki*yaw_i_err) + (yaw_Kd*yaw_d_err);
    
    yaw_p = yaw_Kp*yaw_p_err;
    yaw_i = yaw_Ki*yaw_i_err;
    yaw_d = yaw_Kd*yaw_d_err;
    yaw_val = val_out;
    
    return val_out;
}
 
//---------------------------------------------------------//
//                      Serial Monitor
//----------------------------------------------------------//
void from_computer(void)
{
    char c = Serial.read();
    
    //roll debuging
    if(c=='q'){
      roll_Kp += 0.01;
      Serial.print("roll_Kp = ");Serial.println(roll_Kp);
    }else if(c=='w'){
      roll_Kp -= 0.01;
      Serial.print("roll_Kp = ");Serial.println(roll_Kp);
    }else if(c=='e'){
      roll_Kp= INITROLLKp;
      Serial.print("roll_Kp = ");Serial.println(roll_Kp);
    }else if(c=='a'){
      roll_Ki += 0.000001;
      Serial.print("roll_Ki = ");Serial.println(roll_Ki*10000);
    }else if(c=='s'){
      roll_Ki -= 0.000001;
      Serial.print("roll_Ki = ");Serial.println(roll_Ki*10000);
    }else if(c=='d'){
      roll_Ki = INITROLLKi;
      Serial.print("roll_Ki = ");Serial.println(roll_Ki*10000);
    }else if(c=='z'){
      roll_Kd += 1;
      Serial.print("roll_Kd = ");Serial.println(roll_Kd);
    }else if(c=='x'){
      roll_Kd -= 1;
      Serial.print("roll_Kd = ");Serial.println(roll_Kd);
    }else if(c=='c'){
      roll_Kd = INITROLLKd;
      Serial.print("roll_Kd = ");Serial.println(roll_Kd);
    }
    
    
    
    //pitch debuging
    else if(c=='r'){
      pitch_Kp += 0.01;
      Serial.print("pitch_Kp = ");Serial.println(pitch_Kp);
    }else if(c=='t'){
      pitch_Kp -= 0.01;
      Serial.print("pitch_Kp = ");Serial.println(pitch_Kp);
    }else if(c=='y'){
      pitch_Kp= INITPITCHKp;
      Serial.print("pitch_Kp = ");Serial.println(pitch_Kp);
    }else if(c=='f'){
      pitch_Ki += 0.000001;
      Serial.print("pitch_Ki = ");Serial.println(pitch_Ki*10000);
    }else if(c=='g'){
      pitch_Ki -= 0.000001;
      Serial.print("pitch_Ki = ");Serial.println(pitch_Ki*10000);
    }else if(c=='h'){
      pitch_Ki = INITPITCHKi;
      Serial.print("pitch_Ki = ");Serial.println(pitch_Ki*10000);
    }else if(c=='v'){
      pitch_Kd += 1;
      Serial.print("pitch_Kd = ");Serial.println(pitch_Kd);
    }else if(c=='b'){
      pitch_Kd -= 1;
      Serial.print("pitch_Kd = ");Serial.println(pitch_Kd);
    }else if(c=='n'){
      pitch_Kd = INITPITCHKd;
      Serial.print("pitch_Kd = ");Serial.println(pitch_Kd);
    }
 
    //yaw debuging
    else if(c=='u'){
      yaw_Kp += 0.01;
      Serial.print("yaw_Kp = ");Serial.println(yaw_Kp);
    }else if(c=='i'){
      yaw_Kp -= 0.01;
      Serial.print("yaw_Kp = ");Serial.println(yaw_Kp);
    }else if(c=='o'){
      yaw_Kp= INITYAWKp;
      Serial.print("yaw_Kp = ");Serial.println(yaw_Kp);
    }else if(c=='j'){
      yaw_Ki += 0.000001;
      Serial.print("yaw_Ki = ");Serial.println(yaw_Ki*10000);
    }else if(c=='k'){
      yaw_Ki -= 0.000001;
      Serial.print("yaw_Ki = ");Serial.println(yaw_Ki*10000);
    }else if(c=='l'){
      yaw_Ki = INITYAWKi;
      Serial.print("yaw_Ki = ");Serial.println(yaw_Ki*10000);
    }else if(c=='m'){
      yaw_Kd += 1;
      Serial.print("yaw_Kd = ");Serial.println(yaw_Kd);
    }else if(c==','){
      yaw_Kd -= 1;
      Serial.print("yaw_Kd = ");Serial.println(yaw_Kd);
    }else if(c=='.'){
      yaw_Kd = INITYAWKd;
      Serial.print("yaw_Kd = ");Serial.println(yaw_Kd);
    }
 
    else if(c=='p'){
      Serial_print_sig = !(Serial_print_sig);
    }else if(c=='/'){
      roll_print = !(roll_print);
    }else if(c=='*'){
      pitch_print = !(pitch_print);
    }else if(c=='-'){
      yaw_print = !(yaw_print);
    }else if(c=='+'){
      hover_print = !(hover_print);
    }
    
}
 
 
void Serial_Monitor(void)
{
  if(Serial_print_sig ==){
    if(roll_print == 1){
      Serial.print("Roll=> ");Serial.print(DegRoll);Serial.print(", ");Serial.print(roll_p); Serial.print(", ");Serial.print(roll_i); Serial.print(", ");Serial.print(roll_d);Serial.print(", ");Serial.print(roll_val);Serial.print(", ");Serial.print(motor2Power);Serial.print(", ");Serial.println(motor4Power);
    }else if(pitch_print == 1){
      Serial.print("Pitch=> ");Serial.print(DegPitch);Serial.print(", ");Serial.print(pitch_p); Serial.print(", ");Serial.print(pitch_i); Serial.print(", ");Serial.print(pitch_d);Serial.print(", ");Serial.print(pitch_val);Serial.print(", ");Serial.print(motor1Power);Serial.print(", ");Serial.println(motor3Power);
    }else if(yaw_print == 1){
      Serial.print("Yaw=> ");Serial.print(DegYaw);Serial.print(", ");Serial.print(yaw_p); Serial.print(", ");Serial.print(yaw_i); Serial.print(", ");Serial.print(yaw_d);Serial.print(", ");Serial.println(yaw_val); 
    }
  } 
 
  if(Serial_print_sig == 0){
    if(hover_print == 1){
      Serial.print("hover = ");Serial.println(hover);
      hover_print =0;
    }else if(roll_print == 1){
      Serial.print("roll_Kp = ");Serial.print(roll_Kp);Serial.print(", roll_Ki = ");Serial.print(roll_Ki*10000);Serial.print(", roll_Kd = ");Serial.println(roll_Kd);
      roll_print = 0;
    }else if(pitch_print == 1){
      Serial.print("pitch_Kp = ");Serial.print(pitch_Kp);Serial.print(", pitch_Ki = ");Serial.print(pitch_Ki*10000);Serial.print(", pitch_Kd = ");Serial.println(pitch_Kd);
      pitch_print = 0;
    }else if(yaw_print == 1){
      Serial.print("yaw_Kp = ");Serial.print(yaw_Kp);Serial.print(", yaw_Ki = ");Serial.print(yaw_Ki*10000);Serial.print(", yaw_Kd = ");Serial.println(yaw_Kd);
      yaw_print = 0;
    }
  }
}
 
//-----------------------------------------------------------------//
//                    Wireless Controller
//-----------------------------------------------------------------//                    
void wirelessControllerBegin()
{
  attachInterrupt(CH1, rising1, RISING);
  attachInterrupt(CH2, rising2, RISING);
  attachInterrupt(CH3, rising3, RISING);
  attachInterrupt(CH4, rising4, RISING);
}
 void rising1()
{
  attachInterrupt(CH1, falling1, FALLING);
  CH1_prev_time = micros(); 
}
 
void falling1()
{
  attachInterrupt(CH1, rising1, RISING);
  CH1_pwm_value = micros() - CH1_prev_time;
}
 
void rising2()
{
  attachInterrupt(CH2, falling2, FALLING);
  CH2_prev_time = micros(); 
}
 
void falling2()
{
  attachInterrupt(CH2, rising2, RISING);
  CH2_pwm_value = micros() - CH2_prev_time;
}
 
void rising3()
{
  attachInterrupt(CH3, falling3, FALLING);
  CH3_prev_time = micros(); 
}
 
void falling3()
{
  attachInterrupt(CH3, rising3, RISING);
  CH3_pwm_value = micros() - CH3_prev_time;
}
 
void rising4()
{
  attachInterrupt(CH4, falling4, FALLING);
  CH4_prev_time = micros(); 
}
 
void falling4()
{
  attachInterrupt(CH4, rising4, RISING);
  CH4_pwm_value = micros() - CH4_prev_time;
}
 
 
void vlaueable_wfly(int* storage)
{
  int temp_storage[4];
  
   //---------------CH1------------------------
  if(CH1_pwm_value>CH1_val+WFLYOFFSET | CH1_pwm_value<CH1_val-WFLYOFFSET)
  CH1_val = CH1_pwm_value;
  
  temp_storage[0= map(CH1_val, CH1_MIN, CH1_MAX, (DEGRANGE*-1), DEGRANGE);
 
  catch_jumping_error(&temp_storage[0], &storage[0], CH1);
  
  if(storage[0>=(CUTFORZERO*-1& storage[0<=CUTFORZERO)
  storage[0]  = 0;
 
  //----------------CH2----------------------
  if(CH2_pwm_value>CH2_val+WFLYOFFSET | CH2_pwm_value<CH2_val-WFLYOFFSET)
  CH2_val = CH2_pwm_value;
  
  temp_storage[1= -1*map(CH2_val, CH2_MIN, CH2_MAX, (DEGRANGE*-1), DEGRANGE);
 
catch_jumping_error(&temp_storage[1], &storage[1], CH2);
 
  if(storage[1]>=(CUTFORZERO*-1& storage[1]<=CUTFORZERO)
  storage[1= 0;
  
  //----------------CH3----------------------
  if(CH3_pwm_value>CH3_val+WFLYOFFSET| CH3_pwm_value<CH3_val-WFLYOFFSET)
  CH3_val = CH3_pwm_value;
  
  temp_storage[2= map(CH3_val, CH3_MIN, CH3_MAX, 0, TROTTLERANGE);
 
catch_jumping_error(&temp_storage[2], &storage[2], CH3);
  //-----------------CH4----------------------
  if(CH4_pwm_value>CH4_val+WFLYOFFSET | CH4_pwm_value<CH4_val-WFLYOFFSET)
  CH4_val = CH4_pwm_value;
  
  temp_storage[3= -1*map(CH4_val, CH4_MIN, CH4_MAX, (DEGRANGE*-1), DEGRANGE);
 
  catch_jumping_error(&temp_storage[3], &storage[3], CH4);
 
  if(storage[3]>=(CUTFORZERO*-1& storage[3]<=CUTFORZERO)
  storage[3= 0;
 
  /*
   Serial.print(controll_val[0]);Serial.print(", ");
   Serial.print(controll_val[1]);Serial.print(", ");
   Serial.print(controll_val[2]);Serial.print(", ");
   Serial.print(controll_val[3]);Serial.print(", ");
   Serial.println("");
   */
  }
 
void catch_jumping_error(int * temp_val, int * val, int ch_num)
{
  static int checkArray[CHENELNUM][CHECKINGNUM];
  int sum=0;
  
  checkArray[ch_num][0= *temp_val;
 
  
  //equal??
  for(int i=0; i<CHECKINGNUM; i++)
  sum += checkArray[ch_num][i];
 
  if(* temp_val == sum/CHECKINGNUM)
   *val = * temp_val;
  
 //shift
  for(int i=CHECKINGNUM-1; i>=0; i--)
    checkArray[ch_num][i+1= checkArray[ch_num][i];
  
  
 
  
}
 
//---------------------------------------------------------------------//
//
//                                main
//
//--------------------------------------------------------------------//
void setup() {
  Serial.begin(115200); 
  Serial1.begin(57600); 
  //callibration();
  wirelessControllerBegin();
  motorBegin();
}
 
void loop() {
 
 
  
  if(Serial1.available()) //데이터 받기.
  { 
   if(recieve_data()==1){  //데이터 다 받음?
      
    vlaueable_wfly(&controll_val[0]); //조종값
  
    if(trans_data_to_degree(SBuf)==1//센서값. 
     {
      if(initial == 0){
      yaw_setpoint = DegYaw;
      initial = 1;
      //Serial.println(yaw_setpoint);
      }
 
      //PID
      rollControll = roll_pid(controll_val[3], DegRoll);  
      pitchControll = pitch_pid(controll_val[1], DegPitch);
      yawControll = yaw_pid(yaw_setpoint, DegYaw);
     
      run_motors(controll_val[2], rollControll, pitchControll, yawControll); //Run motor
 
      if(Serial.available()){ //통신입력?
       from_computer(); //입력받기.
       }
    
       Serial_Monitor(); //Debugging
      }
    } 
    
  }
 
 
 
   
 
}
 
 
cs



모터 구동을 하면서 카메라가 제대로 나오는지 테스트 해보았다. 

이 테스트가 되면 하드웨어를 조립해서 보든 부품들이 정상적으로 동작한 다는 것이였다.

결과적으로 잘 동작했다!!


참고

-X형 드론 모터 구동방법

http://technicaladventure.blogspot.kr/2012/09/quadcopter-stabilization-control-system.html


:
Posted by youjin.A

우선 코드를 조금씩 바꿔서 ESC와 IMU, 무선조종기 수신기 각각이 아두이노 MEGA2560에서 제대로 돌아가는 지 보았다.

그 결과 일단 각각은 모두모두 잘 돌아감.


ESC 테스트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include "SoftwareSerial.h"
#include "Servo.h"
 
/////////////////BLDC Motor/////////////////
#define MAX_THROTTLE 180
#define MIN_THROTTLE 0
#define MAX_PWM 150
#define MIN_PWM 0
#define MOTOR1 11  //motor pin number
#define MOTOR2 12  //motor pin number
#define MOTOR3 13  //motor pin number
#define MOTOR4 //motor pin number
 
int throttle = 0;
 
Servo motor1;
Servo motor2;
Servo motor3;
Servo motor4;
////////////////////////////////////////////
 
 
 
//---------------------------------------------------------------------//
//
//                              funtions
//
//--------------------------------------------------------------------//
 
void callibration(void)
{
  
  Serial.println("Calibrate ESC? 'y' or 'n'.");
    
  while (!Serial.available());
  char cali = Serial.read();
  if(cali == 'y'){  
    Serial.println("send max throttle");
    
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MAX_THROTTLE);
    motor2.write(MAX_THROTTLE);
    motor3.write(MAX_THROTTLE);
    motor4.write(MAX_THROTTLE);
   
    delay(5000);
 
     Serial.println("send min throttle");
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
    motor4.write(MIN_THROTTLE);
 
    delay(2000);
    
    Serial.println("callibration complete");
    
  }else if(cali == 'n'){
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
    motor4.write(MIN_THROTTLE);
   
  }
  Serial.println("If you want Program keep going. Press any key.");
  while (!Serial.available());
}
 
void send_val(void)
{
   if(Serial.available()){
    
    char c = Serial.read();
    if(c=='q'){
      throttle += 1;
      Serial.print("throttle = ");Serial.println(throttle);
    }else if(c=='w'){
      throttle -= 1;
      Serial.print("throttle = ");Serial.println(throttle);
    }else if(c=='e'){
      throttle= MAX_PWM;
      Serial.print("throttle = ");Serial.println(throttle);
    }else if(c=='r'){
      throttle= MIN_PWM;
      Serial.print("throttle = ");Serial.println(throttle);
    }
   }
}
 
//제어값을 받어서 모터 구동
void run_motors(int val)
{
  int motor1Power, motor3Power; // Motors on the X axis
  //=>; changing their speeds will affect the pitch
  int motor2Power, motor4Power; // Motors on the Y axis
  //=>; changing their speeds will affect the roll
 
  motor1Power = val;  
  motor2Power = val;  
  motor3Power = val; 
  motor4Power = val; 
  
  motor1.write(motor1Power);motor3.write(motor3Power);
  motor2.write(motor2Power);motor4.write(motor4Power);
  }    
 
 
void setup() {
   Serial.begin(115200); 
 
   callibration();
}
 
void loop() {
  send_val();
  run_motors(throttle);
}
cs


IMU테스트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
typedef union {
  signed short value;
  unsigned char byte[2];
} S2BYTE;
 
S2BYTE data_word;
 
unsigned char SBuf[100];
int SCnt=0;
double  DegRoll, DegPitch, DegYaw;
 
int recieve_data(void)
{
    static int step_=0, check_all_recieve=0;
    unsigned char data1byte;
    int n;
 
    data1byte = Serial1.read();
    
    switch(step_)
    {
        case 0:
           if(data1byte==0x55) {step_=1, check_all_recieve=0;}
        break;
 
        case 1:
           if(data1byte==0x55) { step_=2;  SCnt=0;}
           else step_=0;
        break;
 
        case 2:
           SBuf[SCnt++= (unsigned char)data1byte;
           if(SCnt==8)  // roll(2byte),pitch(2byte),yaw(2byte),checksum(2byte) 
             {   
                step_=0;
                SCnt=0;
                check_all_recieve = 1;
             }
        break;
 
        default:
        break;
     }
   
    return check_all_recieve;
}
 
static int trans_data_to_degree(unsigned char *sdata)  // sdata : roll(2)+pitch(2)+yaw(2)+chk(2)
{
  int n;
  unsigned short chk=0;
 
  ///////////// checksum /////////////////
  chk=0x55+0x55;
  for(n=0;n<6;n++) chk+=sdata[n]; 
  if(chk != get_data_word(&sdata[6])) 
  {
    Serial.println("checksum error!");
    return 0//   
  }
  ////////////////////////////////////////
 
  DegRoll  = get_data_word(&sdata[0]) / 100.;
  DegPitch = get_data_word(&sdata[2]) / 100. * -1;
  DegYaw   = get_data_word(&sdata[4]) / 100.;
 
  return 1;
}
 
static signed short get_data_word(unsigned char *dat)
{
  // little endian..
  data_word.byte[0]=dat[1];  
  data_word.byte[1]=dat[0];  
 
  // big endian..
  //data_word.byte[1]=dat[1];  
  //data_word.byte[0]=dat[0];  
  
  return data_word.value;
}
 
void setup() {
  Serial.begin(115200);
  Serial1.begin(57600);
}
 
void loop() { 
 
  
  if(Serial1.available()){
    if(recieve_data()==1)  //roll(2byte),pitch(2byte),yaw(2byte),checksum(2byte) all recieve!!!
    {   
     if(trans_data_to_degree(SBuf)==1)  
     {
       Serial.print(DegRoll);Serial.print(", ");Serial.print(DegPitch);Serial.print(", ");Serial.println(DegYaw);
     }
    }
  }
 
 
}
cs


무선조종기 수신기 테스트

아래 코드에서 주의 할 점은 attachInterrupt()함수에서 첫번째 인자가 핀 번호가 아니라 인터럽트 번호인것이다.

이것때문에... 많이 고생했지..

Board                     int.0 int.1 int.2 int.3 int.4 int.5

Uno, Ethernet            2      3
Mega2560                 2      3     21     20   19   18
Leonardo                  3      2     0       1      7

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#define CH1 0
#define CH2 1
#define CH3 2
#define CH4 3
 
volatile int  CH1_prev_time, CH1_pwm_value;
volatile int  CH2_prev_time, CH2_pwm_value;
volatile int  CH3_prev_time, CH3_pwm_value;
volatile int  CH4_prev_time, CH4_pwm_value;
 
void rising1()
{
  attachInterrupt(CH1, falling1, FALLING);
  CH1_prev_time = micros(); 
}
 
void falling1()
{
  attachInterrupt(CH1, rising1, RISING);
  CH1_pwm_value = micros() - CH1_prev_time;
}
 
void rising2()
{
  attachInterrupt(CH2, falling2, FALLING);
  CH2_prev_time = micros(); 
}
 
void falling2()
{
  attachInterrupt(CH2, rising2, RISING);
  CH2_pwm_value = micros() - CH2_prev_time;
}
 
void rising3()
{
  attachInterrupt(CH3, falling3, FALLING);
  CH3_prev_time = micros(); 
}
 
void falling3()
{
  attachInterrupt(CH3, rising3, RISING);
  CH3_pwm_value = micros() - CH3_prev_time;
}
 
void rising4()
{
  attachInterrupt(CH4, falling4, FALLING);
  CH4_prev_time = micros(); 
}
 
void falling4()
{
  attachInterrupt(CH4, rising4, RISING);
  CH4_pwm_value = micros() - CH4_prev_time;
}
 
void setup() {
 Serial.begin(115200);
 attachInterrupt(CH1, rising1, RISING);
 attachInterrupt(CH2, rising2, RISING);
 attachInterrupt(CH3, rising3, RISING);
 attachInterrupt(CH4, rising4, RISING);
}
 
void loop() {
 Serial.print(CH1_pwm_value);Serial.print(", ");
 Serial.print(CH2_pwm_value);Serial.print(", ");
 Serial.print(CH3_pwm_value);Serial.print(", ");
 Serial.print(CH4_pwm_value);Serial.print(", ");
 Serial.println("");
}
 
 
cs



-참고

아두이노 인터럽트

http://www.hardcopyworld.com/ngine/aduino/index.php/archives/594

:
Posted by youjin.A

400Hz PWM 파형을 만듬

아두이노에서는 16bit카운터가 하나밖에 없어서 ESC를 제어하기 위해 PWM파형을 400Hz로 출력하는 데 많은 문제가 있다.

이것은 프로그램상의 문제였는데.. 결국에는 실패하고 50Hz를 사용하기로 하였다.

하지만 메가2560은 16bit 카운터가 4개가 있었기 때문에  400Hz를 출력해도 프로그램상 아무 문제가 없었다.

그래서 FAST PWM모드를 이용한 카운터 인터럽트로 400Hz를 만들었다.

아래 코드는 단순히 핀에서 400Hz PWM이 나오도록 한 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/////////////////BLDC Motor/////////////////
#define MAX_THROTTLE 4760
#define MIN_THROTTLE 1040
#define MAX_PWM 4000
#define MIN_PWM 1040
#define MOTOR1 11  //motor pin number
#define MOTOR2 12  //motor pin number
#define MOTOR3 13  //motor pin number
#define MOTOR4 //motor pin number
////////////////////////////////////////////
 
class motor
{
  private:
      int pin;
  public:
      void attach(int);
      void write(int);
  
};
  
void motor::attach(int motorPin)
{
    pin = motorPin;
    
    TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(COM1C1) | _BV(WGM11); //16bit-Timer/Counter1 FAST PWM
    TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10);
    TCCR3A = _BV(COM3A1) | _BV(WGM31); //16bit-Timer/Counter3 FAST PWM
    TCCR3B = _BV(WGM33) | _BV(WGM32) | _BV(CS30);
  
    ICR1 = 40000;
    ICR3 = 40000;
}
  
void motor::write(int pwm)
{
      switch(pin)
     {
        case MOTOR1 :
         OCR1A = pwm;
         break;
        case MOTOR2 :
           OCR1B =  pwm;
           break;
        case MOTOR3 :
           OCR1C =  pwm;
           break;
        case MOTOR4 :
           OCR3A =  pwm;
           break;
        default :
          Serial.println("wrong motor pin");
    }
}
 
 
void setup() {
  pinMode(MOTOR1, OUTPUT);
  pinMode(MOTOR2, OUTPUT);
  pinMode(MOTOR3, OUTPUT);
  pinMode(MOTOR4, OUTPUT);
 
  motor motor1;
  motor motor2;
  motor motor3;
  motor motor4;
 
  motor1.attach(MOTOR1);
  motor2.attach(MOTOR2);
  motor3.attach(MOTOR3);
  motor4.attach(MOTOR4);
  motor1.write(MAX_THROTTLE);
  motor2.write(MAX_THROTTLE);
  motor3.write(MAX_THROTTLE);
  motor4.write(MAX_THROTTLE);
}
 
void loop() {
  // put your main code here, to run repeatedly:
 
}
cs


하지만..

하지만 우리의 esc인 ipeaka esc 22a님께서 400Hz가 너무 빠른지 못받아 들이신다.

아래 코드는 400Hz에다가 초기에 최대 듀티비와 최소 듀티비를 변하게해서 ESC를 callibration하는 코드를 추가한 것이다.

callibration을 할 때 max를 주문 "띠 띠띠"소리 나는 거랑 min을 주면 "띠 띠~띠~띠"소리 나는 설정이 안된다...ㅠ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
 
 
/////////////////BLDC Motor/////////////////
#define MAX_THROTTLE 4760
#define MIN_THROTTLE 1040
#define MAX_PWM 4000
#define MIN_PWM 1040
#define MOTOR1 11  //motor pin number
#define MOTOR2 12  //motor pin number
#define MOTOR3 13  //motor pin number
#define MOTOR4 //motor pin number
 
int throttle = MIN_THROTTLE;
////////////////////////////////////////////
 
class motor
{
  private:
      int pin;
  public:
      void attach(int);
      void write(int);
  
};
  motor motor1;
  motor motor2;
  motor motor3;
  motor motor4;
void motor::attach(int motorPin)
{
    pin = motorPin;
    pinMode(pin, OUTPUT);
    
    TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(COM1C1) | _BV(WGM11); //16bit-Timer/Counter1 FAST PWM
    TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10);
    TCCR3A = _BV(COM3A1) | _BV(WGM31); //16bit-Timer/Counter3 FAST PWM
    TCCR3B = _BV(WGM33) | _BV(WGM32) | _BV(CS30);
  
    ICR1 = 60000;
    ICR3 = 60000;
}
  
void motor::write(int pwm)
{
      switch(pin)
     {
        case MOTOR1 :
         OCR1A = pwm;
         break;
        case MOTOR2 :
           OCR1B =  pwm;
           break;
        case MOTOR3 :
           OCR1C =  pwm;
           break;
        case MOTOR4 :
           OCR3A =  pwm;
           break;
        default :
          Serial.println("wrong motor pin");
    }
}
//-----------------------------------------------------------------
//esc조절 하기
void callibration(void)
{
  
  Serial.println("Calibrate ESC? 'y' or 'n'.");
    
  while (!Serial.available());
  char cali = Serial.read();
  if(cali == 'y'){  
   Serial.println("send max throttle");
    
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MAX_THROTTLE);
    motor2.write(MAX_THROTTLE);
    motor3.write(MAX_THROTTLE);
    motor4.write(MAX_THROTTLE);
   
    delay(5000);
 
    Serial.println("send min throttle");
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
    motor4.write(MIN_THROTTLE);
 
    delay(2000);
    
    Serial.println("callibration complete");
    
  }else if(cali == 'n'){
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
    motor4.write(MIN_THROTTLE);
   
  }
  Serial.println("If you want Program keep going. Press any key.");
  while (!Serial.available());
}
//-----------------------------------------------------
void send_val(void)
{
   if(Serial.available()){
    
    char c = Serial.read();
    if(c=='q'){
      throttle += 1;
      Serial.print("throttle = ");Serial.println(throttle);
    }else if(c=='w'){
      throttle -= 1;
      Serial.print("throttle = ");Serial.println(throttle);
    }else if(c=='e'){
      throttle= MAX_THROTTLE;
      Serial.print("throttle = ");Serial.println(throttle);
    }else if(c=='r'){
      throttle= MIN_THROTTLE;
      Serial.print("throttle = ");Serial.println(throttle);
    }
   }
}
 
//제어값을 받어서 모터 구동
void run_motors(int val)
{
  int motor1Power, motor3Power; // Motors on the X axis
  //=>; changing their speeds will affect the pitch
  int motor2Power, motor4Power; // Motors on the Y axis
  //=>; changing their speeds will affect the roll
 
  motor1Power = val;  
  motor2Power = val;  
  motor3Power = val; 
  motor4Power = val; 
  
  motor1.write(motor1Power);motor3.write(motor3Power);
  motor2.write(motor2Power);motor4.write(motor4Power);
  }    
  //-----------------------------------------------------------
 
void setup() {
 Serial.begin(115200);
  callibration();
}
 
 
 
//---------------------------------------------------------------------//
//
//                                main
//
//--------------------------------------------------------------------//
void loop() {
  // put your main code here, to run repeatedly:
 send_val();
  run_motors(throttle);
}
cs

220Hz로 낮추면 어쩔때는 되고 어떨때는 안되서 ...  하드웨어 적인 문제때문에 결국은 50Hz를 쓰기로 하였다.

:
Posted by youjin.A

아두이노 우노에서의 문제

앞전에 IMU센서와 무선조종기 수신부를 아두이노 우노에 같이 연결하면 

IMU값도 제대로 읽어 들이지 못해서 checksum_error가 발생하였고 무선조종기의 값도 제대로 수신하지 못하였다.

이러한 문제는 아두이노 우노에는 하드웨어적인 UART가 1개만 제공되어 지기때문에

무선조종기의 데이터는 소프트웨어 적으로 처리해서 그 처리 시간이 길어져서 생기는 것이였다.

우노를 사용할 때는 컴퓨터와 Serial통신을 하기 위해 0,1번을 썻고

IMU센서값을 읽기위해 2,4번 핀을 썻고, 모터를 제어하기위해 3,5,9,10을 썻다.

여기에서 4채널 무선수신기를 18,17,16,15에 연결하였다.

무선수신기는 PWM파형이 나오는 데 이것을 읽기 위해서는 처음에 rising edge와 falling edge를 받아서 그 사이에 시간을 구하면 되는 쉬운 문제로 생각했다.

하지만 무선수신기는 pinChange형태이지만 인터럽트를 받는 데 그것이 아주 빠른속도로 계속 들어온다.

그 때문에 한번씩 센서의 값을 읽어들이지 못했던 것이다. 


메가2560으로 교체

프로그램이 센서와 수신부를 동시에 처리할 때 문제를 격었기 때문에 프로그램에서 센서를 없앴다.

이 말은 센서의 값을 읽기위해서 UART를 하드웨어적으로 처리한다는 의미로 결국 UART핀이 더 필요했다.

메가2560은 UART가 컴퓨터와의 Serial통신을 제외하고도 3개가 더 제공되었기 때문에..

과감히..(;;;)보드를 교체했다.

메가에서는 컴퓨터와의 통신은 0,1번핀을 사용했고

IMU센서는 19,18번 핀을 , 모터는 6,7,44,45번 핀을, 조종기 수신부는 2,3,21,20번 핀을 사용하였다.




참고

-아두이노 메가2560 산곳

http://www.mechasolution.com/shop/goods/goods_view.php?goodsno=3&category=038004

-아두이노 메가2560 기본정보

https://www.arduino.cc/en/Main/ArduinoBoardMega2560

:
Posted by youjin.A

무선 조종기

드론을 먼 거리에서도 조종 할 수 있으려면 블루투스로는 텍도없기 때문에 무선 RF 조종기를 구입하였습니다.

Manual for WFT06X.pdf

WFLY-6-2__ ___.pdf


무선 조종기는 아래 동영상을 보면 알 수 있는데 수신부에서는 일정 주파수의 펄스가 계속 들어옵니다.

이때 펄스의 듀티비에 따라 우리는 값을 처리 할 수 있고 그 값을 이용해서 쿼드콥터를 조종할 수 있습니다.

이 듀티비를 받아서 처리할 수 있는 아두이노 코드는 아래에 있어요.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#define CH1 15 // yaw
#define CH2 16 //pitch
#define CH3 17 //hover
#define CH4 18 //roll
 
#define CH1_MIN 1270//200 1264
#define CH1_MID 1464
#define CH1_MAX 1632//168
 
#define CH2_MIN 1224//304 1176
#define CH2_MID 1480
#define CH2_MAX 1736//256
 
#define CH3_MIN 1028
#define CH3_MID 1448
#define CH3_MAX 1808
 
#define CH4_MIN 1296//208 1264
#define CH4_MID 1472
#define CH4_MAX 1648//176
 
#define CUTFORZERO 3
#define DEGRANGE  45
#define TROTTLERANGE  150
#define WFLYOFFSET 10
 
int pin = 15;
int val;
unsigned long duration;
int storage[4];
int CH1_val, CH2_val, CH3_val, CH4_val;
 
void setup()
{
  Serial.begin(115200);
  pinMode(pin, INPUT);
}
 
void loop()
{
  duration = pulseIn(pin, HIGH, 25000);
  
   if(duration>CH1_val+WFLYOFFSET | duration<CH1_val-WFLYOFFSET)
  CH1_val = duration;
  
  storage[0= map(CH1_val, CH1_MIN, CH1_MAX, (DEGRANGE*-1), DEGRANGE);
 
  if(storage[0>=(CUTFORZERO*-1& storage[0<=CUTFORZERO)
  storage[0]  = 0;
  Serial.println( storage[0] );
  delay(10);
  
}
 
cs



카메라
RF카메라는 아두이노와 전혀 연결되어 있지 않아요.
단지 카메라로 찍은 영상은 아두이노를 거치지 않고 바로 공중으로 전송됩니다.
그러면 컴퓨터에 연결되어 있는 수신기가 영상을 받아 컴퓨터에 띄워줌니다.


'작품 > 쿼드콥터' 카테고리의 다른 글

보드를 바꾼 후 ESC에 400Hz제어를 시도했지만...  (0) 2016.02.08
아두이노 메가2560으로 MCU를 교체하다  (0) 2016.02.08
롤 제어  (0) 2016.02.08
호버링 제어  (0) 2016.02.08
조립 후 테스트  (0) 2016.02.08
:
Posted by youjin.A
2016. 2. 8. 02:29

롤 제어 작품/쿼드콥터2016. 2. 8. 02:29

쿼드 콥터는 X자형이냐 +자형이냐에 따라 제어 방법이 다릅니다.

저는 +자형 쿼드 콥터를 만들기 때문에 롤 제어는 다음과 같이 합니다.

롤 제어 방법은 한 축의 두 개의 모터는 균형을 규지하면서 나머지 다른 축의 모터의 기울기를 통하여 비행하는 기울기를 결정합니다.



제가 테스트한 동영상의 방법은 일단 무선 조종기가 없었기 때문에 아두이노 IDE에서 시리얼 디버깅 창을 띄워놓고

한 쪽 축의 목표 기울기 값을 컴퓨터를 통하여 아두이노에 전송하여 기울기 방향을 정하였습니다.

동영상을 자세히 보면 기체가 한 쪽 방향으로 기울인 뒤 그 방향으로 움직이는 것을 볼 수 있어요.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
#include "SoftwareSerial.h"
#include "Servo.h"
 
/////////////////BLDC Motor/////////////////
#define MAX_THROTTLE 179
#define MIN_THROTTLE 0
#define MAX_PWM 100
#define MIN_PWM 20
#define MOTOR1  //motor pin number
#define MOTOR2  //motor pin number
#define MOTOR3 10  //motor pin number
#define MOTOR4 //motor pin number
 
int motor1Power, motor3Power; // Motors on the X axis
//=>; changing their speeds will affect the pitch
int motor2Power, motor4Power; // Motors on the Y axis
//=>; changing their speeds will affect the roll
  
Servo motor1;
Servo motor2;
Servo motor3;
Servo motor4;
////////////////////////////////////////////
 
 
/////////////////IMU Sensor/////////////////
#define DATANUM 12 //6
#define ACC_X_OFFSET 0.18
#define ACC_Y_OFFSET 0.01
#define ACC_Z_OFFSET -0.77
//IMU Sensor Serial
SoftwareSerial SensorSerial(2,4);//Rx Tx
//IMU Sensor variable
typedef union {
  signed short value;
  unsigned char byte[2];
} S2BYTE;
 
S2BYTE data_word;
 
unsigned char SBuf[100];
int SCnt=0;
double  DegRoll, DegPitch, DegYaw;
double Acc_x, Acc_y, Acc_z;
////////////////////////////////////////////
 
 
/////////////////PID Conrtroll/////////////////
#define MINhover 0
#define INIThover  20
 
#define INITROLLKp 0.38
#define INITROLLKi 0.000287 
#define INITROLLKd 33
 
#define INITPITCHKp 0.29
#define INITPITCHKi 0.000287 
#define INITPITCHKd 33
 
#define INITYAWKp 0.29 //0.38
#define INITYAWKi 0.000287 
#define INITYAWKd 33
 
#define MAXSPEED  3
#define MINSPEED  100
 
#define INITROLLSETPOINT -1.532
#define INITPITCHSETPOINT -0.516
 
 
double roll_setpoint = INITROLLSETPOINT, pitch_setpoint = INITPITCHSETPOINT, yaw_setpoint = 0;
int hover = INIThover;
double roll_Kp = INITROLLKp, roll_Ki = INITROLLKi, roll_Kd = INITROLLKd;
double pitch_Kp = INITPITCHKp, pitch_Ki = INITPITCHKi, pitch_Kd = INITPITCHKd;
double yaw_Kp = INITYAWKp, yaw_Ki = INITYAWKi, yaw_Kd = INITYAWKd;
double roll_p, roll_i, roll_d, roll_val;
double pitch_p, pitch_i, pitch_d, pitch_val;
double yaw_p, yaw_i, yaw_d, yaw_val;
int rollControll, pitchControll, yawControll;
 
int initial = 0;
////////////////////////////////////////////
 
/////////////////Serial Monitor/////////////////
int Serial_print_sig=1;
int roll_print = 1, pitch_print =0, yaw_print=0, hover_print=0;
////////////////////////////////////////////
 
 
//---------------------------------------------------------------------//
//
//                              funtions
//
//--------------------------------------------------------------------//
 
//esc조절 하기
void callibration(void)
{
  
  Serial.println("Calibrate ESC? 'y' or 'n'.");
    
  while (!Serial.available());
  char cali = Serial.read();
  if(cali == 'y'){  
   Serial.println("send max throttle");
    
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MAX_THROTTLE);
    motor2.write(MAX_THROTTLE);
    motor3.write(MAX_THROTTLE);
    motor4.write(MAX_THROTTLE);
   
    delay(5000);
 
    Serial.println("send min throttle");
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
    motor4.write(MIN_THROTTLE);
 
    delay(2000);
    
    Serial.println("callibration complete");
    
  }else if(cali == 'n'){
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
    motor4.write(MIN_THROTTLE);
   
  }
  Serial.println("If you want Program keep going. Press any key.");
  while (!Serial.available());
}
 
//------------------------------------------------------------------------//
//센서값을 읽어서 roll,pitch,yaw 값을 알아낸다.
int recieve_data(void)
{
    static int step_=0, check_all_recieve=0;
    unsigned char data1byte;
    int n;
 
    data1byte = SensorSerial.read();
    
    switch(step_)
    {
        case 0:
           if(data1byte==0x55) {step_=1, check_all_recieve=0;}
        break;
 
        case 1:
           if(data1byte==0x55) { step_=2;  SCnt=0;}
           else step_=0;
        break;
 
        case 2:
           SBuf[SCnt++= (unsigned char)data1byte;
           if(SCnt==DATANUM+2)  // roll(2byte),pitch(2byte),yaw(2byte),checksum(2byte) 
             {   
                step_=0;
                SCnt=0;
                check_all_recieve = 1;
             }
        break;
 
        default:
        break;
     }
   
    return check_all_recieve;
}
 
static int trans_data_to_degree(unsigned char *sdata)  // sdata : roll(2)+pitch(2)+yaw(2)+chk(2)
{
  int n;
  unsigned short chk=0;
 
  ///////////// checksum /////////////////
  chk=0x55+0x55;
  for(n=0;n<DATANUM;n++) chk+=sdata[n]; 
  if(chk != get_data_word(&sdata[DATANUM])) 
  {
    Serial.println("checksum error!");
    return 0//   
  }
  ////////////////////////////////////////
 
  DegRoll  = get_data_word(&sdata[0]) / 100.;
  DegPitch = get_data_word(&sdata[2]) / 100. * -1;
  DegYaw   = get_data_word(&sdata[4]) / 100.;
 
  Acc_x = get_data_word(&sdata[6]) / 100. + ACC_X_OFFSET;
  Acc_y = get_data_word(&sdata[8]) / 100. + ACC_Y_OFFSET;
  Acc_z = get_data_word(&sdata[10]) / 100. + ACC_Z_OFFSET;
 
  return 1;
}
 
static signed short get_data_word(unsigned char *dat)
{
  // little endian..
  data_word.byte[0]=dat[1];  
  data_word.byte[1]=dat[0];  
 
  return data_word.value;
}
 
//--------------------------------------------------------------------------------//
//각도 값을 받아서 PID제어값 출력
double roll_pid(double setpoint, double degree)
{
    double val_out;
    static double roll_p_err_prv, roll_p_err, roll_i_err, roll_d_err;
 
    roll_p_err = setpoint-degree;
    roll_i_err += roll_p_err;
    roll_d_err = roll_p_err - roll_p_err_prv;
    
    roll_p_err_prv = roll_p_err;
    val_out = (roll_Kp*roll_p_err) + (roll_Ki*roll_i_err) + (roll_Kd*roll_d_err);
 
    roll_p = roll_Kp*roll_p_err;
    roll_i = roll_Ki*roll_i_err;
    roll_d = roll_Kd*roll_d_err;
    roll_val = val_out;
    
    return val_out;
}
 
double pitch_pid(double setpoint, double degree)
{
    double val_out;
    static double pitch_p_err_prv, pitch_p_err, pitch_i_err, pitch_d_err;
 
    pitch_p_err = setpoint-degree;
    pitch_i_err += pitch_p_err;
    pitch_d_err = pitch_p_err - pitch_p_err_prv;
    
    pitch_p_err_prv = pitch_p_err;
    val_out = (pitch_Kp*pitch_p_err) + (pitch_Ki*pitch_i_err) + (pitch_Kd*pitch_d_err);
    
    pitch_p = pitch_Kp*pitch_p_err;
    pitch_i = pitch_Ki*pitch_i_err;
    pitch_d = pitch_Kd*pitch_d_err;
    pitch_val = val_out;
    
    return val_out;
}
 
double yaw_pid(double setpoint, double degree)
{
    double val_out;
    static double yaw_p_err_prv, yaw_p_err, yaw_i_err, yaw_d_err;
 
    yaw_p_err = setpoint-degree;
    yaw_i_err += yaw_p_err;
    yaw_d_err = yaw_p_err - yaw_p_err_prv;
    
    yaw_p_err_prv = yaw_p_err;
    val_out = (yaw_Kp*yaw_p_err) + (yaw_Ki*yaw_i_err) + (yaw_Kd*yaw_d_err);
    
    yaw_p = yaw_Kp*yaw_p_err;
    yaw_i = yaw_Ki*yaw_i_err;
    yaw_d = yaw_Kd*yaw_d_err;
    yaw_val = val_out;
    
    return val_out;
}
//------------------------------------------------------------------------
//제어값을 받어서 모터 구동
void run_motors(int throttle, int rollOffset, int pitchOffset, int yawOffset)
{
  motor1Power = throttle + pitchOffset - yawOffset;
  motor2Power = throttle + rollOffset + yawOffset;
  motor3Power = throttle - pitchOffset  - yawOffset;
  motor4Power = throttle - rollOffset + yawOffset;
  
  limit_max_min(motor1Power);
  limit_max_min(motor2Power);
  limit_max_min(motor3Power);
  limit_max_min(motor4Power);
 
  motor1.write(motor1Power);motor3.write(motor3Power);
  motor2.write(motor2Power);motor4.write(motor4Power);
}
 
void limit_max_min(int pwm)
{
  if(pwm>MAX_PWM)
  pwm = MAX_PWM;
  else if(pwm<MIN_PWM)
  pwm = MIN_PWM;
}
//-------------------------------------------------------------------------------//
void Serial_Monitor(void)
{
  if(Serial_print_sig ==){
    if(roll_print == 1){
      Serial.print("Roll=> ");Serial.print(DegRoll);Serial.print(", ");Serial.print(roll_p); Serial.print(", ");Serial.print(roll_i); Serial.print(", ");Serial.print(roll_d);Serial.print(", ");Serial.print(roll_val);Serial.print(", ");Serial.print(motor2Power);Serial.print(", ");Serial.println(motor4Power);
    }else if(pitch_print == 1){
      Serial.print("Pitch=> ");Serial.print(DegPitch);Serial.print(", ");Serial.print(pitch_p); Serial.print(", ");Serial.print(pitch_i); Serial.print(", ");Serial.print(pitch_d);Serial.print(", ");Serial.print(pitch_val);Serial.print(", ");Serial.print(motor1Power);Serial.print(", ");Serial.println(motor3Power);
    }else if(yaw_print == 1){
      Serial.print("Yaw=> ");Serial.print(DegYaw);Serial.print(", ");Serial.print(yaw_p); Serial.print(", ");Serial.print(yaw_i); Serial.print(", ");Serial.print(yaw_d);Serial.print(", ");Serial.println(yaw_val); 
    }
  } 
 
  if(Serial_print_sig == 0){
    if(hover_print == 1){
      Serial.print("hover = ");Serial.println(hover);
      hover_print =0;
    }else if(roll_print == 1){
      Serial.print("roll_Kp = ");Serial.print(roll_Kp);Serial.print(", roll_Ki = ");Serial.print(roll_Ki*10000);Serial.print(", roll_Kd = ");Serial.println(roll_Kd);
      roll_print = 0;
    }else if(pitch_print == 1){
      Serial.print("pitch_Kp = ");Serial.print(pitch_Kp);Serial.print(", pitch_Ki = ");Serial.print(pitch_Ki*10000);Serial.print(", pitch_Kd = ");Serial.println(pitch_Kd);
      pitch_print = 0;
    }else if(yaw_print == 1){
      Serial.print("yaw_Kp = ");Serial.print(yaw_Kp);Serial.print(", yaw_Ki = ");Serial.print(yaw_Ki*10000);Serial.print(", yaw_Kd = ");Serial.println(yaw_Kd);
      yaw_print = 0;
    }
  }
}
 
//------------------------------------------------------------------------------//
void from_computer(void)
{
    char c = Serial.read();
    //hover debuging
    if(c=='1'){
      hover += 1;
      Serial.print("hover = ");Serial.println(hover);
    }else if(c=='2'){
      hover -= 1;
      Serial.print("hover = ");Serial.println(hover);
    }else if(c=='3'){
      hover= INIThover;
      Serial.print("hover = ");Serial.println(hover);
    }else if(c=='4'){
      hover= MINhover;
      Serial.print("hover = ");Serial.println(hover);
    }else if(c=='5'){
      roll_setpoint += 0.1;
      Serial.print("roll_setpoint = ");Serial.println(roll_setpoint);
    }else if(c=='6'){
      roll_setpoint -= 0.1;
      Serial.print("roll_setpoint = ");Serial.println(roll_setpoint);
    }else if(c=='7'){
      roll_setpoint = INITROLLSETPOINT;
      Serial.print("roll_setpoint = ");Serial.println(roll_setpoint);
    }
 
    
    
    //roll debuging
    else if(c=='q'){
      roll_Kp += 0.01;
      Serial.print("roll_Kp = ");Serial.println(roll_Kp);
    }else if(c=='w'){
      roll_Kp -= 0.01;
      Serial.print("roll_Kp = ");Serial.println(roll_Kp);
    }else if(c=='e'){
      roll_Kp= INITROLLKp;
      Serial.print("roll_Kp = ");Serial.println(roll_Kp);
    }else if(c=='a'){
      roll_Ki += 0.000001;
      Serial.print("roll_Ki = ");Serial.println(roll_Ki*10000);
    }else if(c=='s'){
      roll_Ki -= 0.000001;
      Serial.print("roll_Ki = ");Serial.println(roll_Ki*10000);
    }else if(c=='d'){
      roll_Ki = INITROLLKi;
      Serial.print("roll_Ki = ");Serial.println(roll_Ki*10000);
    }else if(c=='z'){
      roll_Kd += 1;
      Serial.print("roll_Kd = ");Serial.println(roll_Kd);
    }else if(c=='x'){
      roll_Kd -= 1;
      Serial.print("roll_Kd = ");Serial.println(roll_Kd);
    }else if(c=='c'){
      roll_Kd = INITROLLKd;
      Serial.print("roll_Kd = ");Serial.println(roll_Kd);
    }
    
    
    
    //pitch debuging
    else if(c=='r'){
      pitch_Kp += 0.01;
      Serial.print("pitch_Kp = ");Serial.println(pitch_Kp);
    }else if(c=='t'){
      pitch_Kp -= 0.01;
      Serial.print("pitch_Kp = ");Serial.println(pitch_Kp);
    }else if(c=='y'){
      pitch_Kp= INITPITCHKp;
      Serial.print("pitch_Kp = ");Serial.println(pitch_Kp);
    }else if(c=='f'){
      pitch_Ki += 0.000001;
      Serial.print("pitch_Ki = ");Serial.println(pitch_Ki*10000);
    }else if(c=='g'){
      pitch_Ki -= 0.000001;
      Serial.print("pitch_Ki = ");Serial.println(pitch_Ki*10000);
    }else if(c=='h'){
      pitch_Ki = INITPITCHKi;
      Serial.print("pitch_Ki = ");Serial.println(pitch_Ki*10000);
    }else if(c=='v'){
      pitch_Kd += 1;
      Serial.print("pitch_Kd = ");Serial.println(pitch_Kd);
    }else if(c=='b'){
      pitch_Kd -= 1;
      Serial.print("pitch_Kd = ");Serial.println(pitch_Kd);
    }else if(c=='n'){
      pitch_Kd = INITPITCHKd;
      Serial.print("pitch_Kd = ");Serial.println(pitch_Kd);
    }
 
    //yaw debuging
    else if(c=='u'){
      yaw_Kp += 0.01;
      Serial.print("yaw_Kp = ");Serial.println(yaw_Kp);
    }else if(c=='i'){
      yaw_Kp -= 0.01;
      Serial.print("yaw_Kp = ");Serial.println(yaw_Kp);
    }else if(c=='o'){
      yaw_Kp= INITYAWKp;
      Serial.print("yaw_Kp = ");Serial.println(yaw_Kp);
    }else if(c=='j'){
      yaw_Ki += 0.000001;
      Serial.print("yaw_Ki = ");Serial.println(yaw_Ki*10000);
    }else if(c=='k'){
      yaw_Ki -= 0.000001;
      Serial.print("yaw_Ki = ");Serial.println(yaw_Ki*10000);
    }else if(c=='l'){
      yaw_Ki = INITYAWKi;
      Serial.print("yaw_Ki = ");Serial.println(yaw_Ki*10000);
    }else if(c=='m'){
      yaw_Kd += 1;
      Serial.print("yaw_Kd = ");Serial.println(yaw_Kd);
    }else if(c==','){
      yaw_Kd -= 1;
      Serial.print("yaw_Kd = ");Serial.println(yaw_Kd);
    }else if(c=='.'){
      yaw_Kd = INITYAWKd;
      Serial.print("yaw_Kd = ");Serial.println(yaw_Kd);
    }
 
    else if(c=='p'){
      Serial_print_sig = !(Serial_print_sig);
    }else if(c=='/'){
      roll_print = !(roll_print);
    }else if(c=='*'){
      pitch_print = !(pitch_print);
    }else if(c=='-'){
      yaw_print = !(yaw_print);
    }else if(c=='+'){
      hover_print = !(hover_print);
    }
    
}
 
//---------------------------------------------------------------------//
//
//                                main
//
//--------------------------------------------------------------------//
void setup() {
  Serial.begin(115200); 
  SensorSerial.begin(57600); 
  callibration();
}
 
void loop() {
 
  
  if(SensorSerial.available()){ //데이터 받기.
   if(recieve_data()==1)  //데이터 다 받음?
   {   
     if(trans_data_to_degree(SBuf)==1//센서값. 
     {
      if(initial == 0){
      yaw_setpoint = DegYaw;
      initial = 1;
      //Serial.println(yaw_setpoint);
      }
             
       rollControll = roll_pid(roll_setpoint, DegRoll); //PID.
       pitchControll = pitch_pid(pitch_setpoint, DegPitch);
       yawControll = yaw_pid(yaw_setpoint, DegYaw);
    
       run_motors(hover, rollControll, pitchControll, yawControll); //MOTOR
 
       //Serial_Monitor(); //Serial.print.
       Serial.print(Acc_x);Serial.print(", ");Serial.print(Acc_y);Serial.print(", ");Serial.println(Acc_y);
      }
    } 
  }
 
   if(Serial.available()){ //통신입력?
    from_computer(); //입력받기.
   }
}
 
 
 
cs



'작품 > 쿼드콥터' 카테고리의 다른 글

아두이노 메가2560으로 MCU를 교체하다  (0) 2016.02.08
무선 조종기와 카메라 테스트  (0) 2016.02.08
호버링 제어  (0) 2016.02.08
조립 후 테스트  (0) 2016.02.08
하드웨어 조립  (0) 2016.02.08
:
Posted by youjin.A
2016. 2. 8. 02:06

호버링 제어 작품/쿼드콥터2016. 2. 8. 02:06

1. PID 테스트

날개 4개 중에서 한 축인 2개의 모터만 돌려서 우선 균형을 잡을 수 있는 지 PID 테스트를 해보았습니다.

PID 제어란 목표인 입력값과 현재 상태인 결과 사이의 차이(Error)에 비례, 적분, 미분의 기법을 써서 구동부를 제어하는 방법입니다.

기본적인 PID 제어 방법과 코드는 아래와 같아요.


기초: PID 제어


#define Kp (2) // configurable value.

#define Ki (1) // configurable value.

#define Kd (1) // configurable value.

#define dt   0.01



double pid(int degree)

{

 static double P_err_prv; // Prev P error to get D_err.

 double P_err, I_err, D_err; // Basic Error values.


 P_err = SETPOINT - degree;

 I_err += P_err * dt;

 D_err = (P_err - P_err_prv) / dt;


 P_err_prv = P_err; // backup P_err.

 val_out = (Kp * P_err) + (Ki * I_err) + (Kd * D_err);

 return val_out; // Calculated.

}


균형을 잡는 지 저희 쿼드콥터로 테스트 하기 위해서 디버깅 환경을 다음과 같이 꾸몄습니다.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#include "SoftwareSerial.h"
#include "Servo.h"
 
/////////////////BLDC Motor/////////////////
#define MAX_THROTTLE 179
#define MIN_THROTTLE 0
#define MAX_PWM 100
#define MIN_PWM 20
#define MOTOR0  //motor pin number
#define MOTOR1  //motor pin number
#define MOTOR2 10  //motor pin number
#define MOTOR3 //motor pin number
 
Servo motor0;
Servo motor1;
Servo motor2;
Servo motor3;
int mspeed=0;
int pwm=0, Cpwm=0;
////////////////////////////////////////////
 
 
/////////////////IMU Sensor/////////////////
//IMU Sensor Serial
SoftwareSerial SensorSerial(2,4);//Rx Tx
//IMU Sensor variable
char data[40];
int i = 0;
double  roll, pitch, yaw;
////////////////////////////////////////////
 
 
/////////////////PID Conrtroll/////////////////
#define SETPOINT  0
#define INITfitpoint  30
#define INITKp  0.38
#define INITKi 0.000287
#define INITKd 33
#define MAXSPEED  3
#define MINSPEED  100
 
int fitpoint = INITfitpoint;
double Kp = INITKp, Ki = INITKi, Kd = INITKd;
double last_t;
////////////////////////////////////////////
 
 
//---------------------------------------------------------------------//
//
//                              funtions
//
//--------------------------------------------------------------------//
 
//esc조절 하기
void callibration(void)
{
  
  Serial.println("Calibrate ESC? 'y' or 'n'.");
    
  while (!Serial.available());
  char cali = Serial.read();
  if(cali == 'y'){  
    Serial.println("send max throttle");
    
    motor0.attach(MOTOR0);
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor0.write(MAX_THROTTLE);
    motor1.write(MAX_THROTTLE);
    motor2.write(MAX_THROTTLE);
    motor3.write(MAX_THROTTLE);
   
    delay(4000);
 
     Serial.println("send min throttle");
    motor0.attach(MOTOR0);
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor0.write(MIN_THROTTLE);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
 
    delay(2000);
    
    Serial.println("callibration complete");
    
  }else if(cali == 'n'){
    motor0.attach(MOTOR0);
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor0.write(MIN_THROTTLE);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
   
  }
  Serial.println("If you want Program keep going. Press any key.");
  while (!Serial.available());
}
 
//------------------------------------------------------------------------//
//센서값을 읽어서 roll,pitch,yaw 값을 알아낸다.
//IMU 센서에서 받아온 아스키코드 값을 잘라서 숫자로 저장하는 함수
//trans_ascii_to_num(저장할 버퍼 배열, 롤값 저장할 변수, 피치값 저장할 변수, 요값 저장할 변수)
void trans_ascii_to_num(char * SBuf, double * roll_ptr, double * pitch_ptr, double * yaw_ptr)
{  
  int value, value2;
  
  value=FindComma(SBuf);// ',' 위치(인덱스 값)을 반환?
  SBuf[value]='\0';// ','를 NULL(\0)값으로 바꾸어주어 하나의 스트링배열로 만들어주는듯?(NULL은 스트링의 마지막 값이니까)
  *roll_ptr=atof(SBuf); 
  //atof()는 스트링을 double형으로 바꾸어주는 함수, 소수점도 알아서 인식하고 바꾸어준다.
        
  value++;
  value2=FindComma(&SBuf[value]);
  SBuf[value+value2]='\0';
  *pitch_ptr=atof(&SBuf[value]);
    
  value=value+value2+1;
  value2=FindComma(&SBuf[value]);
  SBuf[value+value2]='\0';
  *yaw_ptr=atof(&SBuf[value]);
 
}
 
int FindComma(char * buf)
{
   int n;
   for(n=0;n<40;n++)
    {
     if(buf[n]==','break;
    }
 
   return n;
}
 
//--------------------------------------------------------------------------------//
//각도 값을 받아서 PID제어값 출력
double pid(double degree)
{
    double val_out;
    static double p_err_prv, p_err, i_err, d_err;
 
    p_err = SETPOINT-degree;
    i_err += p_err;
    d_err = p_err - p_err_prv;
    
    p_err_prv = p_err;
    val_out = (Kp*p_err) + (Ki*i_err) + (Kd*d_err);
    
    Serial.print((Kp*p_err)); Serial.print(", ");Serial.print((Ki*i_err)); Serial.print(", ");Serial.print((Kd*d_err));Serial.print(", ");Serial.print(val_out); 
    return val_out;
}
 
//------------------------------------------------------------------------
//제어값을 받어서 모터 구동
void run_motors(int speed1, int speed2)
{
  pwm = speed1 + speed2; 
  Cpwm = speed1 - speed2;
  
  if(pwm>MAX_PWM)
  pwm = MAX_PWM;
  else if(pwm<MIN_PWM)
  pwm = MIN_PWM;
 
  if(Cpwm>MAX_PWM)
  Cpwm = MAX_PWM;
  else if(Cpwm<MIN_PWM)
  Cpwm = MIN_PWM;
 
  motor1.write(pwm); 
  motor3.write(Cpwm);
 
  Serial.print(", ");Serial.print(pwm);Serial.print(", ");Serial.print(Cpwm);Serial.println("");
}
 
//------------------------------------------------------------------------------//
//pid 계수의 값을 바꾼다.
void modify_pid_val(void)
{
   if(Serial.available()){
    char c = Serial.read();
    if(c=='r'){
      fitpoint += 1;
      Serial.print("fitpoint = ");Serial.println(fitpoint);
    }else if(c=='t'){
      fitpoint -= 1;
      Serial.print("fitpoint = ");Serial.println(fitpoint);
    }else if(c=='y'){
      fitpoint= INITfitpoint;
      Serial.print("fitpoint = ");Serial.println(fitpoint);
    }else if(c=='q'){
      Kp += 0.01;
      Serial.print("Kp = ");Serial.println(Kp);
    }else if(c=='w'){
      Kp -= 0.01;
      Serial.print("Kp = ");Serial.println(Kp);
    }else if(c=='e'){
      Kp= INITKp;
      Serial.print("Kp = ");Serial.println(Kp);
    }else if(c=='a'){
      Ki += 0.000001;
      Serial.print("Ki = ");Serial.println(Ki*10000);
    }else if(c=='s'){
      Ki -= 0.000001;
      Serial.print("Ki = ");Serial.println(Ki*10000);
    }else if(c=='d'){
      Ki = INITKi;
      Serial.print("Ki = ");Serial.println(Ki*10000);
    }else if(c=='z'){
      Kd += 1;
      Serial.print("Kd = ");Serial.println(Kd);
    }else if(c=='x'){
      Kd -= 1;
      Serial.print("Kd = ");Serial.println(Kd);
    }else if(c=='c'){
      Kd = INITKd;
      Serial.print("Kd = ");Serial.println(Kd);
    }else if(c=='p'){
      Serial.print("Kp = ");Serial.print(Kp);Serial.print(", Ki = ");Serial.print(Ki*10000);Serial.print(", Kd = ");Serial.println(Kd);   
    }
  } 
}
 
//---------------------------------------------------------------------//
//
//                                main
//
//--------------------------------------------------------------------//
void setup() {
  Serial.begin(115200); 
  SensorSerial.begin(57600); 
  callibration();
}
 
void loop() {
  if(SensorSerial.available()){
    data[i]= SensorSerial.read();
    i++;
   
    if(data[i-1== 0x0A)
    data[i-1= ',';
    
    if(data[i-1== '*'){//데이터 다받음.
     i=0;
     
     trans_ascii_to_num(data, &roll, &pitch, &yaw);//센서값을 읽어서 roll,pitch,yaw 값을 알아낸다. 
     Serial.print(roll);Serial.print(", ");
     mspeed = pid(roll);//각도 값을 받아서 PID제어값 출력
     run_motors(fitpoint, mspeed);//제어값을 받어서 모터 구동
     
    }
   }
 
    modify_pid_val();
}
  
 
cs



2. 호버링 제어

다음으로 위의 PID 코드를 수정하여 두 축의 균형을 잡을 수 있도록 소스를 수정 한 후 모터 4개를 모두 돌려서 테스트 하였습니다.

기체가 균형을 잡는지, 공중에 뜨는 지를 확인 하였는데 생각보다 안정적이지 않았습니다.






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#include "SoftwareSerial.h"
#include "Servo.h"
 
/////////////////BLDC Motor/////////////////
#define MAX_THROTTLE 179
#define MIN_THROTTLE 0
#define MAX_PWM 100
#define MIN_PWM 20
#define MOTOR1  //motor pin number
#define MOTOR2  //motor pin number
#define MOTOR3 10  //motor pin number
#define MOTOR4 //motor pin number
 
Servo motor1;
Servo motor2;
Servo motor3;
Servo motor4;
////////////////////////////////////////////
 
 
/////////////////IMU Sensor/////////////////
//IMU Sensor Serial
SoftwareSerial SensorSerial(2,4);//Rx Tx
//IMU Sensor variable
typedef union {
  signed short value;
  unsigned char byte[2];
} S2BYTE;
 
S2BYTE data_word;
 
unsigned char SBuf[100];
int SCnt=0;
double  DegRoll, DegPitch, DegYaw;
////////////////////////////////////////////
 
 
/////////////////PID Conrtroll/////////////////
#define MINhover 0
#define INIThover  20
 
#define INITROLLKp 0.38
#define INITROLLKi 0.000287 
#define INITROLLKd 33
 
#define INITPITCHKp 0.29
#define INITPITCHKi 0.000287 
#define INITPITCHKd 33
 
#define INITYAWKp 0.29 //0.38
#define INITYAWKi 0.000287 
#define INITYAWKd 33
 
#define MAXSPEED  3
#define MINSPEED  100
 
#define INITROLLSETPOINT -1.532
#define INITPITCHSETPOINT -0.516
 
 
double roll_setpoint = INITROLLSETPOINT, pitch_setpoint = INITPITCHSETPOINT, yaw_setpoint = 0;
int hover = INIThover;
double roll_Kp = INITROLLKp, roll_Ki = INITROLLKi, roll_Kd = INITROLLKd;
double pitch_Kp = INITPITCHKp, pitch_Ki = INITPITCHKi, pitch_Kd = INITPITCHKd;
double yaw_Kp = INITYAWKp, yaw_Ki = INITYAWKi, yaw_Kd = INITYAWKd;
int rollControll, pitchControll, yawControll;
 
int initial = 0;
////////////////////////////////////////////
 
 
//---------------------------------------------------------------------//
//
//                              funtions
//
//--------------------------------------------------------------------//
 
//esc조절 하기
void callibration(void)
{
  
  Serial.println("Calibrate ESC? 'y' or 'n'.");
    
  while (!Serial.available());
  char cali = Serial.read();
  if(cali == 'y'){  
   Serial.println("send max throttle");
    
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MAX_THROTTLE);
    motor2.write(MAX_THROTTLE);
    motor3.write(MAX_THROTTLE);
    motor4.write(MAX_THROTTLE);
   
    delay(5000);
 
    Serial.println("send min throttle");
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
    motor4.write(MIN_THROTTLE);
 
    delay(2000);
    
    Serial.println("callibration complete");
    
  }else if(cali == 'n'){
    motor1.attach(MOTOR1);
    motor2.attach(MOTOR2);
    motor3.attach(MOTOR3);
    motor4.attach(MOTOR4);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
    motor4.write(MIN_THROTTLE);
   
  }
  Serial.println("If you want Program keep going. Press any key.");
  while (!Serial.available());
}
 
//------------------------------------------------------------------------//
//센서값을 읽어서 roll,pitch,yaw 값을 알아낸다.
int recieve_data(void)
{
    static int step_=0, check_all_recieve=0;
    unsigned char data1byte;
    int n;
 
    data1byte = SensorSerial.read();
    
    switch(step_)
    {
        case 0:
           if(data1byte==0x55) {step_=1, check_all_recieve=0;}
        break;
 
        case 1:
           if(data1byte==0x55) { step_=2;  SCnt=0;}
           else step_=0;
        break;
 
        case 2:
           SBuf[SCnt++= (unsigned char)data1byte;
           if(SCnt==8)  // roll(2byte),pitch(2byte),yaw(2byte),checksum(2byte) 
             {   
                step_=0;
                SCnt=0;
                check_all_recieve = 1;
             }
        break;
 
        default:
        break;
     }
   
    return check_all_recieve;
}
 
static int trans_data_to_degree(unsigned char *sdata)  // sdata : roll(2)+pitch(2)+yaw(2)+chk(2)
{
  int n;
  unsigned short chk=0;
 
  ///////////// checksum /////////////////
  chk=0x55+0x55;
  for(n=0;n<6;n++) chk+=sdata[n]; 
  if(chk != get_data_word(&sdata[6])) 
  {
    Serial.println("checksum error!");
    return 0//   
  }
  ////////////////////////////////////////
 
  DegRoll  = get_data_word(&sdata[0]) / 100.;
  DegPitch = get_data_word(&sdata[2]) / 100. * -1;
  DegYaw   = get_data_word(&sdata[4]) / 100.;
 
  return 1;
}
 
static signed short get_data_word(unsigned char *dat)
{
  // little endian..
  data_word.byte[0]=dat[1];  
  data_word.byte[1]=dat[0];  
 
  return data_word.value;
}
 
//--------------------------------------------------------------------------------//
//각도 값을 받아서 PID제어값 출력
double roll_pid(double setpoint, double degree)
{
    double val_out;
    static double roll_p_err_prv, roll_p_err, roll_i_err, roll_d_err;
 
    roll_p_err = setpoint-degree;
    roll_i_err += roll_p_err;
    roll_d_err = roll_p_err - roll_p_err_prv;
    
    roll_p_err_prv = roll_p_err;
    val_out = (roll_Kp*roll_p_err) + (roll_Ki*roll_i_err) + (roll_Kd*roll_d_err);
    
    Serial.print((roll_Kp* roll_p_err)); Serial.print(", ");Serial.print((roll_Ki* roll_i_err)); Serial.print(", ");Serial.print((roll_Kd* roll_d_err));Serial.print(", ");Serial.print(val_out); 
    return val_out;
}
 
double pitch_pid(double setpoint, double degree)
{
    double val_out;
    static double pitch_p_err_prv, pitch_p_err, pitch_i_err, pitch_d_err;
 
    pitch_p_err = setpoint-degree;
    pitch_i_err += pitch_p_err;
    pitch_d_err = pitch_p_err - pitch_p_err_prv;
    
    pitch_p_err_prv = pitch_p_err;
    val_out = (pitch_Kp*pitch_p_err) + (pitch_Ki*pitch_i_err) + (pitch_Kd*pitch_d_err);
    
    //Serial.print((pitch_Kp* pitch_p_err)); Serial.print(", ");Serial.print((pitch_Ki* pitch_i_err)); Serial.print(", ");Serial.print((pitch_Kd* pitch_d_err));Serial.print(", ");Serial.print(val_out); 
    return val_out;
}
 
double yaw_pid(double setpoint, double degree)
{
    double val_out;
    static double yaw_p_err_prv, yaw_p_err, yaw_i_err, yaw_d_err;
 
    yaw_p_err = setpoint-degree;
    yaw_i_err += yaw_p_err;
    yaw_d_err = yaw_p_err - yaw_p_err_prv;
    
    yaw_p_err_prv = yaw_p_err;
    val_out = (yaw_Kp*yaw_p_err) + (yaw_Ki*yaw_i_err) + (yaw_Kd*yaw_d_err);
    
    //Serial.print((yaw_Kp*yaw_p_err)); Serial.print(", ");Serial.print((yaw_Ki*yaw_i_err)); Serial.print(", ");Serial.print((yaw_Kd*yaw_d_err));Serial.print(", ");Serial.print(val_out); 
    return val_out;
}
//------------------------------------------------------------------------
//제어값을 받어서 모터 구동
void run_motors(int throttle, int rollOffset, int pitchOffset, int yawOffset)
{
  int motor1Power, motor3Power; // Motors on the X axis
  //=>; changing their speeds will affect the pitch
  int motor2Power, motor4Power; // Motors on the Y axis
  //=>; changing their speeds will affect the roll
 
  motor1Power = throttle + pitchOffset - yawOffset;
  motor2Power = throttle + rollOffset + yawOffset;
  motor3Power = throttle - pitchOffset  - yawOffset;
  motor4Power = throttle - rollOffset + yawOffset;
  
  limit_max_min(motor1Power);
  limit_max_min(motor2Power);
  limit_max_min(motor3Power);
  limit_max_min(motor4Power);
 
  motor1.write(motor1Power);motor3.write(motor3Power);
  motor2.write(motor2Power);motor4.write(motor4Power);
 
  //Serial.print(", ");Serial.print(motor1Power);Serial.print(", ");Serial.print(motor3Power);
  Serial.print(", ");Serial.print(motor2Power);Serial.print(", ");Serial.print(motor4Power);
}
 
void limit_max_min(int pwm)
{
  if(pwm>MAX_PWM)
  pwm = MAX_PWM;
  else if(pwm<MIN_PWM)
  pwm = MIN_PWM;
}
//------------------------------------------------------------------------------//
//pid 계수의 값을 바꾼다.
void modify_pid_val(void)
{
   if(Serial.available()){
    
    char c = Serial.read();
    //hover debuging
    if(c=='1'){
      hover += 1;
      Serial.print("hover = ");Serial.println(hover);
    }else if(c=='2'){
      hover -= 1;
      Serial.print("hover = ");Serial.println(hover);
    }else if(c=='3'){
      hover= INIThover;
      Serial.print("hover = ");Serial.println(hover);
    }else if(c=='4'){
      hover= MINhover;
      Serial.print("hover = ");Serial.println(hover);
    }
    
    
    //roll debuging
    else if(c=='q'){
      roll_Kp += 0.01;
      Serial.print("roll_Kp = ");Serial.println(roll_Kp);
    }else if(c=='w'){
      roll_Kp -= 0.01;
      Serial.print("roll_Kp = ");Serial.println(roll_Kp);
    }else if(c=='e'){
      roll_Kp= INITROLLKp;
      Serial.print("roll_Kp = ");Serial.println(roll_Kp);
    }else if(c=='a'){
      roll_Ki += 0.000001;
      Serial.print("roll_Ki = ");Serial.println(roll_Ki*10000);
    }else if(c=='s'){
      roll_Ki -= 0.000001;
      Serial.print("roll_Ki = ");Serial.println(roll_Ki*10000);
    }else if(c=='d'){
      roll_Ki = INITROLLKi;
      Serial.print("roll_Ki = ");Serial.println(roll_Ki*10000);
    }else if(c=='z'){
      roll_Kd += 1;
      Serial.print("roll_Kd = ");Serial.println(roll_Kd);
    }else if(c=='x'){
      roll_Kd -= 1;
      Serial.print("roll_Kd = ");Serial.println(roll_Kd);
    }else if(c=='c'){
      roll_Kd = INITROLLKd;
      Serial.print("roll_Kd = ");Serial.println(roll_Kd);
    }
    
    
    
    //pitch debuging
    else if(c=='r'){
      pitch_Kp += 0.01;
      Serial.print("pitch_Kp = ");Serial.println(pitch_Kp);
    }else if(c=='t'){
      pitch_Kp -= 0.01;
      Serial.print("pitch_Kp = ");Serial.println(pitch_Kp);
    }else if(c=='y'){
      pitch_Kp= INITPITCHKp;
      Serial.print("pitch_Kp = ");Serial.println(pitch_Kp);
    }else if(c=='f'){
      pitch_Ki += 0.000001;
      Serial.print("pitch_Ki = ");Serial.println(pitch_Ki*10000);
    }else if(c=='g'){
      pitch_Ki -= 0.000001;
      Serial.print("pitch_Ki = ");Serial.println(pitch_Ki*10000);
    }else if(c=='h'){
      pitch_Ki = INITPITCHKi;
      Serial.print("pitch_Ki = ");Serial.println(pitch_Ki*10000);
    }else if(c=='v'){
      pitch_Kd += 1;
      Serial.print("pitch_Kd = ");Serial.println(pitch_Kd);
    }else if(c=='b'){
      pitch_Kd -= 1;
      Serial.print("pitch_Kd = ");Serial.println(pitch_Kd);
    }else if(c=='n'){
      pitch_Kd = INITPITCHKd;
      Serial.print("pitch_Kd = ");Serial.println(pitch_Kd);
    }
 
    //yaw debuging
    else if(c=='u'){
      yaw_Kp += 0.01;
      Serial.print("yaw_Kp = ");Serial.println(yaw_Kp);
    }else if(c=='i'){
      yaw_Kp -= 0.01;
      Serial.print("yaw_Kp = ");Serial.println(yaw_Kp);
    }else if(c=='o'){
      yaw_Kp= INITYAWKp;
      Serial.print("yaw_Kp = ");Serial.println(yaw_Kp);
    }else if(c=='j'){
      yaw_Ki += 0.000001;
      Serial.print("yaw_Ki = ");Serial.println(yaw_Ki*10000);
    }else if(c=='k'){
      yaw_Ki -= 0.000001;
      Serial.print("yaw_Ki = ");Serial.println(yaw_Ki*10000);
    }else if(c=='l'){
      yaw_Ki = INITYAWKi;
      Serial.print("yaw_Ki = ");Serial.println(yaw_Ki*10000);
    }else if(c=='m'){
      yaw_Kd += 1;
      Serial.print("yaw_Kd = ");Serial.println(yaw_Kd);
    }else if(c==','){
      yaw_Kd -= 1;
      Serial.print("yaw_Kd = ");Serial.println(yaw_Kd);
    }else if(c=='.'){
      yaw_Kd = INITYAWKd;
      Serial.print("yaw_Kd = ");Serial.println(yaw_Kd);
    }
    
    
  } 
}
 
//---------------------------------------------------------------------//
//
//                                main
//
//--------------------------------------------------------------------//
void setup() {
  Serial.begin(115200); 
  SensorSerial.begin(57600); 
  callibration();
}
 
void loop() {
 
  
  if(SensorSerial.available()){
   if(recieve_data()==1)  //roll(2byte),pitch(2byte),yaw(2byte),checksum(2byte) 모든 데이터 받았음
    {   
     if(trans_data_to_degree(SBuf)==1//센서값을 읽어서 roll,pitch,yaw 값을 알아낸다. 
     {
      if(initial == 0){
      yaw_setpoint = DegYaw;
      initial = 1;
      //Serial.println(yaw_setpoint);
      }
 
       Serial.print(DegRoll);Serial.print(", ");
       //Serial.print(DegPitch);Serial.print(", ");
       //Serial.print(DegYaw); Serial.print(", ");
             
       rollControll = roll_pid(roll_setpoint, DegRoll);//각도 값을 받아서 PID제어값 출력
       pitchControll = pitch_pid(pitch_setpoint, DegPitch);
       yawControll = yaw_pid(yaw_setpoint, DegYaw);
    
       run_motors(hover, rollControll, pitchControll, yawControll);//제어값을 받어서 모터 구동
       Serial.print(", hover = ");Serial.print(hover);
       
       Serial.print(", roll_Kp = ");Serial.print(roll_Kp);Serial.print(", roll_Ki = ");Serial.print(roll_Ki*10000);Serial.print(", roll_Kd = ");Serial.println(roll_Kd);
 
       //Serial.print(", pitch_Kp = ");Serial.print(pitch_Kp);Serial.print(", pitch_Ki = ");Serial.print(pitch_Ki*10000);Serial.print(", pitch_Kd = ");Serial.println(pitch_Kd);
 
       //Serial.print(", yaw_Kp = ");Serial.print(yaw_Kp);Serial.print(", yaw_Ki = ");Serial.print(yaw_Ki*10000);Serial.print(", yaw_Kd = ");Serial.println(yaw_Kd);
      }
    } 
  }
 
 
    modify_pid_val();
}
 
 
 
cs


'작품 > 쿼드콥터' 카테고리의 다른 글

무선 조종기와 카메라 테스트  (0) 2016.02.08
롤 제어  (0) 2016.02.08
조립 후 테스트  (0) 2016.02.08
하드웨어 조립  (0) 2016.02.08
부품 테스트 - 배터리  (0) 2016.02.08
:
Posted by youjin.A
2016. 2. 8. 01:33

조립 후 테스트 작품/쿼드콥터2016. 2. 8. 01:33

아두이노를 넣은 초록색 보드까지 프레임에 장착한 후 모든 모터가 제대로 작동하는 지 테스트 해 보았습니다.

블루투스를 이용하여 각각의 모터를 선택하고 또한 모터의 출력을 높이거나 낮출 수 있도록 하였습니다.



위 동영상의 코드 아래에...

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <SoftwareSerial.h>
 
#define T 20000
#define MOTORNUM 4
 
//PWM : OC0A, OC0B, 
 
//pinNumber:5 , digitalPinNumber:3 , OC2B
//pinNumber:11 , digitalPinNumber:5 , OC0B
//pinNumber:15 , digitalPinNumber:9 , OC1A
//pinNumber:16 , digitalPinNumber:10 , OC2A
 
SoftwareSerial mySerial(13,11);//Rx, Tx 
 
int sig = 140, count = 0;
int ESC[MOTORNUM] = {59103};
char c;
int emergency=0;
int motor_set = 0;
 
void BLDCcont(int object,int val)
{
  digitalWrite(object, HIGH);
  delayMicroseconds(val);
  digitalWrite(object, LOW);
  delayMicroseconds(T-val);
}
 
void BLDCall(int val)
{
  /*
  digitalWrite(ESC[1], HIGH);
  delayMicroseconds(val);
  digitalWrite(ESC[1], LOW);
  digitalWrite(ESC[2], HIGH);
  delayMicroseconds(val);
  digitalWrite(ESC[2], LOW);
  digitalWrite(ESC[0], HIGH);
  delayMicroseconds(val);
  digitalWrite(ESC[0], LOW);
  
  digitalWrite(ESC[3], HIGH);
  delayMicroseconds(val);
  digitalWrite(ESC[3], LOW);
   
  delayMicroseconds(T-(val*4));
  */
 
 
}
  
void setup()  
{
  int i;
  
  for(i=0; i<MOTORNUM; i++)
    pinMode(ESC[i], OUTPUT);
  
  mySerial.begin(115200);//115200 not work
  Serial.begin(115200);
   mySerial.println(sig);
 
 TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
 TCCR0B = _BV(CS01)|_BV(CS00);
 
}
 
void loop() 
{
  if (mySerial.available()){
    
    //read
    c = mySerial.read();
    Serial.println(c);
 
    //motor set?
    if(isdigit(c)){
      motor_set=c-'0';
      sig = 140;
    }
    else{//PWM set?
      if(c == 'u'){
       emergency = 0;
       sig +=10;
       if(sig>180)
          sig = 180;
       mySerial.println(sig);
      }
      else if(c == 'd'){
       emergency = 0;
       sig -=10;
       if(sig<140)
          sig = 140;
        mySerial.println(sig);
      }
      else if(c == 'e'){
       emergency = 1;
      }
    }
  
  }
 
  //emergency
  if(emergency == 1){
    count++;
    if(count == 20){
    sig-=10;
    if(sig<140){
        sig = 140;
        emergency=0;
    }
    mySerial.println(sig);
    count=0;
    }
  }
 
  //output
  if(motor_set == 0)
   analogWrite(ESC[0], sig);
  if(motor_set == 1)
    analogWrite(ESC[1], sig);
  if(motor_set == 2)
   analogWrite(ESC[2], sig);
  if(motor_set == 3)
   analogWrite(ESC[3], sig);
  if(motor_set == 4){
  analogWrite(ESC[0], sig);
  analogWrite(ESC[1], sig);
  analogWrite(ESC[2], sig);
  analogWrite(ESC[3], sig);}
}
cs

 


모터 4개가 동시에 출력되어도 아무 문제가 없었습니다.

그리하여 이번에는 모터가 회전했을 때 힘이 아래방향으로 밀어내도록 모터의 회전 방향을 조정하였습니다.

코드는 위의 코드를 이용하였습니다.





이번에는 모터4개를 동시에 돌리면서 센서를 동작시킬 때 센서에 Roll, Pitch, Yaw 값이 제대로 나오는 지 확인해 보았습니다.

"SerialChart"라는 프로그램을 이용하여 센서의 값을 그래프로 그려서 테스트해 봤는데 

모터와 센서를 동시에 동작시켜도 잘 동작하는 것을 확인할 수 있었습니다.




위 영상의 코드는 아래에..

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#include <SoftwareSerial.h>
 
 
#define T 20000
#define MOTORNUM 4
 
//PWM : OC0A, OC0B, 
 
//pinNumber:5 , digitalPinNumber:3 , OC2B
//pinNumber:11 , digitalPinNumber:5 , OC0B
//pinNumber:15 , digitalPinNumber:9 , OC1A
//pinNumber:16 , digitalPinNumber:10 , OC2A
 
SoftwareSerial bluetoothSerial(13,11);//Rx, Tx 
SoftwareSerial sensorSerial(2,4);//Rx Tx
 
 
int sig = 140, count = 0;
int ESC[MOTORNUM] = {59103};
char c;
int emergency=0;
int motor_set = 0;
char data[40];
int i = 0;
double  roll, pitch, yaw;
 
void printAll(char* ch)
{
  int n;
  
  for(n=0; n<i; n++){
    Serial.print(ch[n]);
  }
    Serial.println("");
}
 
void trans_ascii_to_num(char * SBuf, double * DegRoll, double * DegPitch, double * DegYaw)
{  
  int value, value2;
  
  value=FindComma(SBuf);
  //Serial.print(value);
  SBuf[value]='\0';
  *DegRoll=atof(SBuf);
        
  value++;
  value2=FindComma(&SBuf[value]);
  SBuf[value+value2]='\0';
  *DegPitch=atof(&SBuf[value]);
    
  value=value+value2+1;
  value2=FindComma(&SBuf[value]);
  SBuf[value+value2]='\0';
  *DegYaw=atof(&SBuf[value]);
 
 Serial.print(*DegRoll); Serial.print(", ");Serial.print(*DegPitch); Serial.print(", ");Serial.println(*DegYaw); 
}
 
int FindComma(char * buf)
{
   int n;
   for(n=0;n<40;n++)
    {
     if(buf[n]==','break;
    }
 
   return n;
}
 
void BLDCcont(int object,int val)
{
  digitalWrite(object, HIGH);
  delayMicroseconds(val);
  digitalWrite(object, LOW);
  delayMicroseconds(T-val);
}
 
void BLDCall(int val)
{
  /*
  digitalWrite(ESC[1], HIGH);
  delayMicroseconds(val);
  digitalWrite(ESC[1], LOW);
  digitalWrite(ESC[2], HIGH);
  delayMicroseconds(val);
  digitalWrite(ESC[2], LOW);
  digitalWrite(ESC[0], HIGH);
  delayMicroseconds(val);
  digitalWrite(ESC[0], LOW);
  
  digitalWrite(ESC[3], HIGH);
  delayMicroseconds(val);
  digitalWrite(ESC[3], LOW);
   
  delayMicroseconds(T-(val*4));
  */
 
 
}
  
void setup()  
{
  int i;
  
  for(i=0; i<MOTORNUM; i++)
    pinMode(ESC[i], OUTPUT);
    
  sensorSerial.begin(57600);//115200 not work
  //bluetoothSerial.begin(115200);
 
  Serial.begin(115200);
  
 //bluetoothSerial.println(sig);
 
 TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
 TCCR0B = _BV(CS01)|_BV(CS00);
 
}
 
void loop() 
{
  
 
  if(sensorSerial.available()){
   
    data[i]= sensorSerial.read();
    i++;
   
    if(data[i-1== 0x0A)
      data[i-1= ',';
    
    if(data[i-1== '*'){
     // printAll(data);
      trans_ascii_to_num(data, &roll, &pitch, &yaw);
      i=0;
    }
  }
 
 
  if (Serial.available()){
   
    //read
    c = Serial.read();
    //Serial.println(c);
 
    //motor set?
    if(isdigit(c)){
      motor_set=c-'0';
      sig = 140;
    }
    else{//PWM set?
      if(c == 'u'){
       emergency = 0;
       sig +=10;
       if(sig>180)
          sig = 180;
       //Serial.println(sig);
      }
      else if(c == 'd'){
       emergency = 0;
       sig -=10;
       if(sig<140)
          sig = 140;
        //Serial.println(sig);
      }
      else if(c == 'e'){
       emergency = 1;
      }
    }
  
  }
 
  //emergency
  if(emergency == 1){
    count++;
    if(count == 20){
    sig-=10;
    if(sig<140){
        sig = 140;
        emergency=0;
    }
    //Serial.println(sig);
    count=0;
    }
  }
 
  //output
  if(motor_set == 0)
   analogWrite(ESC[0], sig);
  if(motor_set == 1)
    analogWrite(ESC[1], sig);
  if(motor_set == 2)
   analogWrite(ESC[2], sig);
  if(motor_set == 3)
   analogWrite(ESC[3], sig);
  if(motor_set == 4){
    analogWrite(ESC[0], sig);
    analogWrite(ESC[1], sig);
    analogWrite(ESC[2], sig);
    analogWrite(ESC[3], sig);
  }
}
cs



 

도중에 같은 코드로 동작을 시켰는 데도 모터의 한 쪽 출력이 이상하게 느려지면서 이상해 지는 경우가 있었습니다.

그 원인은 ESC에 배터리를 한번 연결시켜줬을 때 초기에 ESC에 최대PWM과 최소PWM의 범위를 설정하는 단계가 있었는데

저희가 그걸 모르고 그냥 건너 뛴거였죠..

그 단계를 ESC callibration이라고 하는데 callibration을 위한 코드는 아래의 코드를 이용했습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <Servo.h>
 
#define MAX_THROTTLE 179
#define MIN_THROTTLE 0
#define MOTOR0 5
#define MOTOR1 3
#define MOTOR2 9
#define MOTOR3 10
 
Servo motor0;
Servo motor1;
Servo motor2;
Servo motor3;
 
int mspeed;
 
void setup() {
  mspeed = 0;
  
  Serial.begin(115200);
  Serial.println("Program begin...");
  //Serial.println("This program will calibrate the ESC.");
 
  motor0.attach(MOTOR0);
  motor1.attach(MOTOR1);
  motor2.attach(MOTOR2);
  motor3.attach(MOTOR3);
 
  Serial.println("CAUTION!:If YOU STILL CONNECTED BATTERY, NEVER CHOOSE SAY YES!");
  Serial.print("Calibrate ESC? 'y' or 'n'");
  
  while (!Serial.available());
  char cali = Serial.read();
  
  if(cali == 'y'){
    Serial.println("Now writing maximum output.");
    Serial.println("Turn on power source, then wait 2 seconds and press any key.");
    motor0.write(MAX_THROTTLE);
    motor1.write(MAX_THROTTLE);
    motor2.write(MAX_THROTTLE);
    motor3.write(MAX_THROTTLE);
 
    // Wait for input
    while (!Serial.available());
    //Serial.read();
 
    // Send min output
    Serial.println("Sending minimum output");
    motor0.write(MIN_THROTTLE);
    motor1.write(MIN_THROTTLE);
    motor2.write(MIN_THROTTLE);
    motor3.write(MIN_THROTTLE);
 
    Serial.println("When beep on the ESC, Sned any data");
    // Wait for input
    while (!Serial.available());
    //Serial.read();
 
    Serial.println("Finish calibrating the ESC");
  }else {
    Serial.println("Program keep going");
  }
}
 
void loop() { 
  Serial.println(mspeed);
  
  if(Serial.available()){
    char c = Serial.read();
    if(c=='u'){
      mspeed += 1;
      motor0.write(mspeed); motor1.write(mspeed); motor2.write(mspeed); motor3.write(mspeed);
    }else if(c=='d'){
      mspeed -= 1;
      motor0.write(mspeed); motor1.write(mspeed); motor2.write(mspeed); motor3.write(mspeed);
    }else if(c=='e'){
      mspeed = 0;
      motor0.write(mspeed); motor1.write(mspeed); motor2.write(mspeed); motor3.write(mspeed);
    }
  }
}
cs





참고

-아두이노 PWM 제어 레지스터

https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM


-ATMEGA328 DATASHEET

http://www.atmel.com/images/doc8161.pdf


'작품 > 쿼드콥터' 카테고리의 다른 글

롤 제어  (0) 2016.02.08
호버링 제어  (0) 2016.02.08
하드웨어 조립  (0) 2016.02.08
부품 테스트 - 배터리  (0) 2016.02.08
부품테스트 ESC 및 BEC  (0) 2016.02.08
:
Posted by youjin.A