Rev 1634 |
Rev 1645 |
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 excample: 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 <avr/pgmspace.h>
#include "analog.h"
#include "sensors.h"
// for Delay functions
#include "timer0.h"
// For DebugOut
#include "uart0.h"
// For reading and writing acc. meter offsets.
#include "eeprom.h"
/*
* Arrays could have been used for the 2 * 3 axes, but despite some repetition,
* the code is easier to read without.
*
* For each A/D conversion cycle, each channel (eg. the yaw gyro, or the Z axis
* accelerometer) is sampled a number of times (see array channelsForStates), and
* the results for each channel are summed. Here are those for the gyros and the
* acc. meters. They are not zero-offset.
* They are exported in the analog.h file - but please do not use them! The only
* reason for the export is that the ENC-03_FC1.3 modules needs them for calibrating
* the offsets with the DAC.
*/
volatile int16_t rawPitchGyroSum, rawRollGyroSum, rawYawGyroSum;
volatile int16_t pitchAxisAcc = 0, rollAxisAcc = 0, ZAxisAcc = 0;
volatile int16_t filteredPitchAxisAcc = 0, filteredRollAxisAcc = 0;
// that float one - "Top" - is missing.
/*
* These 4 exported variables are zero-offset. The "filtered" ones are
* (if configured to with the GYROS_SECONDORDERFILTER define) low pass
* filtered versions of the other 2.
* They are derived from the "raw" values above, by zero-offsetting.
*/
volatile int16_t hiResPitchGyro = 0, hiResRollGyro = 0;
volatile int16_t filteredHiResPitchGyro = 0, filteredHiResRollGyro = 0;
volatile int16_t pitchGyroD = 0, rollGyroD = 0;
volatile int16_t yawGyro = 0;
/*
* Offset values. These are the raw gyro and acc. meter sums when the copter is
* standing still. They are used for adjusting the gyro and acc. meter values
* to be zero when the copter stands still.
*/
volatile int16_t pitchOffset, rollOffset, yawOffset;
volatile int16_t pitchAxisAccOffset, rollAxisAccOffset, ZAxisAccOffset;
/*
* This allows some experimentation with the gyro filters.
* Should be replaced by #define's later on...
*/
volatile uint8_t GYROS_FIRSTORDERFILTER;
volatile uint8_t GYROS_SECONDORDERFILTER;
volatile uint8_t GYROS_DFILTER;
volatile uint8_t ACC_FILTER;
// Air pressure (no support right now).
// volatile int32_t AirPressure = 32000;
// volatile uint8_t average_pressure = 0;
// volatile int16_t StartAirPressure;
// volatile uint16_t ReadingAirPressure = 1023;
// volatile int16_t HeightD = 0;
/*
* Battery voltage, in units of: 1k/11k / 3V * 1024 = 31.03 per volt.
* That is divided by 3 below, for a final 10.34 per volt.
* So the initial value of 100 is for 9.7 volts.
*/
volatile int16_t UBat = 100;
volatile int16_t filteredAirPressure;
/*
* Control and status.
*/
volatile uint16_t ADCycleCount = 0;
volatile uint8_t analogDataReady = 1;
/*
* Experiment: Measuring vibration-induced sensor noise.
*/
volatile uint16_t pitchGyroNoisePeak, rollGyroNoisePeak;
volatile uint16_t pitchAccNoisePeak, rollAccNoisePeak;
// ADC channels
#define AD_GYRO_YAW 0
#define AD_GYRO_ROLL 1
#define AD_GYRO_PITCH 2
#define AD_AIRPRESSURE 3
#define AD_UBAT 4
#define AD_ACC_Z 5
#define AD_ACC_ROLL 6
#define AD_ACC_PITCH 7
/*
* Table of AD converter inputs for each state.
* The number of samples summed for each channel is equal to
* the number of times the channel appears in the array.
* The max. number of samples that can be taken in 2 ms is:
* 20e6 / 128 / 13 / (1/2e-3) = 24. Since the main control
* loop needs a little time between reading AD values and
* re-enabling ADC, the real limit is (how much?) lower.
* The acc. sensor is sampled even if not used - or installed
* at all. The cost is not significant.
*/
const uint8_t channelsForStates[] PROGMEM = {
AD_GYRO_PITCH,
AD_GYRO_ROLL,
AD_GYRO_YAW,
AD_ACC_PITCH,
AD_ACC_ROLL,
// AD_AIRPRESSURE,
AD_GYRO_PITCH,
AD_GYRO_ROLL,
AD_ACC_Z, // at 7, measure Z acc.
AD_GYRO_PITCH,
AD_GYRO_ROLL,
AD_GYRO_YAW, // at 10, finish yaw gyro
AD_ACC_PITCH, // at 11, finish pitch axis acc.
AD_ACC_ROLL, // at 12, finish roll axis acc.
AD_AIRPRESSURE, // at 13, finish air pressure.
AD_GYRO_PITCH, // at 14, finish pitch gyro
AD_GYRO_ROLL, // at 15, finish roll gyro
AD_UBAT // at 16, measure battery.
};
// Feature removed. Could be reintroduced later - but should work for all gyro types then.
// uint8_t GyroDefectPitch = 0, GyroDefectRoll = 0, GyroDefectYaw = 0;
void analog_init(void) {
uint8_t sreg = SREG;
// disable all interrupts before reconfiguration
cli();
//ADC0 ... ADC7 is connected to PortA pin 0 ... 7
DDRA = 0x00;
PORTA = 0x00;
// Digital Input Disable Register 0
// Disable digital input buffer for analog adc_channel pins
DIDR0 = 0xFF;
// external reference, adjust data to the right
ADMUX &= ~((1 << REFS1)|(1 << REFS0)|(1 << ADLAR));
// set muxer to ADC adc_channel 0 (0 to 7 is a valid choice)
ADMUX = (ADMUX & 0xE0) | AD_GYRO_PITCH;
//Set ADC Control and Status Register A
//Auto Trigger Enable, Prescaler Select Bits to Division Factor 128, i.e. ADC clock = SYSCKL/128 = 156.25 kHz
ADCSRA = (0<<ADEN)|(0<<ADSC)|(0<<ADATE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0)|(0<<ADIE);
//Set ADC Control and Status Register B
//Trigger Source to Free Running Mode
ADCSRB &= ~((1 << ADTS2)|(1 << ADTS1)|(1 << ADTS0));
// Start AD conversion
analog_start();
// restore global interrupt flags
SREG = sreg;
}
void measureNoise(const int16_t sensor, volatile uint16_t* const noiseMeasurement, const uint8_t damping) {
if (sensor > (int16_t)(*noiseMeasurement)) {
*noiseMeasurement = sensor;
} else if (-sensor > (int16_t)(*noiseMeasurement)) {
*noiseMeasurement = -sensor;
} else if (*noiseMeasurement > damping) {
*noiseMeasurement -= damping;
} else {
*noiseMeasurement = 0;
}
}
#define ADCENTER (1023/2)
#define HALFRANGE 400
uint8_t stepsize = 53;
uint16_t getAbsPressure(int advalue) {
return (uint16_t)OCR0A * (uint16_t)stepsize + advalue;
}
uint16_t filterAirPressure(uint16_t rawpressure) {
return rawpressure;
}
/*****************************************************/
/* Interrupt Service Routine for ADC */
/*****************************************************/
// Runs at 312.5 kHz or 3.2 µs
// When all states are processed the interrupt is disabled
// and the update of further AD conversions is stopped.
ISR(ADC_vect) {
static uint8_t ad_channel = AD_GYRO_PITCH, state = 0;
static uint16_t sensorInputs[8] = {0,0,0,0,0,0,0,0};
uint8_t i;
int16_t step = OCR0A;
// for various filters...
static int16_t pitchGyroFilter, rollGyroFilter, tempOffsetGyro;
sensorInputs[ad_channel] += ADC;
/*
* Actually we don't need this "switch". We could do all the sampling into the
* sensorInputs array first, and all the processing after the last sample.
*/
switch(state++) {
case 7: // Z acc
#ifdef ACC_REVERSE_ZAXIS
ZAxisAcc = -ZAxisAccOffset - sensorInputs[AD_ACC_Z];
#else
ZAxisAcc = sensorInputs[AD_ACC_Z] - ZAxisAccOffset;
#endif
break;
case 10: // yaw gyro
rawYawGyroSum = sensorInputs[AD_GYRO_YAW];
#ifdef GYRO_REVERSE_YAW
yawGyro = rawYawGyroSum - yawOffset;
#else
yawGyro = yawOffset - rawYawGyroSum; // negative is "default" (FC 1.0-1.3).
#endif
break;
case 11: // pitch axis acc.
#ifdef ACC_REVERSE_PITCHAXIS
pitchAxisAcc = -pitchAxisAccOffset - sensorInputs[AD_ACC_PITCH];
#else
pitchAxisAcc = sensorInputs[AD_ACC_PITCH] - pitchAxisAccOffset;
#endif
filteredPitchAxisAcc = (filteredPitchAxisAcc * (ACC_FILTER-1) + pitchAxisAcc) / ACC_FILTER;
measureNoise(pitchAxisAcc, &pitchAccNoisePeak, 1);
break;
case 12: // roll axis acc.
#ifdef ACC_REVERSE_ROLLAXIS
rollAxisAcc = sensorInputs[AD_ACC_ROLL] - rollAxisAccOffset;
#else
rollAxisAcc = -rollAxisAccOffset - sensorInputs[AD_ACC_ROLL];
#endif
filteredRollAxisAcc = (filteredRollAxisAcc * (ACC_FILTER-1) + rollAxisAcc) / ACC_FILTER;
measureNoise(rollAxisAcc, &rollAccNoisePeak, 1);
break;
case 13: // air pressure
if (sensorInputs[AD_AIRPRESSURE] < ADCENTER-HALFRANGE) {
// value is too low, so decrease voltage on the op amp minus input, making the value higher.
step -= ((HALFRANGE-sensorInputs[AD_AIRPRESSURE]) / stepsize + 1);
if (step<0) step = 0;
OCR0A = step;
// wait = ... (calculate something here .. calculate at what time the R/C filter is to within one sample off)
} else if (sensorInputs[AD_AIRPRESSURE] > ADCENTER+HALFRANGE) {
// value is too high, so increase voltage on the op amp minus input, making the value lower.
step += ((sensorInputs[AD_AIRPRESSURE] - HALFRANGE)/stepsize + 1);
if (step>254) step = 254;
OCR0A = step;
// wait = ... (calculate something here .. calculate at what time the R/C filter is to within one sample off)
} else {
filteredAirPressure = filterAirPressure(getAbsPressure(sensorInputs[AD_AIRPRESSURE]));
}
break;
case 14: // pitch gyro
rawPitchGyroSum = sensorInputs[AD_GYRO_PITCH];
// Filter already before offsetting. The offsetting resolution improvement obtained by divding by
// GYROS_FIRSTORDERFILTER _after_ offsetting is too small to be worth pursuing.
pitchGyroFilter = (pitchGyroFilter * (GYROS_FIRSTORDERFILTER-1) + rawPitchGyroSum * GYRO_FACTOR_PITCHROLL) / GYROS_FIRSTORDERFILTER;
// Offset to 0.
#ifdef GYROS_REVERSE_PITCH
tempOffsetGyro = pitchOffset - pitchGyroFilter;
#else
tempOffsetGyro = pitchGyroFilter - pitchOffset;
#endif
// Calculate the delta from last shot and filter it.
pitchGyroD = (pitchGyroD * (GYROS_DFILTER-1) + (tempOffsetGyro - hiResPitchGyro)) / GYROS_DFILTER;
// How we can overwrite the last value. This value is used for the D part of the PID controller.
hiResPitchGyro = tempOffsetGyro;
// Filter a little more. This value is used in integration to angles.
filteredHiResPitchGyro = (filteredHiResPitchGyro * (GYROS_SECONDORDERFILTER-1) + hiResPitchGyro) / GYROS_SECONDORDERFILTER;
measureNoise(hiResPitchGyro, &pitchGyroNoisePeak, GYRO_NOISE_MEASUREMENT_DAMPING);
break;
case 15: // Roll gyro. Works the same as pitch.
rawRollGyroSum = sensorInputs[AD_GYRO_ROLL];
rollGyroFilter = (rollGyroFilter * (GYROS_FIRSTORDERFILTER-1) + rawRollGyroSum * GYRO_FACTOR_PITCHROLL) / GYROS_FIRSTORDERFILTER;
#ifdef GYRO_REVERSE_ROLL
tempOffsetGyro = rollOffset - rollGyroFilter;
#else
tempOffsetGyro = rollGyroFilter - rollOffset;
#endif
rollGyroD = (rollGyroD * (GYROS_DFILTER-1) + (tempOffsetGyro - hiResRollGyro)) / GYROS_DFILTER;
hiResRollGyro = tempOffsetGyro;
filteredHiResRollGyro = (filteredHiResRollGyro * (GYROS_SECONDORDERFILTER-1) + hiResRollGyro) / GYROS_SECONDORDERFILTER;
measureNoise(hiResRollGyro, &rollGyroNoisePeak, GYRO_NOISE_MEASUREMENT_DAMPING);
break;
case 16:
// battery
UBat = (3 * UBat + sensorInputs[AD_UBAT] / 3) / 4;
analogDataReady = 1; // mark
ADCycleCount++;
// Stop the sampling. Cycle is over.
state = 0;
for (i=0; i<8; i++) {
sensorInputs[i] = 0;
}
break;
default: {} // do nothing.
}
// set up for next state.
ad_channel = pgm_read_byte(&channelsForStates[state]);
// ad_channel = channelsForStates[state];
// set adc muxer to next ad_channel
ADMUX = (ADMUX & 0xE0) | ad_channel;
// after full cycle stop further interrupts
if(state) analog_start();
}
void analog_calibrate(void) {
#define GYRO_OFFSET_CYCLES 32
uint8_t i;
int32_t _pitchOffset = 0, _rollOffset = 0, _yawOffset = 0;
// Set the filters... to be removed again, once some good settings are found.
GYROS_FIRSTORDERFILTER = (dynamicParams.UserParams[4] & 0b00000011) + 1;
GYROS_SECONDORDERFILTER = ((dynamicParams.UserParams[4] & 0b00001100) >> 2) + 1;
GYROS_DFILTER = ((dynamicParams.UserParams[4] & 0b00110000) >> 4) + 1;
ACC_FILTER = ((dynamicParams.UserParams[4] & 0b11000000) >> 6) + 1;
pitchOffset = rollOffset = yawOffset = 0;
gyro_calibrate();
// determine gyro bias by averaging (requires that the copter does not rotate around any axis!)
for(i=0; i < GYRO_OFFSET_CYCLES; i++) {
Delay_ms_Mess(10);
_pitchOffset += rawPitchGyroSum * GYRO_FACTOR_PITCHROLL;
_rollOffset += rawRollGyroSum * GYRO_FACTOR_PITCHROLL;
_yawOffset += rawYawGyroSum;
}
pitchOffset = (_pitchOffset + GYRO_OFFSET_CYCLES / 2) / GYRO_OFFSET_CYCLES;
rollOffset = (_rollOffset + GYRO_OFFSET_CYCLES / 2) / GYRO_OFFSET_CYCLES;
yawOffset = (_yawOffset + GYRO_OFFSET_CYCLES / 2) / GYRO_OFFSET_CYCLES;
filteredHiResPitchGyro = filteredHiResRollGyro = 0;
pitchAxisAccOffset = (int16_t)GetParamWord(PID_ACC_NICK);
rollAxisAccOffset = (int16_t)GetParamWord(PID_ACC_ROLL);
ZAxisAccOffset = (int16_t)GetParamWord(PID_ACC_TOP);
// Noise is relative to offset. So, reset noise measurements when
// changing offsets.
pitchGyroNoisePeak = rollGyroNoisePeak = 0;
// Setting offset values has an influence in the analog.c ISR
// Therefore run measurement for 100ms to achive stable readings
Delay_ms_Mess(100);
}
/*
* Find acc. offsets for a neutral reading, and write them to EEPROM.
* Does not (!} update the local variables. This must be done with a
* call to analog_calibrate() - this always (?) is done by the caller
* anyway. There would be nothing wrong with updating the variables
* directly from here, though.
*/
void analog_calibrateAcc(void) {
#define ACC_OFFSET_CYCLES 10
uint8_t i;
int32_t _pitchAxisOffset = 0, _rollAxisOffset = 0, _ZAxisOffset = 0;
pitchAxisAccOffset = rollAxisAccOffset = ZAxisAccOffset = 0;
for(i=0; i < ACC_OFFSET_CYCLES; i++) {
Delay_ms_Mess(10);
_pitchAxisOffset += pitchAxisAcc;
_rollAxisOffset += rollAxisAcc;
_ZAxisOffset += ZAxisAcc;
}
// Save ACC neutral settings to eeprom
SetParamWord(PID_ACC_NICK, (uint16_t)((_pitchAxisOffset + ACC_OFFSET_CYCLES / 2) / ACC_OFFSET_CYCLES));
SetParamWord(PID_ACC_ROLL, (uint16_t)((_rollAxisOffset + ACC_OFFSET_CYCLES / 2) / ACC_OFFSET_CYCLES));
SetParamWord(PID_ACC_TOP, (uint16_t)((_ZAxisOffset + ACC_OFFSET_CYCLES / 2) / ACC_OFFSET_CYCLES));
// Noise is relative to offset. So, reset noise measurements when
// changing offsets.
pitchAccNoisePeak = rollAccNoisePeak = 0;
}