Advertisement
Guest User

Quadcopter code

a guest
Jul 6th, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 10.17 KB | None | 0 0
  1.  
  2. #include "I2Cdev.h"
  3. #include <PID_v1.h>
  4.  
  5. #include "MPU6050_6Axis_MotionApps20.h"
  6.  
  7. #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  8.     #include "Wire.h"
  9. #endif
  10.  
  11. long previousMillis = 0;
  12.  
  13.  
  14. MPU6050 mpu;
  15. #include <string.h> // we'll need this for subString
  16.  
  17. char serialbuf[32]; //This gives the incoming serial some room. Change it if you want a longer incoming.
  18. #define MAX_STRING_LEN 15 // like 3 lines above, change as needed.
  19. int xoff, yoff=0;
  20. const char EOPmarker = '.'; //This is the end of packet marker
  21.  
  22. int throttleFL;;
  23. int throttleFR;
  24. int throttleBL;
  25. int throttleBR;
  26. //Define Variables we'll be connecting to
  27. double Setpoint, Input, Output;
  28. double Setpoint1, Input1, Output1;
  29. double Setpoint2, Input2, Output2;
  30.  
  31. int frontright = 9;
  32. int frontleft = 6;
  33. int rearright = 5;
  34. int rearleft = 10;
  35.  
  36. double accYangle, accXangle, YAngle, XAngle, YawAngle;
  37.  
  38.  
  39.  static int bufpos = 0;
  40. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  41. /* BACKUP
  42. double Kp = 66.3;
  43. double Ki = 1.235;
  44. double Kd = 2.88;
  45. */
  46. //double Kp = 69.3;
  47. //double Ki = 0;
  48. //double Kd = 3.08;
  49.  
  50. //double Kp = 55.3;
  51. //double Ki = 0;
  52. //double Kd = 0;
  53. //
  54. //
  55. //
  56. //
  57. //double Kp1 = 56.8;
  58. //double Ki1 = 0;
  59. //double Kd1 = 0;
  60.  
  61.  
  62. double Kp = 68.3;
  63. double Ki = 1.235;
  64. double Kd = 3.08;
  65.  
  66. double Kp2 = 65.9;
  67. double Ki2 = 0.0;
  68. double Kd2 = 0.01;
  69.  
  70. int   STARTSPEED = 0;
  71. int val=0;
  72. int xang=0;
  73. int yang=0;
  74. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  75.  
  76.  
  77. //Specify the links and initial tuning parameters
  78. PID myPID(&Input, &Output, &Setpoint,Kp,Ki,Kd, REVERSE); //Y axis
  79. PID myPID1(&Input1, &Output1, &Setpoint1,Kp,Ki,Kd, REVERSE); //X axis
  80.  
  81. PID myPID2(&Input2, &Output2, &Setpoint2,Kp2,Ki2,Kd2, REVERSE); //Yaw
  82.  
  83. char inchar;
  84.  
  85.  
  86. // MPU control/status vars
  87. // MPU control/status vars
  88. bool dmpReady = false;  // set true if DMP init was successful
  89. uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
  90. uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
  91. uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
  92. uint16_t fifoCount;     // count of all bytes currently in FIFO
  93. uint8_t fifoBuffer[64]; // FIFO storage buffer
  94.  
  95. // orientation/motion vars
  96. Quaternion q;           // [w, x, y, z]         quaternion container
  97. VectorInt16 aa;         // [x, y, z]            accel sensor measurements
  98. VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
  99. VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
  100. VectorFloat gravity;    // [x, y, z]            gravity vector
  101. float euler[3];         // [psi, theta, phi]    Euler angle container
  102. float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
  103.  
  104. VectorInt16 gyro;       // [x, y, z]            gyroscopic output
  105.  
  106.  
  107. // ================================================================
  108. // ===               INTERRUPT DETECTION ROUTINE                ===
  109. // ================================================================
  110.  
  111. volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
  112. boolean interruptLock = false;
  113.  
  114.  
  115.  
  116.  
  117. // ================================================================
  118. // ===                      INITIAL SETUP                       ===
  119. // ================================================================
  120.  
  121. void setup() {
  122.     Input = (YAngle);
  123.     Input1 = (XAngle);
  124.     Input2 = YawAngle;
  125.  
  126.     Setpoint = 0.0;
  127.     Setpoint1 = 0.0;
  128.     Setpoint2 = 0.0;
  129.  
  130.  
  131.     pinMode(13, OUTPUT);
  132.     pinMode(frontright, OUTPUT);
  133.     pinMode(frontleft, OUTPUT);
  134.     pinMode(rearright, OUTPUT);
  135.     pinMode(rearleft, OUTPUT);
  136.     // initialize serial communication
  137.     // (115200 chosen because it is required for Teapot Demo output, but it's
  138.     // really up to you depending on your project)
  139.      Serial.begin(115200);
  140.  
  141.  
  142.      initMPU();
  143.    
  144.    
  145.     myPID.SetOutputLimits(-90, 90);
  146.     myPID1.SetOutputLimits(-90, 90);
  147.     myPID2.SetOutputLimits(-90, 90);
  148.     myPID.SetMode(AUTOMATIC);
  149.     myPID1.SetMode(AUTOMATIC);
  150.     myPID2.SetMode(AUTOMATIC);
  151.     myPID.SetSampleTime(5);
  152.     myPID1.SetSampleTime(5);
  153.     myPID2.SetSampleTime(5);
  154.     // configure LED for output
  155.     //pinMode(LED_PIN, OUTPUT);
  156. }
  157.  
  158.  
  159.  
  160. // ================================================================
  161. // ===                    MAIN PROGRAM LOOP                     ===
  162. // ==============================//checkcommands==================================
  163. void loop() {
  164.     // if programming failed, don't try to do anything
  165.     getYPR();
  166.          
  167.   //Serial.print(ypr[2]);
  168.   //Serial.print('\t');
  169.   //Serial.print(ypr[1]);
  170.   //Serial.print('\t');
  171.   //Serial.print(ypr[0]);
  172.   //Serial.print('\t');
  173.   //Serial.print(gyro.x);
  174.   //Serial.println();
  175.     YAngle = (ypr[1]);
  176.     XAngle = (ypr[2]);
  177.     YawAngle = ypr[0];
  178.  
  179.     checkcommands();
  180.  
  181.     Input = YAngle;
  182.     Input1 = XAngle;
  183.     Input2 = YawAngle;
  184.  
  185.  
  186.     myPID.Compute();
  187.     myPID1.Compute();
  188.     myPID2.Compute();
  189.                
  190.  
  191.     throttleFR = constrain((val + Output + Output1 - Output2 - xang + yang), 0, 255);
  192.     throttleBR = constrain((val + Output - Output1 + Output2 - xang - yang), 0, 255);
  193.     throttleFL = constrain((val - Output + Output1 + Output2 + xang + yang), 0, 255);
  194.     throttleBL = constrain((val - Output - Output1 - Output2 + xang - yang), 0, 255);
  195.  
  196.     analogWrite(frontright, throttleFR);  
  197.     analogWrite(frontleft, throttleFL);  
  198.     analogWrite(rearright, throttleBR);  
  199.     analogWrite(rearleft, throttleBL);  
  200.  
  201. //    
  202. // DEBUG sensors and PID vals
  203. //    Serial.print("Y: "); //side to side
  204. //    Serial.print(YAngle);
  205. //    Serial.print("\t");
  206. //    Serial.print("X: "); //forward to backward
  207. //    Serial.print(XAngle);
  208. //    Serial.print("\t");
  209. //    Serial.print("Z: ");
  210. //    Serial.println(YawAngle);
  211. //    Serial.print("\t");
  212. //    //Serial.print("FR: ");
  213. //    Serial.print(throttleFR);
  214. //    Serial.print("\t");
  215. //    //Serial.print("BR: ");
  216. //    Serial.print(throttleBR);
  217. //    Serial.print("\t");
  218. //    //Serial.print("FL: ");
  219. //    Serial.print(throttleFL);
  220. //    Serial.print("\t");
  221. //    //Serial.print("BL: ");
  222. //    Serial.println(throttleBL);    
  223. ////////////////////////////////////////////////////////////////////////////////////////
  224. // Makes sure Quadcopter stops propellors after a certain angle
  225.     if((YAngle) > 1.0 || (YAngle) < -1.0)
  226.     {
  227.         analogWrite(frontright, 0);
  228.         analogWrite(frontleft, 0);  
  229.         analogWrite(rearright, 0);
  230.         analogWrite(rearleft, 0);
  231.         delay(80000);
  232.     }
  233.     else if((XAngle) > 1.0 || (XAngle) < -1.0)
  234.     {
  235.         analogWrite(frontright, 0);  
  236.         analogWrite(frontleft, 0);  
  237.         analogWrite(rearright, 0);
  238.         analogWrite(rearleft, 0);  
  239.         delay(80000);
  240.  
  241.     }
  242.  
  243.  
  244.    
  245.  
  246.    
  247. }
  248.  
  249.  
  250.  
  251.  
  252. //SUBROUTINES
  253.  
  254.  
  255.  
  256.  
  257. void checkcommands()
  258. {
  259.          while(Serial.available()>0){
  260.              
  261.            
  262.             inchar = Serial.read();
  263.            
  264.             if(inchar == '\n') break;
  265.      
  266.             if (inchar == EOPmarker) { //if the incoming character is not the byte that is the incoming package ender
  267.                           serialbuf[bufpos] = 0; //restart the buff
  268.                           bufpos = 0; //restart the position of the buff
  269.                           val  = atoi(subStr(serialbuf, ",", 1));
  270.                           xang = atoi(subStr(serialbuf, ",", 2));
  271.                           yang = atoi(subStr(serialbuf, ",", 3));
  272.             }
  273.             else { //once the end of package marker has been read
  274.                     serialbuf[bufpos] = inchar; //the buffer position in the array get assigned to the current read
  275.                     bufpos++; //once that has happend the buffer advances, doing this over and over again until the end of package marker is read.
  276.              
  277.              
  278.  
  279.  
  280.        
  281.  
  282.               }
  283.             }  
  284. }
  285. char* subStr (char* input_string, char *separator, int segment_number) {
  286.   char *act, *sub, *ptr;
  287.   static char copy[MAX_STRING_LEN];
  288.   int i;
  289.   strcpy(copy, input_string);
  290.   for (i = 1, act = copy; i <= segment_number; i++, act = NULL) {
  291.     sub = strtok_r(act, separator, &ptr);
  292.     if (sub == NULL) break;
  293.   }
  294.  return sub;
  295. }
  296.  
  297.  
  298. void initMPU(){
  299.  
  300.   Wire.begin();
  301.  
  302.   mpu.initialize();
  303.   devStatus = mpu.dmpInitialize();
  304.           digitalWrite(13, HIGH);
  305.     delay(8000);
  306.  
  307.     digitalWrite(13, LOW);  
  308.       mpu.setXGyroOffset(38);
  309.     mpu.setYGyroOffset(-28);
  310.     mpu.setZGyroOffset(-33);
  311.     mpu.setXAccelOffset(-2351);
  312.     mpu.setYAccelOffset(502);
  313.     mpu.setZAccelOffset(1617);
  314.   if(devStatus == 0){
  315.  
  316.     mpu.setDMPEnabled(true);
  317.     attachInterrupt(0, dmpDataReady, RISING);
  318.     mpuIntStatus = mpu.getIntStatus();
  319.     packetSize = mpu.dmpGetFIFOPacketSize();
  320.    
  321.   }
  322. }
  323.  
  324. inline void dmpDataReady() {
  325.     mpuInterrupt = true;
  326. }
  327. void getYPR(){
  328.  
  329.     mpuInterrupt = false;
  330.     mpuIntStatus = mpu.getIntStatus();
  331.     fifoCount = mpu.getFIFOCount();
  332.    
  333.     if((mpuIntStatus & 0x10) || fifoCount >= 1024){
  334.      
  335.       mpu.resetFIFO();
  336.    
  337.     }else if(mpuIntStatus & 0x02){
  338.    
  339.       while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
  340.  
  341.       mpu.getFIFOBytes(fifoBuffer, packetSize);
  342.      
  343.       fifoCount -= packetSize;
  344.    
  345.       mpu.dmpGetQuaternion(&q, fifoBuffer);
  346.       mpu.dmpGetGyro(&gyro, fifoBuffer);
  347.       mpu.dmpGetGravity(&gravity, &q);
  348.       mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
  349.    
  350.     }
  351.    
  352.  
  353.  
  354. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement