Subversion Repositories FlightCtrl

Rev

Rev 2039 | Rev 2062 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Copyright (c) 04.2007 Holger Buss
// + Nur für den privaten Gebrauch
// + www.MikroKopter.com
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Es gilt für das gesamte Projekt (Hardware, Software, Binärfiles, Sourcecode und Dokumentation),
// + dass eine Nutzung (auch auszugsweise) nur für den privaten (nicht-kommerziellen) Gebrauch zulässig ist.
// + Sollten direkte oder indirekte kommerzielle Absichten verfolgt werden, ist mit uns (info@mikrokopter.de) Kontakt
// + bzgl. der Nutzungsbedingungen aufzunehmen.
// + Eine kommerzielle Nutzung ist z.B.Verkauf von MikroKoptern, Bestückung und Verkauf von Platinen oder Bausätzen,
// + Verkauf von Luftbildaufnahmen, usw.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Werden Teile des Quellcodes (mit oder ohne Modifikation) weiterverwendet oder veröffentlicht,
// + unterliegen sie auch diesen Nutzungsbedingungen und diese Nutzungsbedingungen incl. Copyright müssen dann beiliegen
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Sollte die Software (auch auszugesweise) oder sonstige Informationen des MikroKopter-Projekts
// + auf anderen Webseiten oder sonstigen Medien veröffentlicht werden, muss unsere Webseite "http://www.mikrokopter.de"
// + eindeutig als Ursprung verlinkt werden
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Keine Gewähr auf Fehlerfreiheit, Vollständigkeit oder Funktion
// + Benutzung auf eigene Gefahr
// + Wir übernehmen keinerlei Haftung für direkte oder indirekte Personen- oder Sachschäden
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die Portierung der Software (oder Teile davon) auf andere Systeme (ausser der Hardware von www.mikrokopter.de) ist nur
// + mit unserer Zustimmung zulässig
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Die Funktion printf_P() unterliegt ihrer eigenen Lizenz und ist hiervon nicht betroffen
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// + Redistributions of source code (with or without modifications) must retain the above copyright notice,
// + this list of conditions and the following disclaimer.
// +   * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived
// +     from this software without specific prior written permission.
// +   * The use of this project (hardware, software, binary files, sources and documentation) is only permittet
// +     for non-commercial use (directly or indirectly)
// +     Commercial use (for example: selling of MikroKopters, selling of PCBs, assembly, ...) is only permitted
// +     with our written permission
// +   * If sources or documentations are redistributet on other webpages, out webpage (http://www.MikroKopter.de) must be
// +     clearly linked as origin
// +   * porting to systems other than hardware from www.mikrokopter.de is not allowed
// +  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// +  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// +  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// +  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// +  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// +  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// +  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// +  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN// +  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// +  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// +  POSSIBILITY OF SUCH DAMAGE.
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include <avr/io.h>
#include <avr/interrupt.h>
#include "eeprom.h"
#include "uart0.h"
#include "rc.h"
#include "attitude.h"

#define COARSERESOLUTION 1

#ifdef COARSERESOLUTION
#define NEUTRAL_PULSELENGTH 938
#define SERVOLIMIT 500
#define SCALE_FACTOR 4
#define CS2 ((1<<CS21)|(1<<CS20))
#else
#define NEUTRAL_PULSELENGTH 3750
#define SERVOLIMIT 2000
#define SCALE_FACTOR 16
#define CS2 (<<CS21)
#endif

#define MAX_SERVOS 8
#define FRAMELEN ((NEUTRAL_PULSELENGTH + SERVOLIMIT) * staticParams.servoCount + 128)
#define MIN_PULSELENGTH (NEUTRAL_PULSELENGTH - SERVOLIMIT)
#define MAX_PULSELENGTH (NEUTRAL_PULSELENGTH + SERVOLIMIT)

//volatile uint8_t servoActive = 0;
volatile uint8_t recalculateServoTimes = 0;
volatile uint16_t servoValues[MAX_SERVOS];
volatile uint16_t previousManualValues[2];

#define HEF4017R_ON     PORTC |=  (1<<PORTC6)
#define HEF4017R_OFF    PORTC &= ~(1<<PORTC6)

/*****************************************************
 *              Initialize Timer 2                  
 *****************************************************/

void timer2_init(void) {
        uint8_t sreg = SREG;

        // disable all interrupts before reconfiguration
        cli();

        // set PD7 as output of the PWM for pitch servo
        DDRD |= (1 << DDD7);
        PORTD &= ~(1 << PORTD7); // set PD7 to low

        DDRC |= (1 << DDC6); // set PC6 as output (Reset for HEF4017)
        HEF4017R_ON; // enable reset

        // Timer/Counter 2 Control Register A
        // Timer Mode is CTC (Bits: WGM22 = 0, WGM21 = 1, WGM20 = 0)
        // PD7: Output OCR2 match, (Bits: COM2A1 = 1, COM2A0 = 0)
        // PD6: Normal port operation, OC2B disconnected, (Bits: COM2B1 = 0, COM2B0 = 0)
        TCCR2A &= ~((1 << COM2A0) | (1 << COM2B1) | (1 << COM2B0) | (1 << WGM20) | (1 << WGM22));
        TCCR2A |= (1 << COM2A1) | (1 << WGM21);
 
        // Timer/Counter 2 Control Register B
 
        // Set clock divider for timer 2 to 20MHz / 8 = 2.5 MHz
        // The timer increments from 0x00 to 0xFF with an update rate of 2.5 kHz or 0.4 us
        // hence the timer overflow interrupt frequency is 625 kHz / 256 = 9.765 kHz or 0.1024ms
 
        TCCR2B &= ~((1 << FOC2A) | (1 << FOC2B) | (1 << CS20) | (1 << CS21) | (1 << CS22));
        TCCR2B |= CS2;
 
        // Initialize the Timer/Counter 2 Register
        TCNT2 = 0;
 
        // Initialize the Output Compare Register A used for signal generation on port PD7.
        OCR2A = 255;

        // Timer/Counter 2 Interrupt Mask Register
        // Enable timer output compare match A Interrupt only
        TIMSK2 &= ~((1 << OCIE2B) | (1 << TOIE2));
        TIMSK2 |= (1 << OCIE2A);

        for (uint8_t axis=0; axis<2; axis++)
          previousManualValues[axis] = dynamicParams.servoManualControl[axis] * SCALE_FACTOR;
       
        SREG = sreg;
}

/*
void servo_On(void) {
        servoActive = 1;
}
void servo_Off(void) {
        servoActive = 0;
        HEF4017R_ON; // enable reset
}
*/


/*****************************************************
 * Control Servo Position              
 *****************************************************/


/*typedef struct {
  uint8_t manualControl;
  uint8_t compensationFactor;
  uint8_t minValue;
  uint8_t maxValue;
  uint8_t flags;
} servo_t;*/


int16_t calculateStabilizedServoAxis(uint8_t axis) {
  int32_t value = attitude[axis] / 64L; // between -500000 to 500000 extreme limits. Just about
  // With full blast on stabilization gain (255) we want to convert a delta of, say, 125000 to 2000.
  // That is a divisor of about 1<<14. Same conclusion as H&I.
  value *= staticParams.servoConfigurations[axis].stabilizationFactor;
  value /= 256L;
  if (staticParams.servoConfigurations[axis].flags & SERVO_STABILIZATION_REVERSE)
        return -value;
  return value;
}

// With constant-speed limitation.
uint16_t calculateManualServoAxis(uint8_t axis, uint16_t manualValue) {
  int16_t diff = manualValue - previousManualValues[axis];
  uint8_t maxSpeed = staticParams.servoManualMaxSpeed;
  if (diff > maxSpeed) diff = maxSpeed;
  else if (diff < -maxSpeed) diff = -maxSpeed;
  manualValue = previousManualValues[axis] + diff;
  previousManualValues[axis] = manualValue;
  return manualValue;
}

// add stabilization and manual, apply soft position limits.
// All in a [0..255*SCALE_FACTOR] space (despite signed types used internally)
int16_t featuredServoValue(uint8_t axis) {
  int16_t value = calculateManualServoAxis(axis, dynamicParams.servoManualControl[axis] * SCALE_FACTOR);
  value += calculateStabilizedServoAxis(axis);
  int16_t limit = staticParams.servoConfigurations[axis].minValue * SCALE_FACTOR;
  if (value < limit) value = limit;
  limit = staticParams.servoConfigurations[axis].maxValue * SCALE_FACTOR;
  if (value > limit) value = limit;
  return value;
}

uint16_t servoValue(uint8_t axis) {
  int16_t value;
  if (axis<2) value = featuredServoValue(axis);
  else value = 128 * SCALE_FACTOR; // dummy. Replace by something useful for servos 3..8.
  // Shift out of the [0..255*SCALE_FACTOR] space
  value -= (128 * SCALE_FACTOR);
  if (value < -SERVOLIMIT) value = -SERVOLIMIT;
  else if (value > SERVOLIMIT) value = SERVOLIMIT;
  // Shift into the [NEUTRAL_PULSELENGTH-SERVOLIMIT..NEUTRAL_PULSELENGTH+SERVOLIMIT] space.
  return value + NEUTRAL_PULSELENGTH;
}

void calculateServoValues(void) {
  if (!recalculateServoTimes) return;
  for (uint8_t axis=0; axis<MAX_SERVOS; axis++) {
        servoValues[axis] = servoValue(axis);
  }  
  recalculateServoTimes = 0;
}

ISR(TIMER2_COMPA_vect) {
  static uint16_t remainingPulseTime;
  static uint8_t servoIndex = 0;
  static uint16_t sumOfPulseTimes = 0;
 
  if (!remainingPulseTime) {
    // Pulse is over, and the next pulse has already just started. Calculate length of next pulse.
    if (servoIndex < staticParams.servoCount) {
      // There are more signals to output.
      sumOfPulseTimes += (remainingPulseTime = servoValues[servoIndex]);
      servoIndex++;
    } else {
      // There are no more signals. Reset the counter and make this pulse cover the missing frame time.
      remainingPulseTime = FRAMELEN - sumOfPulseTimes;
      sumOfPulseTimes = servoIndex = 0;
      recalculateServoTimes = 1;
      HEF4017R_ON;
    }
  }

  // Schedule the next OCR2A event. The counter is already reset at this time.
  if (remainingPulseTime > 256+128) {
    // Set output to reset to zero at next OCR match. It does not really matter when the output is set low again,
    // as long as it happens once per pulse. This will, because all pulses are > 255+128 long.
    OCR2A = 255;
    TCCR2A &= ~(1<<COM2A0);
    remainingPulseTime-=256;
  } else if (remainingPulseTime > 256) {
    // Remaining pulse lengths in the range [256..256+128] might cause trouble if handled the standard
    // way, which is in chunks of 256. The remainder would be very small, possibly causing an interrupt on interrupt
    // condition. Instead we now make a chunk of 128. The remaining chunk will then be in [128..255] which is OK.
    remainingPulseTime-=128;
    OCR2A=127;
  } else {
    // Set output to high at next OCR match. This is when the 4017 counter will advance by one. Also set reset low
    TCCR2A |= (1<<COM2A0);
    OCR2A = remainingPulseTime-1;
    remainingPulseTime=0;
    HEF4017R_OFF; // implement servo-disable here, by only removing the reset signal if ServoEnabled!=0.
  }
}