Relocate some structures and code to the right places.
[betaflight.git] / src / main / main.c
blob27093e9e50a521712ffc81e498c259e97a1ca0c0
1 /*
2 * This file is part of Cleanflight.
4 * Cleanflight is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * Cleanflight is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with Cleanflight. If not, see <http://www.gnu.org/licenses/>.
18 #include <stdbool.h>
19 #include <stdint.h>
20 #include <stdlib.h>
21 #include <string.h>
23 #include "platform.h"
25 #include "common/axis.h"
26 #include "common/color.h"
27 #include "common/atomic.h"
28 #include "common/maths.h"
30 #include "drivers/nvic.h"
32 #include "drivers/sensor.h"
33 #include "drivers/system.h"
34 #include "drivers/gpio.h"
35 #include "drivers/light_led.h"
36 #include "drivers/sound_beeper.h"
37 #include "drivers/timer.h"
38 #include "drivers/serial.h"
39 #include "drivers/serial_softserial.h"
40 #include "drivers/serial_uart.h"
41 #include "drivers/accgyro.h"
42 #include "drivers/compass.h"
43 #include "drivers/pwm_mapping.h"
44 #include "drivers/pwm_rx.h"
45 #include "drivers/adc.h"
46 #include "drivers/bus_i2c.h"
47 #include "drivers/bus_spi.h"
48 #include "drivers/inverter.h"
50 #include "rx/rx.h"
52 #include "io/serial.h"
53 #include "io/gps.h"
54 #include "io/escservo.h"
55 #include "io/rc_controls.h"
56 #include "io/gimbal.h"
57 #include "io/ledstrip.h"
58 #include "io/display.h"
60 #include "sensors/sensors.h"
61 #include "sensors/sonar.h"
62 #include "sensors/barometer.h"
63 #include "sensors/compass.h"
64 #include "sensors/acceleration.h"
65 #include "sensors/gyro.h"
66 #include "sensors/battery.h"
67 #include "sensors/boardalignment.h"
69 #include "telemetry/telemetry.h"
70 #include "blackbox/blackbox.h"
72 #include "flight/flight.h"
73 #include "flight/imu.h"
74 #include "flight/mixer.h"
75 #include "flight/failsafe.h"
76 #include "flight/navigation.h"
78 #include "config/runtime_config.h"
79 #include "config/config.h"
80 #include "config/config_profile.h"
81 #include "config/config_master.h"
83 #ifdef USE_HARDWARE_REVISION_DETECTION
84 #include "hardware_revision.h"
85 #endif
87 #include "build_config.h"
89 #ifdef DEBUG_SECTION_TIMES
90 uint32_t sectionTimes[2][4];
91 #endif
92 extern uint32_t previousTime;
94 #ifdef SOFTSERIAL_LOOPBACK
95 serialPort_t *loopbackPort;
96 #endif
98 failsafe_t *failsafe;
100 void printfSupportInit(void);
101 void timerInit(void);
102 void telemetryInit(void);
103 void serialInit(serialConfig_t *initialSerialConfig);
104 failsafe_t* failsafeInit(rxConfig_t *intialRxConfig);
105 pwmOutputConfiguration_t *pwmInit(drv_pwm_config_t *init);
106 void mixerInit(mixerMode_e mixerMode, motorMixer_t *customMixers);
107 void mixerUsePWMOutputConfiguration(pwmOutputConfiguration_t *pwmOutputConfiguration);
108 void rxInit(rxConfig_t *rxConfig, failsafe_t *failsafe);
109 void beepcodeInit(failsafe_t *initialFailsafe);
110 void gpsInit(serialConfig_t *serialConfig, gpsConfig_t *initialGpsConfig);
111 void navigationInit(gpsProfile_t *initialGpsProfile, pidProfile_t *pidProfile);
112 bool sensorsAutodetect(sensorAlignmentConfig_t *sensorAlignmentConfig, uint16_t gyroLpf, uint8_t accHardwareToUse, int8_t magHardwareToUse, int16_t magDeclinationFromConfig);
113 void imuInit(void);
114 void displayInit(rxConfig_t *intialRxConfig);
115 void ledStripInit(ledConfig_t *ledConfigsToUse, hsvColor_t *colorsToUse, failsafe_t* failsafeToUse);
116 void loop(void);
117 void spektrumBind(rxConfig_t *rxConfig);
119 #ifdef STM32F303xC
120 // from system_stm32f30x.c
121 void SetSysClock(void);
122 #endif
123 #ifdef STM32F10X
124 // from system_stm32f10x.c
125 void SetSysClock(bool overclock);
126 #endif
128 void init(void)
130 uint8_t i;
131 drv_pwm_config_t pwm_params;
132 bool sensorsOK = false;
134 printfSupportInit();
136 initEEPROM();
138 ensureEEPROMContainsValidData();
139 readEEPROM();
141 #ifdef STM32F303
142 // start fpu
143 SCB->CPACR = (0x3 << (10*2)) | (0x3 << (11*2));
144 #endif
146 #ifdef STM32F303xC
147 SetSysClock();
148 #endif
149 #ifdef STM32F10X
150 // Configure the System clock frequency, HCLK, PCLK2 and PCLK1 prescalers
151 // Configure the Flash Latency cycles and enable prefetch buffer
152 SetSysClock(masterConfig.emf_avoidance);
153 #endif
155 #ifdef USE_HARDWARE_REVISION_DETECTION
156 detectHardwareRevision();
157 #endif
159 systemInit();
161 ledInit();
163 #ifdef SPEKTRUM_BIND
164 if (feature(FEATURE_RX_SERIAL)) {
165 switch (masterConfig.rxConfig.serialrx_provider) {
166 case SERIALRX_SPEKTRUM1024:
167 case SERIALRX_SPEKTRUM2048:
168 // Spektrum satellite binding if enabled on startup.
169 // Must be called before that 100ms sleep so that we don't lose satellite's binding window after startup.
170 // The rest of Spektrum initialization will happen later - via spektrumInit()
171 spektrumBind(&masterConfig.rxConfig);
172 break;
175 #endif
177 delay(100);
179 timerInit(); // timer must be initialized before any channel is allocated
181 #ifdef BEEPER
182 beeperConfig_t beeperConfig = {
183 .gpioMode = Mode_Out_OD,
184 .gpioPin = BEEP_PIN,
185 .gpioPort = BEEP_GPIO,
186 .gpioPeripheral = BEEP_PERIPHERAL,
187 .isInverted = false
189 #ifdef NAZE
190 if (hardwareRevision >= NAZE32_REV5) {
191 // naze rev4 and below used opendrain to PNP for buzzer. Rev5 and above use PP to NPN.
192 beeperConfig.gpioMode = Mode_Out_PP;
193 beeperConfig.isInverted = true;
195 #endif
197 beeperInit(&beeperConfig);
198 #endif
200 #ifdef INVERTER
201 initInverter();
202 #endif
205 #ifdef USE_SPI
206 spiInit(SPI1);
207 spiInit(SPI2);
208 #endif
210 #ifdef USE_HARDWARE_REVISION_DETECTION
211 updateHardwareRevision();
212 #endif
214 #ifdef USE_I2C
215 #if defined(NAZE)
216 if (hardwareRevision != NAZE32_SP) {
217 i2cInit(I2C_DEVICE);
219 #elif defined(CC3D)
220 if (!doesConfigurationUsePort(SERIAL_PORT_USART3)) {
221 i2cInit(I2C_DEVICE);
223 #else
224 i2cInit(I2C_DEVICE);
225 #endif
226 #endif
228 #ifdef USE_ADC
229 drv_adc_config_t adc_params;
231 adc_params.enableRSSI = feature(FEATURE_RSSI_ADC);
232 adc_params.enableCurrentMeter = feature(FEATURE_CURRENT_METER);
233 adc_params.enableExternal1 = false;
234 #ifdef OLIMEXINO
235 adc_params.enableExternal1 = true;
236 #endif
237 #ifdef NAZE
238 // optional ADC5 input on rev.5 hardware
239 adc_params.enableExternal1 = (hardwareRevision >= NAZE32_REV5);
240 #endif
242 adcInit(&adc_params);
243 #endif
246 initBoardAlignment(&masterConfig.boardAlignment);
248 #ifdef DISPLAY
249 if (feature(FEATURE_DISPLAY)) {
250 displayInit(&masterConfig.rxConfig);
252 #endif
254 // We have these sensors; SENSORS_SET defined in board.h depending on hardware platform
255 sensorsSet(SENSORS_SET);
256 // drop out any sensors that don't seem to work, init all the others. halt if gyro is dead.
257 sensorsOK = sensorsAutodetect(&masterConfig.sensorAlignmentConfig, masterConfig.gyro_lpf, masterConfig.acc_hardware, masterConfig.mag_hardware, currentProfile->mag_declination);
259 // if gyro was not detected due to whatever reason, we give up now.
260 if (!sensorsOK)
261 failureMode(3);
263 LED1_ON;
264 LED0_OFF;
265 for (i = 0; i < 10; i++) {
266 LED1_TOGGLE;
267 LED0_TOGGLE;
268 delay(25);
269 BEEP_ON;
270 delay(25);
271 BEEP_OFF;
273 LED0_OFF;
274 LED1_OFF;
276 imuInit();
277 mixerInit(masterConfig.mixerMode, masterConfig.customMixer);
279 #ifdef MAG
280 if (sensors(SENSOR_MAG))
281 compassInit();
282 #endif
284 serialInit(&masterConfig.serialConfig);
286 memset(&pwm_params, 0, sizeof(pwm_params));
287 // when using airplane/wing mixer, servo/motor outputs are remapped
288 if (masterConfig.mixerMode == MIXER_AIRPLANE || masterConfig.mixerMode == MIXER_FLYING_WING)
289 pwm_params.airplane = true;
290 else
291 pwm_params.airplane = false;
292 #if defined(SERIAL_PORT_USART2) && defined(STM32F10X)
293 pwm_params.useUART2 = doesConfigurationUsePort(SERIAL_PORT_USART2);
294 #endif
295 pwm_params.useVbat = feature(FEATURE_VBAT);
296 pwm_params.useSoftSerial = feature(FEATURE_SOFTSERIAL);
297 pwm_params.useParallelPWM = feature(FEATURE_RX_PARALLEL_PWM);
298 pwm_params.useRSSIADC = feature(FEATURE_RSSI_ADC);
299 pwm_params.useCurrentMeterADC = feature(FEATURE_CURRENT_METER)
300 && masterConfig.batteryConfig.currentMeterType == CURRENT_SENSOR_ADC;
301 pwm_params.useLEDStrip = feature(FEATURE_LED_STRIP);
302 pwm_params.usePPM = feature(FEATURE_RX_PPM);
303 pwm_params.useOneshot = feature(FEATURE_ONESHOT125);
304 pwm_params.useSerialRx = feature(FEATURE_RX_SERIAL);
305 pwm_params.useServos = isMixerUsingServos();
306 pwm_params.extraServos = currentProfile->gimbalConfig.gimbal_flags & GIMBAL_FORWARDAUX;
307 pwm_params.motorPwmRate = masterConfig.motor_pwm_rate;
308 pwm_params.servoPwmRate = masterConfig.servo_pwm_rate;
309 pwm_params.idlePulse = PULSE_1MS; // standard PWM for brushless ESC (default, overridden below)
310 if (feature(FEATURE_3D))
311 pwm_params.idlePulse = masterConfig.flight3DConfig.neutral3d;
312 if (pwm_params.motorPwmRate > 500)
313 pwm_params.idlePulse = 0; // brushed motors
314 pwm_params.servoCenterPulse = masterConfig.escAndServoConfig.servoCenterPulse;
316 pwmRxInit(masterConfig.inputFilteringMode);
318 pwmOutputConfiguration_t *pwmOutputConfiguration = pwmInit(&pwm_params);
320 mixerUsePWMOutputConfiguration(pwmOutputConfiguration);
322 failsafe = failsafeInit(&masterConfig.rxConfig);
323 beepcodeInit(failsafe);
324 rxInit(&masterConfig.rxConfig, failsafe);
326 #ifdef GPS
327 if (feature(FEATURE_GPS)) {
328 gpsInit(
329 &masterConfig.serialConfig,
330 &masterConfig.gpsConfig
332 navigationInit(
333 &currentProfile->gpsProfile,
334 &currentProfile->pidProfile
337 #endif
339 #ifdef SONAR
340 if (feature(FEATURE_SONAR)) {
341 sonarInit();
343 #endif
345 #ifdef LED_STRIP
346 ledStripInit(masterConfig.ledConfigs, masterConfig.colors, failsafe);
348 if (feature(FEATURE_LED_STRIP)) {
349 ledStripEnable();
351 #endif
353 #ifdef TELEMETRY
354 if (feature(FEATURE_TELEMETRY))
355 telemetryInit();
356 #endif
358 #ifdef BLACKBOX
359 initBlackbox();
360 #endif
362 previousTime = micros();
364 if (masterConfig.mixerMode == MIXER_GIMBAL) {
365 accSetCalibrationCycles(CALIBRATING_ACC_CYCLES);
367 gyroSetCalibrationCycles(CALIBRATING_GYRO_CYCLES);
368 #ifdef BARO
369 baroSetCalibrationCycles(CALIBRATING_BARO_CYCLES);
370 #endif
372 // start all timers
373 // TODO - not implemented yet
374 timerStart();
376 ENABLE_STATE(SMALL_ANGLE);
377 DISABLE_ARMING_FLAG(PREVENT_ARMING);
379 #ifdef SOFTSERIAL_LOOPBACK
380 // FIXME this is a hack, perhaps add a FUNCTION_LOOPBACK to support it properly
381 loopbackPort = (serialPort_t*)&(softSerialPorts[0]);
382 if (!loopbackPort->vTable) {
383 loopbackPort = openSoftSerial(0, NULL, 19200, SERIAL_NOT_INVERTED);
385 serialPrint(loopbackPort, "LOOPBACK\r\n");
386 #endif
388 // Now that everything has powered up the voltage and cell count be determined.
390 // Check battery type/voltage
391 if (feature(FEATURE_VBAT))
392 batteryInit(&masterConfig.batteryConfig);
394 #ifdef DISPLAY
395 if (feature(FEATURE_DISPLAY)) {
396 #ifdef USE_OLED_GPS_DEBUG_PAGE_ONLY
397 displayShowFixedPage(PAGE_GPS);
398 #else
399 displayEnablePageCycling();
400 #endif
402 #endif
404 #ifdef CJMCU
405 LED2_ON;
406 #endif
409 #ifdef SOFTSERIAL_LOOPBACK
410 void processLoopback(void) {
411 if (loopbackPort) {
412 uint8_t bytesWaiting;
413 while ((bytesWaiting = serialTotalBytesWaiting(loopbackPort))) {
414 uint8_t b = serialRead(loopbackPort);
415 serialWrite(loopbackPort, b);
419 #else
420 #define processLoopback()
421 #endif
423 int main(void) {
424 init();
426 while (1) {
427 loop();
428 processLoopback();
432 void HardFault_Handler(void)
434 // fall out of the sky
435 writeAllMotors(masterConfig.escAndServoConfig.mincommand);
436 while (1);