'' Super ghetto simple flight control using the Parallax Propeller
'' found on the DEF*CON 22 (and 20) badge. 
''
'' Connect as follows: 
''    receiver 'throttle' to PA0
''    receiver 'aileron'  to PA1
''    receiver 'elevator' to PA2
''    receiver 'rudder'   to PA3
''
''    port fwd ESC input  to PA8
''    stbd fwd ESC input  to PA9
''    port aft ESC input  to PA10
''    stbd aft ESC input  to PA11
''
''    InvenSense MPU-6050 SCL to PA29
''    InvenSense MPU-6050 SDA to PA28 
''

CON
  ' set 80 MHz clock via 5 MHz crystal

  _clkmode = xtal1 + pll16x
  _xinfreq = 5_000_000

  ' these are indices into the esc object, not the pins
  OUT_PF = 0   ' Port fwd esc                       
  OUT_SF = 1   ' Stbd fwd esc
  OUT_PA = 2   ' Port aft esc                        
  OUT_SA = 3   ' Stbd aft esc

OBJ
  mpu  : "MPU.spin"
  rx   : "RC_Receiver_4.spin"
  esc  : "Servo8Fast.spin"
  dbg  : "FullDuplexSerial.spin"

  pid_r : "IntPID.spin"
  pid_p : "IntPID.spin"
  pid_y : "IntPID.spin"

VAR
  long o_val[4]   ' PWM high period outputs for ESC object

  ' flying machines have four basic controls:
  ' power, roll, pitch, and r_yaw.
  long r_pow, r_rol, r_pit, r_yaw
  long i_rol, i_pit, i_yaw
  long cmd_r, cmd_p, cmd_y
  long out_r, out_p, out_y
  long pow_mix
  long time_p, time

  long raw_gx, raw_gy, raw_gz   ' mpu readings (raw)
  long int_gx, int_gy, int_gz   ' mpu readings (integrated)

PUB Main
 
  ' use the serial port on 30/31 for debugging
  dbg.Start(31, 30, 0, 115200)

  ' intiialize the MPU-6050 and start the cog that polls it
  mpu.Start

  ' Initialize servo values to all neutral (zero for throttles)
  ' Delay values of 1500 = center, 1000 = min, 2000 = max
  ' 1100 "arms" most ESCs
  o_val[0] := 1100    
  o_val[1] := 1100
  o_val[2] := 1100    
  o_val[3] := 1100

  esc.AddPin(8)
  esc.AddPin(9)
  esc.AddPin(10)
  esc.AddPin(11)  
  esc.Set( 8, o_val[0])
  esc.Set( 9, o_val[1])
  esc.Set(10, o_val[2])
  esc.Set(11, o_val[3])
  esc.Start

  ' Initialize the rx input object with a bitfield corresponding
  ' to pins 0-3 and start the cog
  rx.setpins(%1111)
  rx.start  

  pid_r.Init(35, 0, 8)
  pid_p.Init(35, 0, 8)                       
  pid_y.Init(45, 0, 15)                    

  flight

PUB flight

  time_p := cnt

  cmd_r := cmd_p := cmd_y := 0

  repeat
    ' get the input from the receiver
    r_pow := rx.getrc(0)
    r_rol := rx.getrc(1)
    r_pit := rx.getrc(2)
    r_yaw := rx.getrc(3)

    ' flight contr_rol accumulators; accumulate only roll, pitch, and yaw
    ' because on rotorcraft lift is directly proportional to power
    i_rol += r_rol
    i_pit += r_pit
    i_yaw += r_yaw

    ' gyro y-axis is forward on this contr_roller because i apparently can't
    ' read silkscreen
    raw_gy := mpu.GetRX
    raw_gx := mpu.GetRY
    raw_gz := mpu.GetRZ

    ' a gyroscope measures rate of change about an axis so we need to 
    ' "integrate" (read: accumulate) the gyro values akin to small angle 
    ' approximation.
    ' 
    ' TODO: use the accellerometer to apply a complementary filter, which
    ' should help correct the effects of gyroscopic precession or "gyro drift"
    int_gx += raw_gx
    int_gy += raw_gy
    int_gz += raw_gz

    ' Zero all targets when throttle is off - makes for more stable liftoff
    if(r_pow < -380)
      int_gx := i_rol := 0
      int_gy := i_pit := 0
      int_gz := i_yaw := 0

    cmd_r := i_rol << 1
    cmd_p := i_pit << 1
    cmd_y := i_yaw << 1

    ' the PID loops calculate the difference between the commanded attitude
    ' and the actual attitude
    out_r := pid_r.Calculate(cmd_r, int_gx)
    out_p := pid_p.Calculate(cmd_p, int_gy)
    out_y := pid_y.Calculate(cmd_y, int_gz)

    pow_mix := (r_pow + 400) ~> 2  ' appx. 0 - 256
    pow_mix <#= 64                 ' lock it to 64 at 25% throttle and above
    pow_mix #>= 0

    ' add 1500 to all output values to make them 'servo friendly' again
    r_pow += 1500

    ' channel mixing - "X" orientation where the IMU is mounted in the 
    ' center of the frame, motors are equidistant and 90 degrees apart.
    ' so, a basic X frame; this won't properly control e.g. deadcat-layout
    ' frames without doing some angular math.
    o_val[OUT_PF] := r_pow + ((-out_p - out_r - out_y) * pow_mix) ~> 6 
    o_val[OUT_SF] := r_pow + ((-out_p + out_r + out_y) * pow_mix) ~> 6  
    o_val[OUT_PA] := r_pow + (( out_p - out_r + out_y) * pow_mix) ~> 6
    o_val[OUT_SA] := r_pow + (( out_p + out_r - out_y) * pow_mix) ~> 6

    ' constrain
    o_val[0] #>= 1000
    o_val[0] <#= 2000
    o_val[1] #>= 1000
    o_val[1] <#= 2000
    o_val[2] #>= 1000
    o_val[2] <#= 2000
    o_val[3] #>= 1000
    o_val[3] <#= 2000
     
    ' output to motors
    esc.Set( 8, o_val[0])
    esc.Set( 9, o_val[1])
    esc.Set(10, o_val[2])
    esc.Set(11, o_val[3])

    ' variable delay to execute 200 times per second because I can't
    ' guarantee what the cogs and the hub is doing with respect to 
    ' cog<->hub memory access and the timings thereto

    waitcnt(constant(80_000_000 / 200) + time_p)
    time_p += constant(80_000_000 / 200)
