C
Add files via upload
Jobit Joseph7a841582857b
diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/amg8833.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/amg8833.hnew file mode 100644index 0000000..adf5c5a--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/amg8833.h@@ -0,0 +1,122 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2017 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * amg8833.h - Functions for interfacing AMG8833 thermal sensor+ * Reference : https://github.com/adafruit/Adafruit_AMG88xx+ */+#ifndef __AMG8833_H__+#define __AMG8833_H__++#include <stdint.h>+#include <stdbool.h>++#include "i2cdev.h"+#include "task.h"+#include "num.h"+++#define MINTEMP 22+#define MAXTEMP 34++#define AMG_I2C_CHUNKSIZE 32+#define AMG88xx_PIXEL_ARRAY_SIZE 64++#define AMG88xx_ADDRESS 0x68+/************** Registers ***************/+#define AMG88xx_PCTL 0x00+#define AMG88xx_RST 0x01+#define AMG88xx_FPSC 0x02+#define AMG88xx_INTC 0x03+#define AMG88xx_STAT 0x04+#define AMG88xx_SCLR 0x05+#define AMG88xx_AVE 0x07+#define AMG88xx_INTHL 0x08+#define AMG88xx_INTHH 0x09+#define AMG88xx_INTLL 0x0A+#define AMG88xx_INTLH 0x0B+#define AMG88xx_IHYSL 0x0C+#define AMG88xx_IHYSH 0x0D+#define AMG88xx_TTHL 0x0E+#define AMG88xx_TTHH 0x0F+#define AMG88xx_INT_OFFSET 0x10+#define AMG88xx_PIXEL_OFFSET 0x80+/************* Power modes *************/+#define AMG88xx_NORMAL_MODE 0x00+#define AMG88xx_SLEEP_MODE 0x01+#define AMG88xx_STAND_BY_60 0x20+#define AMG88xx_STAND_BY_10 0x21+/*********** Software resets ***********/+#define AMG88xx_FLAG_RESET 0x30+#define AMG88xx_INITIAL_RESET 0x3F+/************* Frame rates *************/+#define AMG88xx_FPS_10 0x00+#define AMG88xx_FPS_1 0x01+/********** Interrupt Enables **********/+#define AMG88xx_INT_DISABLED 0x00+#define AMG88xx_INT_ENABLED 0x01+/********** Interrupt modes ************/+#define AMG88xx_DIFFERENCE 0x00+#define AMG88xx_ABSOLUTE_VALUE 0x01++typedef struct {+ uint8_t devAddr;+ I2C_Dev *I2Cx;+} AMG8833_Dev_t;++typedef AMG8833_Dev_t *AMG8833_DEV;++// Initiate thermal sensor+bool begin(AMG8833_Dev_t *dev, I2C_Dev *I2Cx);++// Data capture+void readPixels(AMG8833_Dev_t *dev, float *buf, uint8_t size);+float readThermistor(AMG8833_Dev_t *dev);++// Interrupts+bool enableInterrupt(AMG8833_Dev_t *dev);+bool disableInterrupt(AMG8833_Dev_t *dev);+void setInterruptMode(AMG8833_Dev_t *dev, uint8_t mode);+void getInterrupt(AMG8833_Dev_t *dev, uint8_t *buf, uint8_t size);+void clearInterrupt(AMG8833_Dev_t *dev);+// This will automatically set hysteresis to 95% of the high value+void setInterruptLevels_N(AMG8833_Dev_t *dev, float high, float low);+// This will manually set hysteresis+void setInterruptLevels_H(AMG8833_Dev_t *dev, float high, float low, float hysteresis);++// Modes+void setMovingAverageMode(AMG8833_Dev_t *dev, bool mode);++// Read operations+uint8_t read8(AMG8833_Dev_t *dev, uint8_t reg);+void read(AMG8833_Dev_t *dev, uint8_t reg, uint8_t *buf, uint8_t num);++// Write operations+bool write8(AMG8833_Dev_t *dev, uint16_t reg, uint8_t value);+void write(AMG8833_Dev_t *dev, uint8_t reg, uint8_t *buf, uint8_t num);++// Supportive calculations+float signedMag12ToFloat(uint16_t val);+float int12ToFloat(uint16_t val);+uint8_t min(uint8_t a, uint8_t b);++#endif /* __AMG8833_H__ */diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/buzzer.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/buzzer.hnew file mode 100644index 0000000..1665e7c--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/buzzer.h@@ -0,0 +1,65 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2015 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * buzzdeck.h - Functions for interfacing with decks with buzzers+ */+#ifndef __BUZZER_H__+#define __BUZZER_H__++#include <stdint.h>+#include <stdbool.h>++/** Functionpointers used to control the buzzer */+struct buzzerControl+{+ void (*off)();+ void (*on)(uint32_t freq);+};++/**+ * Initilize the buzzer sub-system.+ */+void buzzerInit();++/**+ * Test the buzzer sub-system.+ */+bool buzzerTest();++/**+ * Turn the buzzer off.+ */+void buzzerOff();++/**+ * Turn the buzzer on and set it to a specific frequency (if supported).+ */+void buzzerOn(uint32_t freq);++/**+ * Set function pointers for controlling the buzzer hardware.+ */+void buzzerSetControl(struct buzzerControl * bc);++#endif //__BUZZER_H__+diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/eskylink.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/eskylink.hnew file mode 100644index 0000000..062a479--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/eskylink.h@@ -0,0 +1,37 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2012 BitCraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * eskylink.h: esky 2.4GHz-compatible link driver+ */++#ifndef __ESKYLINK_H__+#define __ESKYLINK_H__++#include "crtp.h"++void eskylinkInit();+bool eskylinkTest();+struct crtpLinkOperations * eskylinkGetLink();+void eskylinkReInit(void);++#endifdiff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/freeRTOSdebug.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/freeRTOSdebug.hnew file mode 100644index 0000000..165344e--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/freeRTOSdebug.h@@ -0,0 +1,42 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * debug_cf.h - Various debug functions+ */+#ifndef DEBUG_H_+#define DEBUG_H_++/**+ * Initializes peripherals used for creating trace+ * information+ */+void debugInitTrace(void);++/**+ * Sends trace information using the UART1. This function is+ * used with the freertos traceTASK_SWITCHED_IN() macro.+ * @param Task number currently running+ */+void debugSendTraceInfo(unsigned int taskNbr);++#endif /* DEBUG_H_ */diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/imu.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/imu.hnew file mode 100644index 0000000..dbf3cfa--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/imu.h@@ -0,0 +1,65 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * imu.h - inertial measurement unit header file+ */+#ifndef IMU_H_+#define IMU_H_+#include <stdbool.h>+#include "filter.h"+#include "imu_types.h"++/**+ * IMU update frequency dictates the overall update frequency.+ */+#define IMU_UPDATE_FREQ 500+#define IMU_UPDATE_DT (float)(1.0/IMU_UPDATE_FREQ)++/**+ * Set ACC_WANTED_LPF1_CUTOFF_HZ to the wanted cut-off freq in Hz.+ * The highest cut-off freq that will have any affect is fs /(2*pi).+ * E.g. fs = 350 Hz -> highest cut-off = 350/(2*pi) = 55.7 Hz -> 55 Hz+ */+#define IMU_ACC_WANTED_LPF_CUTOFF_HZ 4+/**+ * Attenuation should be between 1 to 256.+ *+ * f0 = fs / 2*pi*attenuation ->+ * attenuation = fs / 2*pi*f0+ */+#define IMU_ACC_IIR_LPF_ATTENUATION (IMU_UPDATE_FREQ / (2 * 3.1415 * IMU_ACC_WANTED_LPF_CUTOFF_HZ))+#define IMU_ACC_IIR_LPF_ATT_FACTOR (int)(((1<<IIR_SHIFT) / IMU_ACC_IIR_LPF_ATTENUATION) + 0.5)++void imu6Init(void);+bool imu6Test(void);+bool imu6ManufacturingTest(void);+void imu6Read(Axis3f* gyro, Axis3f* acc);+void imu9Read(Axis3f* gyroOut, Axis3f* accOut, Axis3f* magOut);+bool imu6IsCalibrated(void);+bool imuHasBarometer(void);+bool imuHasMangnetometer(void);++++#endif /* IMU_H_ */diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/imu_types.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/imu_types.hnew file mode 100644index 0000000..f027b7b--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/imu_types.h@@ -0,0 +1,66 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * imu_types.h - Types used by IMU and releted functions.+ */+#ifndef IMU_TYPES_H_+#define IMU_TYPES_H_++ typedef union {+ struct {+ int16_t x;+ int16_t y;+ int16_t z;+ };+ int16_t axis[3];+ } Axis3i16;++ typedef union {+ struct {+ int32_t x;+ int32_t y;+ int32_t z;+ };+ int32_t axis[3];+ } Axis3i32;++ typedef union {+ struct {+ int64_t x;+ int64_t y;+ int64_t z;+ };+ int64_t axis[3];+ } Axis3i64;++ typedef union {+ struct {+ float x;+ float y;+ float z;+ };+ float axis[3];+ } Axis3f;++#endif /* IMU_TYPES_H_ */diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/ledseq.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/ledseq.hnew file mode 100644index 0000000..9d70f00--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/ledseq.h@@ -0,0 +1,142 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */++/*+ * ledseq.h - LED sequence handler+ */++#ifndef __LEDSEQ_H__+#define __LEDSEQ_H__++/* A LED sequence is made of a list of actions. Each action contains the new+ * state of the LED and either a time to wait before executing the next action+ * or a command LOOP or STOP.+ *+ * The sequences are stored in a list by priority order ([0] is the highest+ * priority). The list ordered by priority is defined at the beginning of+ * ledseq.c+ *+ * Each sequence effects only one LED. For each LED only the runnable sequence+ * with the highest priority is run.+ */++#include <stdint.h>+#include <stdbool.h>+#include "led.h"++#define LEDSEQ_CHARGE_CYCLE_TIME_500MA 1000+#define LEDSEQ_CHARGE_CYCLE_TIME_MAX 500+//Led sequence action+#define LEDSEQ_WAITMS(X) (X)+#define LEDSEQ_STOP -1+#define LEDSEQ_LOOP -2++typedef struct {+ bool value;+ int action;+} ledseqStep_t;++typedef struct ledseqContext_s {+ ledseqStep_t* const sequence;+ struct ledseqContext_s* nextContext;+ int state;+ const led_t led;+} ledseqContext_t;++// Public API+void ledseqInit(void);+bool ledseqTest(void);++/**+ * @brief Enable/disable the led sequence module+ *+ * @param enable Enabled if true+ */+void ledseqEnable(bool enable);++/**+ * @brief Register a new LED sequence. Sequences must be+ * registerd before they can be used, registration order detemines the+ * relative priorities between sequences.+ *+ * @param context Pointer to a LED seqence runtime context. Note the+ * context will be part of linked list of contexts and must exist+ * as long as the system is running.+ */+void ledseqRegisterSequence(ledseqContext_t* context);++/**+ * @brief Run a LED sequence. This function is non-blocking any may fail to start the sequence.+ *+ * @param context The context for the sequence to start+ * @return true If the sequence was started+ * @return false If the sequence did not start+ */+bool ledseqRun(ledseqContext_t* context);++/**+ * @brief Run a LED sequence. This function is blocking and may take some time,+ * but is quaranteed to mark the sequence as started.+ *+ * @param context The context for the sequence to start+ */+void ledseqRunBlocking(ledseqContext_t* context);++/**+ * @brief Stop a LED sequence. This function is non-blocking any may fail to stop the sequence.+ *+ * @param context The context for the sequence to stop+ * @return true If the sequence was stopped+ * @return false If the sequence did not stop+ */+bool ledseqStop(ledseqContext_t* context);++/**+ * @brief Stop a LED sequence. This function is blocking and may take some time,+ * but is quaranteed to mark the sequence as started.+ *+ * @param context The context for the sequence to stop+ */+void ledseqStopBlocking(ledseqContext_t* context);++/**+ * @brief Set interval in the charging sequence to reflect the+ * charge level+ *+ * @param chargeLevel The charge level between 0.0 and 1.0+ */+void ledseqSetChargeLevel(const float chargeLevel);++// System led sequences+extern ledseqContext_t seq_calibrated;+extern ledseqContext_t seq_alive;+extern ledseqContext_t seq_lowbat;+extern ledseqContext_t seq_linkUp;+extern ledseqContext_t seq_linkDown;+extern ledseqContext_t seq_charged;+extern ledseqContext_t seq_charging;+extern ledseqContext_t seq_testPassed;+extern ledseqContext_t seq_testFailed;++#endifdiff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/ow.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/ow.hnew file mode 100644index 0000000..88b96ee--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/ow.h@@ -0,0 +1,76 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * ow.h - One-wire functions+ */+#ifndef __OW_H__+#define __OW_H__++#include <stdint.h>+#include "syslink.h"++#define OW_MAX_SIZE 112+#define OW_READ_SIZE 29+#define OW_MAX_WRITE_SIZE 26 // Use even numbers because of 16bits segments++typedef struct owCommand_s {+ uint8_t nmem;+ union {+ struct {+ uint8_t memId[8];+ } __attribute__((packed)) info;+ struct {+ uint16_t address;+ uint8_t data[29];+ } __attribute__((packed)) read;+ struct write {+ uint16_t address;+ uint16_t length;+ char data[27];+ } __attribute__((packed)) write;+ };+} __attribute__((packed)) OwCommand;++typedef struct owSerialNum_s+{+ union {+ struct {+ uint8_t type;+ uint8_t id[6];+ uint8_t crc;+ };+ uint8_t data[8];+ };+} OwSerialNum;++void owInit();+bool owTest();+void owCommonInit();+bool owCommonTest();+void owSyslinkRecieve(SyslinkPacket *slp);+bool owScan(uint8_t *nMem);+bool owGetinfo(uint8_t selectMem, OwSerialNum *serialNum);+bool owRead(uint8_t selectMem, uint16_t address, uint8_t length, uint8_t *data);+bool owWrite(uint8_t selectMem, uint16_t address, uint8_t length, const uint8_t *data);++#endif //__OW_H__diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/pca9555.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/pca9555.hnew file mode 100644index 0000000..70b3c33--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/pca9555.h@@ -0,0 +1,88 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2017 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * pca9555.h - Functions for interfacing PCA9555 I2C GPIO extender+ */+#ifndef __PCA9555_H__+#define __PCA9555_H__++#include <stdint.h>+#include <stdbool.h>++#define PCA9555_DEFAULT_ADDRESS 0b0100000++#define PCA9555_INPUT_REGA (0x00)+#define PCA9555_INPUT_REGB (0x01)+#define PCA9555_OUTPUT_REGA (0x02)+#define PCA9555_OUTPUT_REGB (0x03)+#define PCA9555_POL_REGA (0x04)+#define PCA9555_POL_REGB (0x05)+#define PCA9555_CONFIG_REGA (0x06)+#define PCA9555_CONFIG_REGB (0x07)++#define PCA9555_P00 (1 << 0)+#define PCA9555_P01 (1 << 1)+#define PCA9555_P02 (1 << 2)+#define PCA9555_P03 (1 << 3)+#define PCA9555_P04 (1 << 4)+#define PCA9555_P05 (1 << 5)+#define PCA9555_P06 (1 << 6)+#define PCA9555_P07 (1 << 7)+#define PCA9555_P10 (1 << 0)+#define PCA9555_P11 (1 << 1)+#define PCA9555_P12 (1 << 2)+#define PCA9555_P13 (1 << 3)+#define PCA9555_P14 (1 << 4)+#define PCA9555_P15 (1 << 5)+#define PCA9555_P16 (1 << 6)+#define PCA9555_P17 (1 << 7)++/**+ * Initialize the PCA9555 sub-system.+ */+void pca9555Init();++/**+ * Test the PCA9555 sub-system.+ */+bool pca9555Test();++/**+ * Set the output register values.+ */+bool pca9555ConfigOutputRegA(uint32_t val);+bool pca9555ConfigOutputRegB(uint32_t val);++/**+ * Set output bits.+ */+bool pca9555SetOutputRegA(uint32_t mask);+bool pca9555SetOutputRegB(uint32_t mask);++/**+ * Reset output bits.+ */+bool pca9555ClearOutputRegA(uint32_t mask);+bool pca9555ClearOutputRegB(uint32_t mask);++#endif //__PCA9555_H__diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/pca95x4.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/pca95x4.hnew file mode 100644index 0000000..4404f1b--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/pca95x4.h@@ -0,0 +1,73 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2017 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * pca95x4.h - Functions for interfacing PCA95X4 I2C GPIO extender+ */+#ifndef __PCA95X4_H__+#define __PCA95X4_H__++#include <stdint.h>+#include <stdbool.h>++#define PCA95X4_DEFAULT_ADDRESS 0b0100000++#define PCA95X4_INPUT_REG (0x00)+#define PCA95X4_OUTPUT_REG (0x01)+#define PCA95X4_POL_REG (0x02)+#define PCA95X4_CONFIG_REG (0x03)++#define PCA95X4_P0 (1 << 0)+#define PCA95X4_P1 (1 << 1)+#define PCA95X4_P2 (1 << 2)+#define PCA95X4_P3 (1 << 3)+#define PCA95X4_P4 (1 << 4)+#define PCA95X4_P5 (1 << 5)+#define PCA95X4_P6 (1 << 6)+#define PCA95X4_P7 (1 << 7)++/**+ * Initilize the PCA95X4 sub-system.+ */+void pca95x4Init();++/**+ * Test the PCA95X4 sub-system.+ */+bool pca95x4Test();++/**+ * Set the output register value.+ */+bool pca95x4ConfigOutput(uint32_t val);++/**+ * Set output bits.+ */+bool pca95x4SetOutput(uint32_t mask);++/**+ * Reset output bits.+ */+bool pca95x4ClearOutput(uint32_t mask);++#endif //__PCA95X4_H__diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/pm.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/pm.hnew file mode 100644index 0000000..b8845b8--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/pm.h@@ -0,0 +1,179 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * pm.h - Power Management driver and functions.+ */+#ifdef 0+#ifndef PM_H_+#define PM_H_++#include "adc.h"+#include "syslink.h"+#include "deck.h"++#ifndef CRITICAL_LOW_VOLTAGE+ #define PM_BAT_CRITICAL_LOW_VOLTAGE 3.0f+#else+ #define PM_BAT_CRITICAL_LOW_VOLTAGE CRITICAL_LOW_VOLTAGE+#endif+#ifndef CRITICAL_LOW_TIMEOUT+ #define PM_BAT_CRITICAL_LOW_TIMEOUT M2T(1000 * 5) // 5 sec default+#else+ #define PM_BAT_CRITICAL_LOW_TIMEOUT CRITICAL_LOW_TIMEOUT+#endif++#ifndef LOW_VOLTAGE+ #define PM_BAT_LOW_VOLTAGE 3.2f+#else+ #define PM_BAT_LOW_VOLTAGE LOW_VOLTAGE+#endif+#ifndef LOW_TIMEOUT+ #define PM_BAT_LOW_TIMEOUT M2T(1000 * 5) // 5 sec default+#else+ #define PM_BAT_LOW_TIMEOUT LOW_TIMEOUT+#endif++#ifndef SYSTEM_SHUTDOWN_TIMEOUT+ #define PM_SYSTEM_SHUTDOWN_TIMEOUT M2T(1000 * 60 * 5) // 5 min default+#else+ #define PM_SYSTEM_SHUTDOWN_TIMEOUT M2T(1000 * 60 * SYSTEM_SHUTDOWN_TIMEOUT)+#endif++#define PM_BAT_DIVIDER 3.0f+#define PM_BAT_ADC_FOR_3_VOLT (int32_t)(((3.0f / PM_BAT_DIVIDER) / 2.8f) * 4096)+#define PM_BAT_ADC_FOR_1p2_VOLT (int32_t)(((1.2f / PM_BAT_DIVIDER) / 2.8f) * 4096)++#define PM_BAT_IIR_SHIFT 8+/**+ * Set PM_BAT_WANTED_LPF_CUTOFF_HZ to the wanted cut-off freq in Hz.+ */+#define PM_BAT_WANTED_LPF_CUTOFF_HZ 1++/**+ * Attenuation should be between 1 to 256.+ *+ * f0 = fs / 2*pi*attenuation.+ * attenuation = fs / 2*pi*f0+ */+#define PM_BAT_IIR_LPF_ATTENUATION (int)(ADC_SAMPLING_FREQ / (int)(2 * 3.1415f * PM_BAT_WANTED_LPF_CUTOFF_HZ))+#define PM_BAT_IIR_LPF_ATT_FACTOR (int)((1<<PM_BAT_IIR_SHIFT) / PM_BAT_IIR_LPF_ATTENUATION)++typedef enum+{+ battery,+ charging,+ charged,+ lowPower,+ shutDown,+} PMStates;++typedef enum+{+ charge100mA,+ charge500mA,+ chargeMax,+} PMChargeStates;++typedef enum+{+ USBNone,+ USB500mA,+ USBWallAdapter,+} PMUSBPower;++void pmInit(void);++bool pmTest(void);++/**+ * Power management task+ */+void pmTask(void *param);++void pmSetChargeState(PMChargeStates chgState);+void pmSyslinkUpdate(SyslinkPacket *slp);++/**+ * Returns the battery voltage i volts as a float+ */+float pmGetBatteryVoltage(void);++/**+ * Returns the min battery voltage i volts as a float+ */+float pmGetBatteryVoltageMin(void);++/**+ * Returns the max battery voltage i volts as a float+ */+float pmGetBatteryVoltageMax(void);++/**+ * Updates and calculates battery values.+ * Should be called for every new adcValues sample.+ */+void pmBatteryUpdate(AdcGroup* adcValues);++/**+ * Returns true if the battery is below its low capacity threshold for an+ * extended period of time.+ */+bool pmIsBatteryLow(void);++/**+ * Returns true if the charger is currently connected+ */+bool pmIsChargerConnected(void);++/**+ * Returns true if the battery is currently charging+ */+bool pmIsCharging(void);++/**+ * Returns true if the battery is currently in use+ */+bool pmIsDischarging(void);++/**+ * Enable or disable external battery voltage measuring.+ */+void pmEnableExtBatteryVoltMeasuring(const deckPin_t pin, float multiplier);++/**+ * Measure an external voltage.+ */+float pmMeasureExtBatteryVoltage(void);++/**+ * Enable or disable external battery current measuring.+ */+void pmEnableExtBatteryCurrMeasuring(const deckPin_t pin, float ampPerVolt);++/**+ * Measure an external current.+ */+float pmMeasureExtBatteryCurrent(void);++#endif /* PM_H_ */+#endif\ No newline at end of filediff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/pm_esplane.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/pm_esplane.hnew file mode 100644index 0000000..f000d00--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/pm_esplane.h@@ -0,0 +1,181 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * pm_esplane.h - Power Management driver and functions.+ */++#ifndef PM_H_+#define PM_H_++#include "esp_idf_version.h"+#include "syslink.h"+#include "driver/adc.h"+//#include "deck.h"++#ifndef CRITICAL_LOW_VOLTAGE+ #define PM_BAT_CRITICAL_LOW_VOLTAGE 3.0f+#else+ #define PM_BAT_CRITICAL_LOW_VOLTAGE CRITICAL_LOW_VOLTAGE+#endif+#ifndef CRITICAL_LOW_TIMEOUT+ #define PM_BAT_CRITICAL_LOW_TIMEOUT M2T(1000 * 5) // 5 sec default+#else+ #define PM_BAT_CRITICAL_LOW_TIMEOUT CRITICAL_LOW_TIMEOUT+#endif++#ifndef LOW_VOLTAGE+ #define PM_BAT_LOW_VOLTAGE 3.2f+#else+ #define PM_BAT_LOW_VOLTAGE LOW_VOLTAGE+#endif+#ifndef LOW_TIMEOUT+ #define PM_BAT_LOW_TIMEOUT M2T(1000 * 5) // 5 sec default+#else+ #define PM_BAT_LOW_TIMEOUT LOW_TIMEOUT+#endif++#ifndef SYSTEM_SHUTDOWN_TIMEOUT+ #define PM_SYSTEM_SHUTDOWN_TIMEOUT M2T(1000 * 60 * 5) // 5 min default+#else+ #define PM_SYSTEM_SHUTDOWN_TIMEOUT M2T(1000 * 60 * SYSTEM_SHUTDOWN_TIMEOUT)+#endif++#define PM_BAT_DIVIDER 3.0f+#define PM_BAT_ADC_FOR_3_VOLT (int32_t)(((3.0f / PM_BAT_DIVIDER) / 2.8f) * 4096)+#define PM_BAT_ADC_FOR_1p2_VOLT (int32_t)(((1.2f / PM_BAT_DIVIDER) / 2.8f) * 4096)++#define PM_BAT_IIR_SHIFT 8+/**+ * Set PM_BAT_WANTED_LPF_CUTOFF_HZ to the wanted cut-off freq in Hz.+ */+#define PM_BAT_WANTED_LPF_CUTOFF_HZ 1++/**+ * Attenuation should be between 1 to 256.+ *+ * f0 = fs / 2*pi*attenuation.+ * attenuation = fs / 2*pi*f0+ */+#define PM_BAT_IIR_LPF_ATTENUATION (int)(ADC_SAMPLING_FREQ / (int)(2 * 3.1415f * PM_BAT_WANTED_LPF_CUTOFF_HZ))+#define PM_BAT_IIR_LPF_ATT_FACTOR (int)((1<<PM_BAT_IIR_SHIFT) / PM_BAT_IIR_LPF_ATTENUATION)++typedef enum+{+ battery,+ charging,+ charged,+ lowPower,+ shutDown,+} PMStates;++typedef enum+{+ charge100mA,+ charge300mA,+ charge500mA,+ chargeMax,+} PMChargeStates;++typedef enum+{+ USBNone,+ USB500mA,+ USBWallAdapter,+} PMUSBPower;++void pmInit(void);++bool pmTest(void);++/**+ * Power management task+ */+void pmTask(void *param);++void pmSetChargeState(PMChargeStates chgState);+void pmSyslinkUpdate(SyslinkPacket *slp);++/**+ * Returns the battery voltage i volts as a float+ */+float pmGetBatteryVoltage(void);++/**+ * Returns the min battery voltage i volts as a float+ */+float pmGetBatteryVoltageMin(void);++/**+ * Returns the max battery voltage i volts as a float+ */+float pmGetBatteryVoltageMax(void);++/**+ * Updates and calculates battery values.+ * Should be called for every new adcValues sample.+ */+//void pmBatteryUpdate(AdcGroup* adcValues);++/**+ * Returns true if the battery is below its low capacity threshold for an+ * extended period of time.+ */+bool pmIsBatteryLow(void);++/**+ * Returns true if the charger is currently connected+ */+bool pmIsChargerConnected(void);++/**+ * Returns true if the battery is currently charging+ */+bool pmIsCharging(void);++/**+ * Returns true if the battery is currently in use+ */+bool pmIsDischarging(void);++/**+ * Enable or disable external battery voltage measuring.+ */+void pmEnableExtBatteryVoltMeasuring(uint8_t pin, float multiplier);++/**+ * Measure an external voltage.+ */+float pmMeasureExtBatteryVoltage(void);++/**+ * Enable or disable external battery current measuring.+ */+void pmEnableExtBatteryCurrMeasuring(uint8_t pin, float ampPerVolt);++/**+ * Measure an external current.+ */+float pmMeasureExtBatteryCurrent(void);++#endif /* PM_H_ */diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/proximity.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/proximity.hnew file mode 100644index 0000000..749a08d--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/proximity.h@@ -0,0 +1,74 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2015 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * proximity.h - Interface to hardware abstraction layer for proximity sensors+ */++#ifndef __PROXIMITY_H__+#define __PROXIMITY_H__++#include <stdint.h>++/**+ * \def PROXIMITY_ENABLED+ * Enable the proximity measurement subsystem.+ */+//#define PROXIMITY_ENABLED++/**+ * \def PROXIMITY_TASK_FREQ+ * The frequency the proximity task runs at. This is the same as the sampling frequency for the distance measurements.+ *+ * Of the supported sensor, the following maximum frequencies apply:+ *+ * MaxBotix LV-MaxSonar-EZ4 (MB1040): 20Hz+ */+#define PROXIMITY_TASK_FREQ 20++/**+ * Number of samples in the sliding window. Used for average and median calculations.+ * When using median calculations, this should be an odd number.+ *+ * Initial testing suggests the following values:+ *+ * MaxBotix LV-MaxSonar-EZ4 (MB1040): 9 (for median values, with PROXIMITY_TASK_FREQ=20Hz)+ */+#define PROXIMITY_SWIN_SIZE 9++/**+ * \def PROXIMITY_LOG_ENABLED+ * Uncomment to enable log variables.+ */+//#define PROXIMITY_LOG_ENABLED++void proximityInit(void);++uint32_t proximityGetDistance(void);++uint32_t proximityGetDistanceAvg(void);++uint32_t proximityGetDistanceMedian(void);++uint32_t proximityGetAccuracy(void);++#endifdiff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/radiolink.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/radiolink.hnew file mode 100644index 0000000..293c5c6--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/radiolink.h@@ -0,0 +1,63 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * radiolink.c - Radio link layer+ */++#ifndef __RADIO_H__+#define __RADIO_H__++#include <stdint.h>+#include <stdbool.h>+#include "syslink.h"++#define P2P_MAX_DATA_SIZE 60++typedef struct _P2PPacket+{+ uint8_t size; //< Size of data+ uint8_t rssi; //< Received Signal Strength Intensity+ union {+ struct {+ uint8_t port; //< Header selecting channel and port+ uint8_t data[P2P_MAX_DATA_SIZE]; //< Data+ };+ uint8_t raw[P2P_MAX_DATA_SIZE+1]; //< The full packet "raw"+ };+} __attribute__((packed)) P2PPacket;++typedef void (*P2PCallback)(P2PPacket *);++void radiolinkInit(void);+bool radiolinkTest(void);+void radiolinkSetChannel(uint8_t channel);+void radiolinkSetDatarate(uint8_t datarate);+void radiolinkSetAddress(uint64_t address);+void radiolinkSetPowerDbm(int8_t powerDbm);+void radiolinkSyslinkDispatch(SyslinkPacket *slp);+struct crtpLinkOperations * radiolinkGetLink();+bool radiolinkSendP2PPacketBroadcast(P2PPacket *p2pp);+void p2pRegisterCB(P2PCallback cb);+++#endif //__RADIO_H__diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors.hnew file mode 100644index 0000000..0f89834--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors.h@@ -0,0 +1,61 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2016 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * sensors.h - Sensors interface+ */+#ifndef __SENSORS_H__+#define __SENSORS_H__++#include "stabilizer_types.h"++typedef enum { ACC_MODE_PROPTEST, ACC_MODE_FLIGHT } accModes;++void sensorsInit(void);+bool sensorsTest(void);+bool sensorsAreCalibrated(void);++/**+ * More extensive test of the sensors+ */+bool sensorsManufacturingTest(void);++// For legacy control+void sensorsAcquire(sensorData_t *sensors, const uint32_t tick);++/**+ * This function should block and unlock at 1KhZ+ */+void sensorsWaitDataReady(void);++// Allows individual sensor measurement+bool sensorsReadGyro(Axis3f *gyro);+bool sensorsReadAcc(Axis3f *acc);+bool sensorsReadMag(Axis3f *mag);+bool sensorsReadBaro(baro_t *baro);++/**+ * Set acc mode, one of accModes enum+ */+void sensorsSetAccMode(accModes accMode);++#endif //__SENSORS_H__diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_bmi088_bmp388.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_bmi088_bmp388.hnew file mode 100644index 0000000..30944a5--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_bmi088_bmp388.h@@ -0,0 +1,44 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2018 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ */++#ifndef __SENSORS_BMI088_BMP388_H__+#define __SENSORS_BMI088_BMP388_H__++#include "sensors.h"++void sensorsBmi088Bmp388Init(void);+bool sensorsBmi088Bmp388Test(void);+bool sensorsBmi088Bmp388AreCalibrated(void);+bool sensorsBmi088Bmp388ManufacturingTest(void);+void sensorsBmi088Bmp388Acquire(sensorData_t *sensors, const uint32_t tick);+void sensorsBmi088Bmp388WaitDataReady(void);+bool sensorsBmi088Bmp388ReadGyro(Axis3f *gyro);+bool sensorsBmi088Bmp388ReadAcc(Axis3f *acc);+bool sensorsBmi088Bmp388ReadMag(Axis3f *mag);+bool sensorsBmi088Bmp388ReadBaro(baro_t *baro);+void sensorsBmi088Bmp388SetAccMode(accModes accMode);+void sensorsBmi088Bmp388DataAvailableCallback(void);++#endif // __SENSORS_BMI088_BMP388_H__\ No newline at end of filediff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_bmi088_spi_bmp388.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_bmi088_spi_bmp388.hnew file mode 100644index 0000000..556a7e1--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_bmi088_spi_bmp388.h@@ -0,0 +1,44 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2018 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ */++#ifndef __SENSORS_BMI088SPI_BMP388_H__+#define __SENSORS_BMI088SPI_BMP388_H__++#include "sensors.h"++void sensorsBmi088SpiBmp388Init(void);+bool sensorsBmi088SpiBmp388Test(void);+bool sensorsBmi088SpiBmp388AreCalibrated(void);+bool sensorsBmi088SpiBmp388ManufacturingTest(void);+void sensorsBmi088SpiBmp388Acquire(sensorData_t *sensors, const uint32_t tick);+void sensorsBmi088SpiBmp388WaitDataReady(void);+bool sensorsBmi088SpiBmp388ReadGyro(Axis3f *gyro);+bool sensorsBmi088SpiBmp388ReadAcc(Axis3f *acc);+bool sensorsBmi088SpiBmp388ReadMag(Axis3f *mag);+bool sensorsBmi088SpiBmp388ReadBaro(baro_t *baro);+void sensorsBmi088SpiBmp388SetAccMode(accModes accMode);+void sensorsBmi088SpiBmp388DataAvailableCallback(void);++#endif // __SENSORS_BMI088SPI_BMP388_H__\ No newline at end of filediff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_bosch.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_bosch.hnew file mode 100644index 0000000..9e7269c--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_bosch.h@@ -0,0 +1,44 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2016 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * sensors_bosch.h - Sensors interface+ */+#ifndef __SENSORS_BOSCH_H__+#define __SENSORS_BOSCH_H__++#include "sensors.h"++void sensorsBoschInit(void);+bool sensorsBoschTest(void);+bool sensorsBoschAreCalibrated(void);+bool sensorsBoschManufacturingTest(void);+void sensorsBoschAcquire(sensorData_t *sensors, const uint32_t tick);+void sensorsBoschWaitDataReady(void);+bool sensorsBoschReadGyro(Axis3f *gyro);+bool sensorsBoschReadAcc(Axis3f *acc);+bool sensorsBoschReadMag(Axis3f *mag);+bool sensorsBoschReadBaro(baro_t *baro);+void sensorsBoschSetAccMode(accModes accMode);+void sensorsBoschDataAvailableCallback(void);++#endif /* __SENSORS_BOSCH_H__ */diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_mpu6050_hm5883L_ms5611.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_mpu6050_hm5883L_ms5611.hnew file mode 100644index 0000000..847b731--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_mpu6050_hm5883L_ms5611.h@@ -0,0 +1,44 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2018 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ */++#ifndef __SENSORS_MPU9250_LPS25H_H__+#define __SENSORS_MPU9250_LPS25H_H__++#include "sensors.h"++void sensorsMpu6050Hmc5883lMs5611Init(void);+bool sensorsMpu6050Hmc5883lMs5611Test(void);+bool sensorsMpu6050Hmc5883lMs5611AreCalibrated(void);+bool sensorsMpu6050Hmc5883lMs5611ManufacturingTest(void);+void sensorsMpu6050Hmc5883lMs5611Acquire(sensorData_t *sensors, const uint32_t tick);+void sensorsMpu6050Hmc5883lMs5611WaitDataReady(void);+bool sensorsMpu6050Hmc5883lMs5611ReadGyro(Axis3f *gyro);+bool sensorsMpu6050Hmc5883lMs5611ReadAcc(Axis3f *acc);+bool sensorsMpu6050Hmc5883lMs5611ReadMag(Axis3f *mag);+bool sensorsMpu6050Hmc5883lMs5611ReadBaro(baro_t *baro);+void sensorsMpu6050Hmc5883lMs5611SetAccMode(accModes accMode);++#endif // __SENSORS_MPU9250_LPS25H_H__\ No newline at end of filediff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_mpu9250_lps25h.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_mpu9250_lps25h.hnew file mode 100644index 0000000..4df6afc--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/sensors_mpu9250_lps25h.h@@ -0,0 +1,43 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2018 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ */++#ifndef __SENSORS_MPU9250_LPS25H_H__+#define __SENSORS_MPU9250_LPS25H_H__++#include "sensors.h"++void sensorsMpu9250Lps25hInit(void);+bool sensorsMpu9250Lps25hTest(void);+bool sensorsMpu9250Lps25hAreCalibrated(void);+bool sensorsMpu9250Lps25hManufacturingTest(void);+void sensorsMpu9250Lps25hAcquire(sensorData_t *sensors, const uint32_t tick);+void sensorsMpu9250Lps25hWaitDataReady(void);+bool sensorsMpu9250Lps25hReadGyro(Axis3f *gyro);+bool sensorsMpu9250Lps25hReadAcc(Axis3f *acc);+bool sensorsMpu9250Lps25hReadMag(Axis3f *mag);+bool sensorsMpu9250Lps25hReadBaro(baro_t *baro);+void sensorsMpu9250Lps25hSetAccMode(accModes accMode);++#endif // __SENSORS_MPU9250_LPS25H_H__\ No newline at end of filediff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/storage.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/storage.hnew file mode 100644index 0000000..e55bdfe--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/storage.h@@ -0,0 +1,87 @@+/**+ * ,---------, ____ _ __+ * | ,-^-, | / __ )(_) /_______________ _____ ___+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2019 - 2020 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * storage.h: Key/Buffer persistant storage+ *+ */+++#pragma once++#include <stdbool.h>+#include <stddef.h>++/**+ * Initialize the storage subsystem.+ *+ * This function is not reentrant.+ */+void storageInit();++/**+ * Test the storage subsystem+ *+ * Check the key/buffer table health. If the table is not healthy, format it.+ */+bool storageTest();++/**+ * Store a buffer in a key. If the key already exist in the table,+ * it will be replaced.+ *+ * This function can take a lot of time to complete: if there is no space for the new buffer,+ * the memory is going to be defragmented before the new buffer is written.+ *+ * This function can fail either if there is no place left in memory or if the memory+ * is corrupted.+ *+ * @param[key] Null terminated string for the key. Its length must be between 1 and 255.+ * @param[buffer] Pointer to the buffer to store+ * @param[length] Length of the buffer to store+ *+ * @return true in case of success, false otherwise.+ */+bool storageStore(char* key, const void* buffer, size_t length);++/**+ * Fetch a buffer from the memory at some key.+ *+ * @param[key] Null terminated string for the key. Its length must be between 1 and 255.+ * @param[buffer] Pointer to the buffer where the data should be copied+ * @param[length] Max length to copy in the buffer+ *+ * @return length of the data read. This is the lowest length between the length of the+ * receiving buffer, and the length of the data in memory. If the key is not found+ * this function returns 0.+ */+size_t storageFetch(char *key, void* buffer, size_t length);++/**+ * Deletes and entry from the storage.+ *+ * @param[key] Null terminated string for the key. Its length must be between 1 and 255.+ *+ * @return true in case of success. false if the key was not found or if an error occured.+ */+bool storageDelete(char* key);diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/syslink.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/syslink.hnew file mode 100644index 0000000..ca4408b--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/syslink.h@@ -0,0 +1,90 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2012 BitCraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * syslink.h: Implementation of the link between MCU+ */++#ifndef __SYSLINK_H__+#define __SYSLINK_H__++#include <stdbool.h>++#define SYSLINK_MTU 64++#define CRTP_START_BYTE 0xAA+#define SYSLINK_START_BYTE1 0xBC+#define SYSLINK_START_BYTE2 0xCF++// Defined packet types+#define SYSLINK_GROUP_MASK 0xF0++#define SYSLINK_RADIO_GROUP 0x00+#define SYSLINK_RADIO_RAW 0x00+#define SYSLINK_RADIO_CHANNEL 0x01+#define SYSLINK_RADIO_DATARATE 0x02+#define SYSLINK_RADIO_CONTWAVE 0x03+#define SYSLINK_RADIO_RSSI 0x04+#define SYSLINK_RADIO_ADDRESS 0x05+#define SYSLINK_RADIO_RAW_BROADCAST 0x06+#define SYSLINK_RADIO_POWER 0x07+#define SYSLINK_RADIO_P2P 0x08+#define SYSLINK_RADIO_P2P_ACK 0x09+#define SYSLINK_RADIO_P2P_BROADCAST 0x0A++#define SYSLINK_PM_GROUP 0x10+#define SYSLINK_PM_SOURCE 0x10+#define SYSLINK_PM_ONOFF_SWITCHOFF 0x11+#define SYSLINK_PM_BATTERY_VOLTAGE 0x12+#define SYSLINK_PM_BATTERY_STATE 0x13+#define SYSLINK_PM_BATTERY_AUTOUPDATE 0x14++#define SYSLINK_OW_GROUP 0x20+#define SYSLINK_OW_SCAN 0x20+#define SYSLINK_OW_GETINFO 0x21+#define SYSLINK_OW_READ 0x22+#define SYSLINK_OW_WRITE 0x23++typedef struct _SyslinkPacket+{+ uint8_t type;+ uint8_t length;+ char data[SYSLINK_MTU];+} __attribute__((packed)) SyslinkPacket;++typedef enum+{+ waitForFirstStart,+ waitForSecondStart,+ waitForType,+ waitForLength,+ waitForData,+ waitForChksum1,+ waitForChksum2+} SyslinkRxState;+++void syslinkInit();+bool syslinkTest();+int syslinkSendPacket(SyslinkPacket *slp);++#endifdiff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/usb.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usb.hnew file mode 100644index 0000000..0a9ebdf--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usb.h@@ -0,0 +1,85 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * usb.h - USB CRTP link and raw access functions+ */+#ifndef USB_H_+#define USB_H_++#include <stdbool.h>+#include <stdint.h>++#include "usbd_conf.h"+++#define USB_RX_TX_PACKET_SIZE (64)++/* Structure used for in/out data via USB */+typedef struct+{+ uint8_t size;+ uint8_t data[USB_RX_TX_PACKET_SIZE];+} USBPacket;++/**+ * Initialize the UART.+ *+ * @note Initialize CRTP link only if USE_CRTP_UART is defined+ */+void usbInit(void);++/**+ * Test the UART status.+ *+ * @return true if the UART is initialized+ */+bool usbTest(void);++/**+ * Get CRTP link data structure+ *+ * @return Address of the crtp link operations structure.+ */+struct crtpLinkOperations * usbGetLink();++/**+ * Get data from rx queue with timeout.+ * @param[out] c Byte of data+ *+ * @return true if byte received, false if timout reached.+ */+bool usbGetDataBlocking(USBPacket *in);++/**+ * Sends raw data using a lock. Should be used from+ * exception functions and for debugging when a lot of data+ * should be transfered.+ * @param[in] size Number of bytes to send+ * @param[in] data Pointer to data+ *+ * @note If UART Crtp link is activated this function does nothing+ */+bool usbSendData(uint32_t size, uint8_t* data);+++#endif /* UART_H_ */diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/usb_conf.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usb_conf.hnew file mode 100644index 0000000..5e45379--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usb_conf.h@@ -0,0 +1,313 @@+/**+ ******************************************************************************+ * @file usb_conf.h+ * @author MCD Application Team+ * @version V1.1.0+ * @date 19-March-2012+ * @brief General low level driver configuration+ ******************************************************************************+ * @attention+ *+ * <h2><center>© COPYRIGHT 2012 STMicroelectronics</center></h2>+ *+ * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");+ * You may not use this file except in compliance with the License.+ * You may obtain a copy of the License at:+ *+ * http://www.st.com/software_license_agreement_liberty_v2+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ ******************************************************************************+ */++/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef __USB_CONF__H__+#define __USB_CONF__H__++#include <sys/cdefs.h>++/* Includes ------------------------------------------------------------------*/+/*#if defined (USE_STM322xG_EVAL)+ #include "stm322xg_eval.h"+ #include "stm322xg_eval_lcd.h"+ #include "stm322xg_eval_ioe.h"+ #include "stm322xg_eval_sdio_sd.h"+#elif defined(USE_STM324xG_EVAL)+ #include "stm32f4xx.h"+ #include "stm324xg_eval.h"+ #include "stm324xg_eval_lcd.h"+ #include "stm324xg_eval_ioe.h"+ #include "stm324xg_eval_sdio_sd.h"+#elif defined (USE_STM3210C_EVAL)+ #include "stm32f10x.h"+ #include "stm3210c_eval.h"+ #include "stm3210c_eval_lcd.h"+ #include "stm3210c_eval_ioe.h"+ #include "stm3210c_eval_spi_sd.h"+#else+ #error "Missing define: Evaluation board (ie. USE_STM322xG_EVAL)"+#endif*/+++/** @addtogroup USB_OTG_DRIVER+ * @{+ */++/** @defgroup USB_CONF+ * @brief USB low level driver configuration file+ * @{+ */++/** @defgroup USB_CONF_Exported_Defines+ * @{+ */++/* USB Core and PHY interface configuration.+ Tip: To avoid modifying these defines each time you need to change the USB+ configuration, you can declare the needed define in your toolchain+ compiler preprocessor.+ */+/****************** USB OTG FS PHY CONFIGURATION *******************************+* The USB OTG FS Core supports one on-chip Full Speed PHY.+*+* The USE_EMBEDDED_PHY symbol is defined in the project compiler preprocessor+* when FS core is used.+*******************************************************************************/+#ifndef USE_USB_OTG_FS+ #define USE_USB_OTG_FS+#endif /* USE_USB_OTG_FS */++#ifdef USE_USB_OTG_FS+ #define USB_OTG_FS_CORE+#endif++/****************** USB OTG HS PHY CONFIGURATION *******************************+* The USB OTG HS Core supports two PHY interfaces:+* (i) An ULPI interface for the external High Speed PHY: the USB HS Core will+* operate in High speed mode+* (ii) An on-chip Full Speed PHY: the USB HS Core will operate in Full speed mode+*+* You can select the PHY to be used using one of these two defines:+* (i) USE_ULPI_PHY: if the USB OTG HS Core is to be used in High speed mode+* (ii) USE_EMBEDDED_PHY: if the USB OTG HS Core is to be used in Full speed mode+*+* Notes:+* - The USE_ULPI_PHY symbol is defined in the project compiler preprocessor as+* default PHY when HS core is used.+* - On STM322xG-EVAL and STM324xG-EVAL boards, only configuration(i) is available.+* Configuration (ii) need a different hardware, for more details refer to your+* STM32 device datasheet.+*******************************************************************************/+#ifndef USE_USB_OTG_HS+ //#define USE_USB_OTG_HS+#endif /* USE_USB_OTG_HS */++#ifndef USE_ULPI_PHY+ //#define USE_ULPI_PHY+#endif /* USE_ULPI_PHY */++#ifndef USE_EMBEDDED_PHY+ //#define USE_EMBEDDED_PHY+#endif /* USE_EMBEDDED_PHY */++#ifdef USE_USB_OTG_HS+ #define USB_OTG_HS_CORE+#endif++/*******************************************************************************+* FIFO Size Configuration in Device mode+*+* (i) Receive data FIFO size = RAM for setup packets ++* OUT endpoint control information ++* data OUT packets + miscellaneous+* Space = ONE 32-bits words+* --> RAM for setup packets = 10 spaces+* (n is the nbr of CTRL EPs the device core supports)+* --> OUT EP CTRL info = 1 space+* (one space for status information written to the FIFO along with each+* received packet)+* --> data OUT packets = (Largest Packet Size / 4) + 1 spaces+* (MINIMUM to receive packets)+* --> OR data OUT packets = at least 2*(Largest Packet Size / 4) + 1 spaces+* (if high-bandwidth EP is enabled or multiple isochronous EPs)+* --> miscellaneous = 1 space per OUT EP+* (one space for transfer complete status information also pushed to the+* FIFO with each endpoint's last packet)+*+* (ii)MINIMUM RAM space required for each IN EP Tx FIFO = MAX packet size for+* that particular IN EP. More space allocated in the IN EP Tx FIFO results+* in a better performance on the USB and can hide latencies on the AHB.+*+* (iii) TXn min size = 16 words. (n : Transmit FIFO index)+* (iv) When a TxFIFO is not used, the Configuration should be as follows:+* case 1 : n > m and Txn is not used (n,m : Transmit FIFO indexes)+* --> Txm can use the space allocated for Txn.+* case2 : n < m and Txn is not used (n,m : Transmit FIFO indexes)+* --> Txn should be configured with the minimum space of 16 words+* (v) The FIFO is used optimally when used TxFIFOs are allocated in the top+* of the FIFO.Ex: use EP1 and EP2 as IN instead of EP1 and EP3 as IN ones.+* (vi) In HS case 12 FIFO locations should be reserved for internal DMA registers+* so total FIFO size should be 1012 Only instead of 1024+*******************************************************************************/++/****************** USB OTG HS CONFIGURATION **********************************/+#ifdef USB_OTG_HS_CORE+ #define RX_FIFO_HS_SIZE 512+ #define TX0_FIFO_HS_SIZE 64+ #define TX1_FIFO_HS_SIZE 372+ #define TX2_FIFO_HS_SIZE 64+ #define TX3_FIFO_HS_SIZE 0+ #define TX4_FIFO_HS_SIZE 0+ #define TX5_FIFO_HS_SIZE 0++// #define USB_OTG_HS_SOF_OUTPUT_ENABLED++ #ifdef USE_ULPI_PHY+ #define USB_OTG_ULPI_PHY_ENABLED+ #endif+ #ifdef USE_EMBEDDED_PHY+ #define USB_OTG_EMBEDDED_PHY_ENABLED+ /* wakeup is working only when HS core is configured in FS mode */+ #define USB_OTG_HS_LOW_PWR_MGMT_SUPPORT+ #endif+ /* #define USB_OTG_HS_INTERNAL_DMA_ENABLED */ /* Be aware that enabling DMA mode will result in data being sent only by+ multiple of 4 packet sizes. This is due to the fact that USB DMA does+ not allow sending data from non word-aligned addresses.+ For this specific application, it is advised to not enable this option+ unless required. */+ #define USB_OTG_HS_DEDICATED_EP1_ENABLED+#endif++/****************** USB OTG FS CONFIGURATION **********************************/+#ifdef USB_OTG_FS_CORE+ #define RX_FIFO_FS_SIZE 128+ #define TX0_FIFO_FS_SIZE 32+ #define TX1_FIFO_FS_SIZE 128+ #define TX2_FIFO_FS_SIZE 32+ #define TX3_FIFO_FS_SIZE 0++// #define USB_OTG_FS_LOW_PWR_MGMT_SUPPORT+// #define USB_OTG_FS_SOF_OUTPUT_ENABLED+#endif++/****************** USB OTG MISC CONFIGURATION ********************************/+//#define VBUS_SENSING_ENABLED++/****************** USB OTG MODE CONFIGURATION ********************************/+//#define USE_HOST_MODE+#define USE_DEVICE_MODE+//#define USE_OTG_MODE++#ifndef USB_OTG_FS_CORE+ #ifndef USB_OTG_HS_CORE+ #error "USB_OTG_HS_CORE or USB_OTG_FS_CORE should be defined"+ #endif+#endif++#ifndef USE_DEVICE_MODE+ #ifndef USE_HOST_MODE+ #error "USE_DEVICE_MODE or USE_HOST_MODE should be defined"+ #endif+#endif++#ifndef USE_USB_OTG_HS+ #ifndef USE_USB_OTG_FS+ #error "USE_USB_OTG_HS or USE_USB_OTG_FS should be defined"+ #endif+#else //USE_USB_OTG_HS+ #ifndef USE_ULPI_PHY+ #ifndef USE_EMBEDDED_PHY+ #error "USE_ULPI_PHY or USE_EMBEDDED_PHY should be defined"+ #endif+ #endif+#endif++/****************** C Compilers dependant keywords ****************************/+/* In HS mode and when the DMA is used, all variables and data structures dealing+ with the DMA during the transaction process should be 4-bytes aligned */+#ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED+ #if defined (__GNUC__) /* GNU Compiler */+ #define __ALIGN_END __attribute__ ((aligned (4)))+ #define __ALIGN_BEGIN+ #else+ #define __ALIGN_END+ #if defined (__CC_ARM) /* ARM Compiler */+ #define __ALIGN_BEGIN __align(4)+ #elif defined (__ICCARM__) /* IAR Compiler */+ #define __ALIGN_BEGIN+ #elif defined (__TASKING__) /* TASKING Compiler */+ #define __ALIGN_BEGIN __align(4)+ #endif /* __CC_ARM */+ #endif /* __GNUC__ */+#else+ #define __ALIGN_BEGIN+ #define __ALIGN_END+#endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */++/* __packed keyword used to decrease the data type alignment to 1-byte */+#if defined (__CC_ARM) /* ARM Compiler */+ #define __packed __packed+#elif defined (__ICCARM__) /* IAR Compiler */+ #define __packed __packed+#elif defined ( __GNUC__ ) /* GNU Compiler */+// #define __packed __attribute__ ((__packed__))+#ifndef __packed+ #define __packed __attribute__ ((__packed__))+#endif+#elif defined (__TASKING__) /* TASKING Compiler */+ #define __packed __unaligned+#endif /* __CC_ARM */++/**+ * @}+ */+++/** @defgroup USB_CONF_Exported_Types+ * @{+ */+/**+ * @}+ */+++/** @defgroup USB_CONF_Exported_Macros+ * @{+ */+/**+ * @}+ */++/** @defgroup USB_CONF_Exported_Variables+ * @{+ */+/**+ * @}+ */++/** @defgroup USB_CONF_Exported_FunctionsPrototype+ * @{+ */+/**+ * @}+ */+++#endif //__USB_CONF__H__+++/**+ * @}+ */++/**+ * @}+ */++/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/+diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/usbd_conf.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usbd_conf.hnew file mode 100644index 0000000..d392c30--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usbd_conf.h@@ -0,0 +1,107 @@+/**+ ******************************************************************************+ * @file usbd_conf.h+ * @author MCD Application Team+ * @version V1.1.0+ * @date 19-March-2012+ * @brief USB Device configuration file+ ******************************************************************************+ * @attention+ *+ * <h2><center>© COPYRIGHT 2012 STMicroelectronics</center></h2>+ *+ * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");+ * You may not use this file except in compliance with the License.+ * You may obtain a copy of the License at:+ *+ * http://www.st.com/software_license_agreement_liberty_v2+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ ******************************************************************************+ */++/* Define to prevent recursive inclusion -------------------------------------*/+#ifndef __USBD_CONF__H__+#define __USBD_CONF__H__++/* Includes ------------------------------------------------------------------*/+#include "usb_conf.h"++/** @defgroup USB_CONF_Exported_Defines+ * @{+ */+#define USBD_CFG_MAX_NUM 1+#define USBD_ITF_MAX_NUM 1++#define USBD_SELF_POWERED++#define USB_MAX_STR_DESC_SIZ 255++/** @defgroup USB_VCP_Class_Layer_Parameter+ * @{+ */+#define CDC_IN_EP 0x81 /* EP1 for data IN */+#define CDC_OUT_EP 0x01 /* EP1 for data OUT */+#define CDC_CMD_EP 0x82 /* EP2 for CDC commands */++/* CDC Endpoints parameters: you can fine tune these values depending on the needed baudrates and performance. */+#ifdef USE_USB_OTG_HS+ #define CDC_DATA_MAX_PACKET_SIZE 512 /* Endpoint IN & OUT Packet size */+ #define CDC_CMD_PACKET_SZE 8 /* Control Endpoint Packet size */++ #define CDC_IN_FRAME_INTERVAL 40 /* Number of micro-frames between IN transfers */+ #define APP_RX_DATA_SIZE 2048 /* Total size of IN buffer:+ APP_RX_DATA_SIZE*8/MAX_BAUDARATE*1000 should be > CDC_IN_FRAME_INTERVAL*8 */+#else+ #define CDC_DATA_MAX_PACKET_SIZE 64 /* Endpoint IN & OUT Packet size */+ #define CDC_CMD_PACKET_SZE 8 /* Control Endpoint Packet size */++ #define CDC_IN_FRAME_INTERVAL 1 /* Number of frames between IN transfers */+ #define APP_RX_DATA_SIZE 2048 /* Total size of IN buffer:+ APP_RX_DATA_SIZE*8/MAX_BAUDARATE*1000 should be > CDC_IN_FRAME_INTERVAL */+#endif /* USE_USB_OTG_HS */++#define APP_FOPS CRTP_fops+/**+ * @}+ */++/** @defgroup USB_CONF_Exported_Types+ * @{+ */+/**+ * @}+ */+++/** @defgroup USB_CONF_Exported_Macros+ * @{+ */+/**+ * @}+ */++/** @defgroup USB_CONF_Exported_Variables+ * @{+ */+/**+ * @}+ */++/** @defgroup USB_CONF_Exported_FunctionsPrototype+ * @{+ */+/**+ * @}+ */+++#endif //__USBD_CONF__H__++/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/+diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/usbd_desc.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usbd_desc.hnew file mode 100644index 0000000..75b694e--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usbd_desc.h@@ -0,0 +1,120 @@+/**+ ******************************************************************************+ * @file usbd_desc.h+ * @author MCD Application Team+ * @version V1.1.0+ * @date 19-March-2012+ * @brief header file for the usbd_desc.c file+ ******************************************************************************+ * @attention+ *+ * <h2><center>© COPYRIGHT 2012 STMicroelectronics</center></h2>+ *+ * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");+ * You may not use this file except in compliance with the License.+ * You may obtain a copy of the License at:+ *+ * http://www.st.com/software_license_agreement_liberty_v2+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ ******************************************************************************+ */++/* Define to prevent recursive inclusion -------------------------------------*/++#ifndef __USB_DESC_H+#define __USB_DESC_H++/* Includes ------------------------------------------------------------------*/+#include "usbd_def.h"++/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY+ * @{+ */++/** @defgroup USB_DESC+ * @brief general defines for the usb device library file+ * @{+ */++/** @defgroup USB_DESC_Exported_Defines+ * @{+ */+#define USB_DEVICE_DESCRIPTOR_TYPE 0x01+#define USB_CONFIGURATION_DESCRIPTOR_TYPE 0x02+#define USB_STRING_DESCRIPTOR_TYPE 0x03+#define USB_INTERFACE_DESCRIPTOR_TYPE 0x04+#define USB_ENDPOINT_DESCRIPTOR_TYPE 0x05+#define USB_SIZ_DEVICE_DESC 18+#define USB_SIZ_STRING_LANGID 4++/**+ * @}+ */+++/** @defgroup USBD_DESC_Exported_TypesDefinitions+ * @{+ */+/**+ * @}+ */++++/** @defgroup USBD_DESC_Exported_Macros+ * @{+ */+/**+ * @}+ */++/** @defgroup USBD_DESC_Exported_Variables+ * @{+ */+extern uint8_t USBD_DeviceDesc [USB_SIZ_DEVICE_DESC];+extern uint8_t USBD_StrDesc[USB_MAX_STR_DESC_SIZ];+extern uint8_t USBD_OtherSpeedCfgDesc[USB_LEN_CFG_DESC];+extern uint8_t USBD_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC];+extern uint8_t USBD_LangIDDesc[USB_SIZ_STRING_LANGID];+extern USBD_DEVICE USR_desc;+/**+ * @}+ */++/** @defgroup USBD_DESC_Exported_FunctionsPrototype+ * @{+ */+++uint8_t * USBD_USR_DeviceDescriptor( uint8_t speed , uint16_t *length);+uint8_t * USBD_USR_LangIDStrDescriptor( uint8_t speed , uint16_t *length);+uint8_t * USBD_USR_ManufacturerStrDescriptor ( uint8_t speed , uint16_t *length);+uint8_t * USBD_USR_ProductStrDescriptor ( uint8_t speed , uint16_t *length);+uint8_t * USBD_USR_SerialStrDescriptor( uint8_t speed , uint16_t *length);+uint8_t * USBD_USR_ConfigStrDescriptor( uint8_t speed , uint16_t *length);+uint8_t * USBD_USR_InterfaceStrDescriptor( uint8_t speed , uint16_t *length);++#ifdef USB_SUPPORT_USER_STRING_DESC+uint8_t * USBD_USR_USRStringDesc (uint8_t speed, uint8_t idx , uint16_t *length);+#endif /* USB_SUPPORT_USER_STRING_DESC */++/**+ * @}+ */++#endif /* __USBD_DESC_H */++/**+ * @}+ */++/**+* @}+*/+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/usblink.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usblink.hnew file mode 100644index 0000000..d4a5fa9--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usblink.h@@ -0,0 +1,79 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2012 BitCraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * syslink.h: Implementation of the link between MCU+ */++#ifndef __USBLINK_H__+#define __USBLINK_H__++#include <stdbool.h>+#include "crtp.h"++//#define SYSLINK_MTU 32++#define CRTP_START_BYTE 0xAA+#define SYSLINK_START_BYTE1 0xBC+#define SYSLINK_START_BYTE2 0xCF++// Defined packet types+//#define SYSLINK_RADIO_RAW 0x00+//#define SYSLINK_RADIO_CHANNEL 0x01+//#define SYSLINK_RADIO_DATARATE 0x02+++//#define SYSLINK_PM_SOURCE 0x10++//#define SYSLINK_PM_ONOFF_SWITCHOFF 0x11++//#define SYSLINK_PM_BATTERY_VOLTAGE 0x12+//#define SYSLINK_PM_BATTERY_STATE 0x13+//#define SYSLINK_PM_BATTERY_AUTOUPDATE 0x14++//#define SYSLINK_OW_SCAN 0x20+//#define SYSLINK_OW_READ 0x21+/*+typedef struct _SyslinkPacket+{+ uint8_t type;+ uint8_t length;+ char data[SYSLINK_MTU];+} __attribute__((packed)) SyslinkPacket;++typedef enum+{+ waitForFirstStart,+ waitForSecondStart,+ waitForType,+ waitForLengt,+ waitForData,+ waitForChksum1,+ waitForChksum2+} SyslinkRxState;+*/++void usblinkInit();+bool usblinkTest();+struct crtpLinkOperations * usblinkGetLink();++#endifdiff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/usec_time.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usec_time.hnew file mode 100644index 0000000..8542f64--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/usec_time.h@@ -0,0 +1,41 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2013 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * usec_time.h - Microsecond-resolution timer.+ */+#ifndef USEC_TIME_H_+#define USEC_TIME_H_++#include <stdint.h>++/**+ * Initialize microsecond-resolution timer (TIM1).+ */+void initUsecTimer(void);++/**+ * Get microsecond-resolution timestamp.+ */+uint64_t usecTimestamp(void);++#endif /* USEC_TIME_H_ */diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/interface/wifilink.h b/Firmware/esp-drone/components/core/crazyflie/hal/interface/wifilink.hnew file mode 100644index 0000000..d0ec653--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/interface/wifilink.h@@ -0,0 +1,79 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2012 BitCraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * wifilink.h: Implementation of the link between MCU+ */++#ifndef __WIFILINK_H__+#define __WIFILINK_H__++#include <stdbool.h>+#include "crtp.h"++#define SYSLINK_MTU 64++#define CRTP_START_BYTE 0xAA+#define SYSLINK_START_BYTE1 0xBC+#define SYSLINK_START_BYTE2 0xCF++// Defined packet types+//#define SYSLINK_RADIO_RAW 0x00+//#define SYSLINK_RADIO_CHANNEL 0x01+//#define SYSLINK_RADIO_DATARATE 0x02+++//#define SYSLINK_PM_SOURCE 0x10++//#define SYSLINK_PM_ONOFF_SWITCHOFF 0x11++//#define SYSLINK_PM_BATTERY_VOLTAGE 0x12+//#define SYSLINK_PM_BATTERY_STATE 0x13+//#define SYSLINK_PM_BATTERY_AUTOUPDATE 0x14++//#define SYSLINK_OW_SCAN 0x20+//#define SYSLINK_OW_READ 0x21+/*+typedef struct _SyslinkPacket+{+ uint8_t type;+ uint8_t length;+ char data[SYSLINK_MTU];+} __attribute__((packed)) SyslinkPacket;++typedef enum+{+ waitForFirstStart,+ waitForSecondStart,+ waitForType,+ waitForLengt,+ waitForData,+ waitForChksum1,+ waitForChksum2+} SyslinkRxState;+*/+void wifilinkInit();+bool wifilinkTest();+struct crtpLinkOperations *wifilinkGetLink();++#endifdiff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/amg8833.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/amg8833.cnew file mode 100644index 0000000..06ea5ed--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/amg8833.c@@ -0,0 +1,303 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2017 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * amg8833.c - Functions for interfacing AMG8833 thermal sensor+ * Reference : https://github.com/adafruit/Adafruit_AMG88xx+ */+#include "amg8833.h"++const float AMG88xx_TEMP_CONVERSION = 0.25;+const float AMG88xx_THRM_CONVERSION = 0.0625;++static uint8_t mode = 1;++/**************************************************************************+ Setups the I2C interface and thermal camera basic registers++ @param dev Thermal camera struct+ @param I2Cx I2C driver instance+ @returns True if device is set up, false on any failure+**************************************************************************/+bool begin(AMG8833_Dev_t *dev, I2C_Dev *I2Cx)+{+ // Set I2C parameters+ dev->I2Cx = I2Cx;+ dev->devAddr = AMG88xx_ADDRESS;+ bool i2c_complete = i2cdevInit(dev->I2Cx);+ // Enter normal mode+ bool mode_selected = write8(dev, AMG88xx_PCTL, AMG88xx_NORMAL_MODE);+ // Software reset+ bool software_resetted = write8(dev, AMG88xx_RST, AMG88xx_INITIAL_RESET);+ //disable interrupts by default+ bool interrupts_set = disableInterrupt(dev);+ //set to 10 FPS+ bool fps_set = write8(dev, AMG88xx_FPSC, (AMG88xx_FPS_10 & 0x01));+ vTaskDelay(M2T(10));+ return i2c_complete && mode_selected && software_resetted &&+ interrupts_set && fps_set;+}++/**************************************************************************+ Read Infrared sensor values++ @param pdev Thermal camera struct+ @param buf the array to place the pixels in+ @param size Optionsl number of bytes to read (up to 64). Default is 64 bytes.+ @return up to 64 bytes of pixel data in buf+**************************************************************************/+void readPixels(AMG8833_Dev_t *dev, float *buf, uint8_t size)+{+ uint16_t recast;+ float converted;+ uint8_t bytesToRead = min((uint8_t) (size << 1), (uint8_t) (AMG88xx_PIXEL_ARRAY_SIZE << 1));+ uint8_t rawArray[bytesToRead];+ read(dev, AMG88xx_PIXEL_OFFSET, rawArray, bytesToRead);++ for (int i = 0; i < size; i++) {+ uint8_t pos = i << 1;+ recast = ((uint16_t) rawArray[pos + 1] << 8) | ((uint16_t) rawArray[pos]);+ converted = int12ToFloat(recast) * AMG88xx_TEMP_CONVERSION;+ buf[i] = converted;+ }+}++/**************************************************************************+ Read the onboard thermistor++ @param pdev Thermal camera struct+ @returns a the floating point temperature in degrees Celsius+**************************************************************************/+float readThermistor(AMG8833_Dev_t *dev)+{+ uint8_t raw[2];+ read(dev, AMG88xx_TTHL, raw, 2);+ uint16_t recast = ((uint16_t) raw[1] << 8) | ((uint16_t) raw[0]);+ return signedMag12ToFloat(recast) * AMG88xx_THRM_CONVERSION;+}++/**************************************************************************+ Enables the interrupt pin on the device.++ @param pdev Thermal camera struct+**************************************************************************/+bool enableInterrupt(AMG8833_Dev_t *dev)+{+ // 0 = Difference interrupt mode+ // 1 = absolute value interrupt mode+ return write8(dev, AMG88xx_INTC, (mode << 1 | 1) & 0x03);+}++/**************************************************************************+ Disables the interrupt pin on the device++ @param pdev Thermal camera struct+**************************************************************************/+bool disableInterrupt(AMG8833_Dev_t *dev)+{+ // 0 = Difference interrupt mode+ // 1 = absolute value interrupt mode+ return write8(dev, AMG88xx_INTC, (mode << 1 | 0) & 0x03);+}++/**************************************************************************+ Set the interrupt to either absolute value or difference mode++ @param pdev Thermal camera struct+ @param mode passing AMG88xx_DIFFERENCE sets the device to difference+ mode, AMG88xx_ABSOLUTE_VALUE sets to absolute value mode.+**************************************************************************/+void setInterruptMode(AMG8833_Dev_t *dev, uint8_t m)+{+ mode = m;+ write8(dev, AMG88xx_INTC, (mode << 1 | 1) & 0x03);+}++/**************************************************************************+ Read the state of the triggered interrupts on the device. The full+ interrupt register is 8 bytes in length.++ @param pdev Thermal camera struct+ @param buf the pointer to where the returned data will be stored+ @param size Optional number of bytes to read. Default is 8 bytes.+ @returns up to 8 bytes of data in buf+**************************************************************************/+void getInterrupt(AMG8833_Dev_t *dev, uint8_t *buf, uint8_t size)+{+ uint8_t bytesToRead = min(size, (uint8_t) 8);+ read(dev, AMG88xx_INT_OFFSET, buf, bytesToRead);+}++/**************************************************************************+ Clear any triggered interrupts++ @param pdev Thermal camera struct+**************************************************************************/+void clearInterrupt(AMG8833_Dev_t *dev)+{+ write8(dev, AMG88xx_RST, AMG88xx_FLAG_RESET);+}++/**************************************************************************+ Set the interrupt levels. The hysteresis value defaults to .95 * high++ @param pdev Thermal camera struct+ @param high the value above which an interrupt will be triggered+ @param low the value below which an interrupt will be triggered+**************************************************************************/+void setInterruptLevels_N(AMG8833_Dev_t *dev, float high, float low)+{+ setInterruptLevels_H(dev, high, low, high * 0.95f);+}++/**************************************************************************+ Set the interrupt levels++ @param pdev Thermal camera struct+ @param high the value above which an interrupt will be triggered+ @param low the value below which an interrupt will be triggered+ @param hysteresis the hysteresis value for interrupt detection+**************************************************************************/+void setInterruptLevels_H(AMG8833_Dev_t *dev, float high, float low,+ float hysteresis)+{+ int highConv = high / AMG88xx_TEMP_CONVERSION;+ highConv = constrain(highConv, -4095, 4095);+ write8(dev, AMG88xx_INTHL, (highConv & 0xFF));+ write8(dev, AMG88xx_INTHH, ((highConv & 0xF) >> 4));++ int lowConv = low / AMG88xx_TEMP_CONVERSION;+ lowConv = constrain(lowConv, -4095, 4095);+ write8(dev, AMG88xx_INTLL, (lowConv & 0xFF));+ write8(dev, AMG88xx_INTLH, (((lowConv & 0xF) >> 4) & 0xF));++ int hysConv = hysteresis / AMG88xx_TEMP_CONVERSION;+ hysConv = constrain(hysConv, -4095, 4095);+ write8(dev, AMG88xx_IHYSL, (hysConv & 0xFF));+ write8(dev, AMG88xx_IHYSH, (((hysConv & 0xF) >> 4) & 0xF));+}++/**************************************************************************+ Set the moving average mode.++ @param pdev Thermal camera struct+ @param mode If false, no moving average. If true, twice the moving average+**************************************************************************/+void setMovingAverageMode(AMG8833_Dev_t *dev, bool mode)+{+ write8(dev, AMG88xx_AVE, (mode << 5));+}++/**************************************************************************+ Read one byte of data from the specified register++ @param dev Thermal camera struct+ @param reg the register to read+ @returns one byte of register data+**************************************************************************/+uint8_t read8(AMG8833_Dev_t *dev, uint8_t reg)+{+ uint8_t ret;+ read(dev, reg, &ret, 1);+ return ret;+}++/**************************************************************************+ Read a chunk of bytes of data from the specified register++ @param dev Thermal camera struct+ @param reg the register to read+ @param buf integer buffer to save read bytes+ @param num number of bytes need to be read+**************************************************************************/+void read(AMG8833_Dev_t *dev, uint8_t reg, uint8_t *buf, uint8_t num)+{+ i2cdevReadReg8(dev->I2Cx, dev->devAddr, reg, num, buf);+}++/**************************************************************************+ Write one byte of data to the specified register++ @param dev Thermal camera struct+ @param reg the register to write to+ @param value the value to write+ @returns result of the write operation+**************************************************************************/+bool write8(AMG8833_Dev_t *dev, uint16_t reg, uint8_t value)+{+ return (i2cdevWrite16(dev->I2Cx, dev->devAddr, reg, 1, &value));+}++/**************************************************************************+ Read one byte of data from the specified register++ @param dev Thermal camera struct+ @param reg the register to write+ @param buf integer buffer containing data to write+ @param num number of bytes need to be written+**************************************************************************/+void write(AMG8833_Dev_t *dev, uint8_t reg, uint8_t *buf, uint8_t num)+{+ for (int i = 0; i < num; i++) {+ write8(dev, reg, buf[i]);+ }+}++/**************************************************************************+ Convert a 12-bit signed magnitude value to a floating point number++ @param val the 12-bit signed magnitude value to be converted+ @returns the converted floating point value+**************************************************************************/+float signedMag12ToFloat(uint16_t val)+{+ // Take first 11 bits as absolute val+ uint16_t absVal = (val & 0x7FF);+ return (val & 0x800) ? 0 - (float) absVal : (float) absVal;+}++/**************************************************************************+ Convert a 12-bit integer two's complement value to a floating point number++ @param val the 12-bit integer two's complement value to be converted+ @returns the converted floating point value+**************************************************************************/+float int12ToFloat(uint16_t val)+{+ // Shift to left so that sign bit of 12 bit integer number is placed on+ // sign bit of 16 bit signed integer number+ int16_t sVal = (val << 4);+ // Shift back the signed number, return converts to float+ return sVal >> 4;+}++/**************************************************************************+ Finds the minimum value between two integers++ @param a first integer value+ @param b second integer value+ @returns the minimum of a and b integers+**************************************************************************/+uint8_t min(uint8_t a, uint8_t b)+{+ return (a < b) ? a : b;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/buzzer.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/buzzer.cnew file mode 100644index 0000000..98b45d1--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/buzzer.c@@ -0,0 +1,64 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * buzzer.c - Functions for interfacing with decks with buzzers+ */+#define DEBUG_MODULE "BUZZER"++#include "buzzer.h"+//#include "buzzdeck.h"+#include "sdkconfig.h"++static struct buzzerControl * ctrl;++extern void buzzDeckInit();++void buzzerInit()+{+#ifdef CONFIG_BUZZER_ON+ buzzDeckInit();+#endif+}++bool buzzerTest()+{+ return true;+}++void buzzerOff()+{+ if (ctrl)+ ctrl->off();+}++void buzzerOn(uint32_t freq)+{+ if (ctrl)+ ctrl->on(freq);+}++void buzzerSetControl(struct buzzerControl * bc)+{+ ctrl = bc;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/freeRTOSdebug.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/freeRTOSdebug.cnew file mode 100644index 0000000..4aaaad5--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/freeRTOSdebug.c@@ -0,0 +1,107 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * debug.c - Various debug functions+ */+#include <stdint.h>++#include "freertos/FreeRTOSConfig.h"+#include "FreeRTOS.h"+#include "task.h"++#include "config.h"+#define DEBUG_MODULE "FreeRTOSConfig"+#include "debug_cf.h"+#include "nvicconf.h"+#include "led.h"+#include "power_distribution.h"++uint32_t traceTickCount;++//TODO:disable system hook now+// void vApplicationMallocFailedHook( void )+// {+// portDISABLE_INTERRUPTS();+// DEBUG_PRINTE("Malloc failed!\n");+// ledSet(ERR_LED1, 1);+// ledSet(ERR_LED2, 1);+// powerStop();+// storeAssertTextData("Malloc failed");+// while(1);+// }++// #if (configCHECK_FOR_STACK_OVERFLOW > 0)+// void vApplicationStackOverflowHook(xTaskHandle *pxTask, signed portCHAR *pcTaskName)+// {+// portDISABLE_INTERRUPTS();+// DEBUG_PRINT("\nStack overflow!\n");+// ledSet(ERR_LED1, 1);+// ledSet(ERR_LED2, 1);+// powerStop();+// storeAssertTextData("Stack overflow");+// while(1);+// }+// #endif++#ifdef UART_OUTPUT_TRACE_DATA+void debugSendTraceInfo(unsigned int taskNbr)+{+ uint32_t traceData;+ traceData = (taskNbr << 29) | (((traceTickCount << 16) + TIM1->CNT) & 0x1FFFFFF);+ uartSendDataDma(sizeof(traceData), (uint8_t*)&traceData);+}++void debugInitTrace(void)+{+ /*TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;+ NVIC_InitTypeDef NVIC_InitStructure;++ //Enable the Timer+ RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);++ //Timer configuration+ TIM_TimeBaseStructure.TIM_Period = 0xFFFF;+ TIM_TimeBaseStructure.TIM_Prescaler = 72;+ TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;+ TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;+ TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;+ TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);++ NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_IRQn;+ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_TRACE_TIM_PRI;+ NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;+ NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;+ NVIC_Init(&NVIC_InitStructure);++ DBGMCU_Config(DBGMCU_TIM1_STOP, ENABLE);+ TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE);+ TIM_Cmd(TIM1, ENABLE);++ traceTickCount = 0;*/+}+#else+void debugSendTraceInfo(unsigned int taskNbr)+{+}+#endifdiff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/ledseq.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/ledseq.cnew file mode 100644index 0000000..4240d47--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/ledseq.c@@ -0,0 +1,405 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2020 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */++/*+ * ledseq.c - LED sequence handler+ */++#include <stdbool.h>++#include "ledseq.h"++#include "FreeRTOS.h"+#include "timers.h"+#include "semphr.h"+#include "static_mem.h"++#include "led.h"+#include "stm32_legacy.h"+#include "config.h"++#ifdef CALIBRATED_LED_MORSE+ #define DOT 100+ #define DASH (3 * DOT)+ #define GAP DOT+ #define LETTER_GAP (3 * DOT)+ #define WORD_GAP (7 * DOT)+#endif // #ifdef CALIBRATED_LED_MORSE++#define LEDSEQ_CHARGE_CYCLE_TIME_500MA 1000+#define LEDSEQ_CHARGE_CYCLE_TIME_MAX 500++/* Led sequences */+ledseqStep_t seq_lowbat_def[] = {+ { true, LEDSEQ_WAITMS(1000)},+ { 0, LEDSEQ_LOOP},+};++ledseqContext_t seq_lowbat = {+ .sequence = seq_lowbat_def,+ .led = LOWBAT_LED,+};++#define NO_CONTEXT 0+ledseqContext_t* sequences = NO_CONTEXT;++ledseqStep_t seq_calibrated_def[] = {+#ifndef CALIBRATED_LED_MORSE+ { true, LEDSEQ_WAITMS(50)},+ {false, LEDSEQ_WAITMS(450)},+ { 0, LEDSEQ_LOOP},+#else+ { true, LEDSEQ_WAITMS(DASH)},+ {false, LEDSEQ_WAITMS(GAP)},+ { true, LEDSEQ_WAITMS(DOT)},+ {false, LEDSEQ_WAITMS(GAP)},+ { true, LEDSEQ_WAITMS(DASH)},+ {false, LEDSEQ_WAITMS(GAP)},+ { true, LEDSEQ_WAITMS(DOT)},+ {false, LEDSEQ_WAITMS(LETTER_GAP)},+ { true, LEDSEQ_WAITMS(DOT)},+ {false, LEDSEQ_WAITMS(GAP)},+ { true, LEDSEQ_WAITMS(DOT)},+ {false, LEDSEQ_WAITMS(GAP)},+ { true, LEDSEQ_WAITMS(DASH)},+ {false, LEDSEQ_WAITMS(GAP)},+ { true, LEDSEQ_WAITMS(DOT)},+ {false, LEDSEQ_WAITMS(WORD_GAP)},+ { 0, LEDSEQ_LOOP},+#endif // ifndef CALIBRATED_LED_MORSE+};++ledseqContext_t seq_calibrated = {+ .sequence = seq_calibrated_def,+ .led = SYS_LED,+};++ledseqStep_t seq_alive_def[] = {+ { true, LEDSEQ_WAITMS(50)},+ {false, LEDSEQ_WAITMS(1950)},+ { 0, LEDSEQ_LOOP},+};++ledseqContext_t seq_alive = {+ .sequence = seq_alive_def,+ .led = SYS_LED,+};++ledseqStep_t seq_linkup_def[] = {+ { true, LEDSEQ_WAITMS(1)},+ {false, LEDSEQ_WAITMS(0)},+ { 0, LEDSEQ_STOP},+};++ledseqContext_t seq_linkUp = {+ .sequence = seq_linkup_def,+ .led = LINK_LED,+};++ledseqContext_t seq_linkDown = {+ .sequence = seq_linkup_def,+ .led = LINK_DOWN_LED,+};++ledseqStep_t seq_charged_def[] = {+ { true, LEDSEQ_WAITMS(1000)},+ { 0, LEDSEQ_LOOP},+};++ledseqContext_t seq_charged = {+ .sequence = seq_charged_def,+ .led = CHG_LED,+};++ledseqStep_t seq_charging_def[] = {+ { true, LEDSEQ_WAITMS(200)},+ {false, LEDSEQ_WAITMS(800)},+ { 0, LEDSEQ_LOOP},+};++ledseqContext_t seq_charging = {+ .sequence = seq_charging_def,+ .led = CHG_LED,+};++ledseqStep_t seq_testPassed_def[] = {+ { true, LEDSEQ_WAITMS(50)},+ {false, LEDSEQ_WAITMS(50)},+ { true, LEDSEQ_WAITMS(50)},+ {false, LEDSEQ_WAITMS(50)},+ { true, LEDSEQ_WAITMS(50)},+ {false, LEDSEQ_WAITMS(50)},+ { true, LEDSEQ_WAITMS(50)},+ {false, LEDSEQ_WAITMS(50)},+ { true, LEDSEQ_WAITMS(50)},+ {false, LEDSEQ_WAITMS(50)},+ { true, LEDSEQ_WAITMS(50)},+ {false, LEDSEQ_WAITMS(50)},+ { true, LEDSEQ_WAITMS(50)},+ {false, LEDSEQ_WAITMS(50)},+ {false, LEDSEQ_STOP},+};++ledseqContext_t seq_testPassed = {+ .sequence = seq_testPassed_def,+ .led = LINK_LED,+};++ledseqContext_t seq_testFailed = {+ .sequence = seq_testPassed_def,+ .led = SYS_LED,+};++struct ledseqCmd_s {+ enum {run, stop} command;+ ledseqContext_t *sequence;+};++/* Led sequence handling machine implementation */+static void runLedseq(xTimerHandle xTimer);+static void updateActive(led_t led);++NO_DMA_CCM_SAFE_ZERO_INIT static ledseqContext_t* activeSeq[LED_NUM];++NO_DMA_CCM_SAFE_ZERO_INIT static xTimerHandle timer[LED_NUM];+NO_DMA_CCM_SAFE_ZERO_INIT static StaticTimer_t timerBuffer[LED_NUM];++static xSemaphoreHandle ledseqMutex;+static xQueueHandle ledseqCmdQueue;++static bool isInit = false;+static bool ledseqEnabled = false;++static void lesdeqCmdTask(void* param);++void ledseqInit() {+ if(isInit) {+ return;+ }++ ledInit();++ /* Led sequence priority */+ ledseqRegisterSequence(&seq_testPassed);+ ledseqRegisterSequence(&seq_testFailed);+ ledseqRegisterSequence(&seq_lowbat);+ ledseqRegisterSequence(&seq_charged);+ ledseqRegisterSequence(&seq_charging);+ ledseqRegisterSequence(&seq_calibrated);+ ledseqRegisterSequence(&seq_alive);+ ledseqRegisterSequence(&seq_linkUp);+ ledseqRegisterSequence(&seq_linkDown);++ //Initialise the sequences state+ for(int i=0; i<LED_NUM; i++) {+ activeSeq[i] = 0;+ }++ //Init the soft timers that runs the led sequences for each leds+ for(int i=0; i<LED_NUM; i++) {+ timer[i] = xTimerCreateStatic("ledseqTimer", M2T(1000), pdFALSE, (void*)i, runLedseq, &timerBuffer[i]);+ }++ ledseqMutex = xSemaphoreCreateMutex();++ ledseqCmdQueue = xQueueCreate(10, sizeof(struct ledseqCmd_s));+ xTaskCreate(lesdeqCmdTask, LEDSEQCMD_TASK_NAME, LEDSEQCMD_TASK_STACKSIZE, NULL, LEDSEQCMD_TASK_PRI, NULL);++ isInit = true;+}++static void lesdeqCmdTask(void* param) {+ struct ledseqCmd_s command;+ while(1) {+ xQueueReceive(ledseqCmdQueue, &command, portMAX_DELAY);++ switch(command.command) {+ case run:+ ledseqRunBlocking(command.sequence);+ break;+ case stop:+ ledseqStopBlocking(command.sequence);+ break;+ }+ }+}++bool ledseqTest(void) {+ bool status;++ status = isInit & ledTest();+ #ifdef TURN_OFF_LEDS+ ledseqEnable(false);+ ledSet(LED_BLUE_L, 0);+ #else+ ledseqEnable(true);+ #endif++ return status;+}++void ledseqEnable(bool enable) {+ ledseqEnabled = enable;+}++bool ledseqRun(ledseqContext_t *context) {+ struct ledseqCmd_s command;+ command.command = run;+ command.sequence = context;+ if (xQueueSend(ledseqCmdQueue, &command, 0) == pdPASS) {+ return true;+ }+ return false;+}++void ledseqRunBlocking(ledseqContext_t *context) {+ const led_t led = context->led;++ xSemaphoreTake(ledseqMutex, portMAX_DELAY);+ context->state = 0; //Reset the seq. to its first step+ updateActive(led);+ xSemaphoreGive(ledseqMutex);++ // Run the first step if the new seq is the active sequence+ if(activeSeq[led] == context) {+ runLedseq(timer[led]);+ }+}++void ledseqSetChargeLevel(const float chargeLevel) {+ int onTime = LEDSEQ_CHARGE_CYCLE_TIME_500MA * chargeLevel;+ int offTime = LEDSEQ_CHARGE_CYCLE_TIME_500MA - onTime;++ seq_charging.sequence[0].action = onTime;+ seq_charging.sequence[1].action = offTime;+}++bool ledseqStop(ledseqContext_t *context) {+ struct ledseqCmd_s command;+ command.command = stop;+ command.sequence = context;+ if (xQueueSend(ledseqCmdQueue, &command, 0) == pdPASS) {+ return true;+ }+ return false;+}++void ledseqStopBlocking(ledseqContext_t *context) {+ const led_t led = context->led;++ xSemaphoreTake(ledseqMutex, portMAX_DELAY);+ context->state = LEDSEQ_STOP; //Stop the seq.+ updateActive(led);+ xSemaphoreGive(ledseqMutex);++ //Run the next active sequence (if any...)+ runLedseq(timer[led]);+}++/* Center of the led sequence machine. This function is executed by the FreeRTOS+ * timers and runs the sequences+ */+static void runLedseq( xTimerHandle xTimer ) {+ if (!ledseqEnabled) {+ return;+ }++ led_t led = (led_t)pvTimerGetTimerID(xTimer);+ ledseqContext_t* context = activeSeq[led];+ if (NO_CONTEXT == context) {+ return;+ }++ bool leave = false;+ while(!leave) {+ if (context->state == LEDSEQ_STOP) {+ return;+ }++ const ledseqStep_t* step = &context->sequence[context->state];++ xSemaphoreTake(ledseqMutex, portMAX_DELAY);+ context->state++;+ led_t led = context->led;++ switch(step->action) {+ case LEDSEQ_LOOP:+ context->state = 0;+ break;+ case LEDSEQ_STOP:+ context->state = LEDSEQ_STOP;+ updateActive(led);+ break;+ default: //The step is a LED action and a time+ ledSet(led, step->value);+ if (step->action == 0) {+ break;+ }+ xTimerChangePeriod(xTimer, M2T(step->action), 0);+ xTimerStart(xTimer, 0);+ leave = true;+ break;+ }+ xSemaphoreGive(ledseqMutex);+ }+}++void ledseqRegisterSequence(ledseqContext_t* context) {+ context->state = LEDSEQ_STOP;+ context->nextContext = NO_CONTEXT;++ if (sequences == NO_CONTEXT) {+ sequences = context;+ } else {+ ledseqContext_t* last = sequences;+ if (last == context) {+ // Skip if already registered+ return;+ }++ while (last->nextContext != NO_CONTEXT) {+ last = last->nextContext;+ if (last == context) {+ // Skip if already registered+ return;+ }+ }++ last->nextContext = context;+ }+}++// Utility functions++static void updateActive(led_t led) {+ activeSeq[led] = NO_CONTEXT;+ ledSet(led, false);++ for (ledseqContext_t* sequence = sequences; sequence != 0; sequence = sequence->nextContext) {+ if (sequence->led == led && sequence->state != LEDSEQ_STOP) {+ activeSeq[led] = sequence;+ break;+ }+ }+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/ow_common.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/ow_common.cnew file mode 100644index 0000000..d4f0050--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/ow_common.c@@ -0,0 +1,85 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2020 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * ow_common.c - One-wire functions+ */++#include "ow.h"+#include "mem.h"++static bool handleMemGetSerialNr(const uint8_t selectedMem, uint8_t* serialNr);+static bool handleMemRead(const uint8_t selectedMem, const uint32_t memAddr, const uint8_t readLen, uint8_t* startOfData);+static bool handleMemWrite(const uint8_t selectedMem, const uint32_t memAddr, const uint8_t writeLen, const uint8_t* startOfData);++static MemoryOwHandlerDef_t memHandlerDef = {+ .nrOfMems = 0,+ .size = OW_MAX_SIZE,+ .getSerialNr = handleMemGetSerialNr,+ .read = handleMemRead,+ .write = handleMemWrite,+};++static bool isInit = false;++void owCommonInit() {+ if (isInit) {+ return;+ }++ owScan(&memHandlerDef.nrOfMems);+ memoryRegisterOwHandler(&memHandlerDef);++ isInit = true;+}++bool owCommonTest() {+ return isInit;+}++static bool handleMemGetSerialNr(const uint8_t selectedMem, uint8_t* serialNr) {+ return owGetinfo(selectedMem, (OwSerialNum*)serialNr);+}++static bool handleMemRead(const uint8_t selectedMem, const uint32_t memAddr, const uint8_t readLen, uint8_t* startOfData) {+ bool result = false;++ if (memAddr + readLen <= OW_MAX_SIZE) {+ if (owRead(selectedMem, memAddr, readLen, startOfData)) {+ result = true;+ }+ }++ return result;+}++static bool handleMemWrite(const uint8_t selectedMem, const uint32_t memAddr, const uint8_t writeLen, const uint8_t* startOfData) {+ bool result = false;++ if (memAddr + writeLen <= OW_MAX_SIZE) {+ if (owWrite(selectedMem, memAddr, writeLen, startOfData)) {+ result = true;+ }+ }++ return result;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/ow_none.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/ow_none.cnew file mode 100644index 0000000..6cc48e7--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/ow_none.c@@ -0,0 +1,68 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * ow.c - One-wire functions+ */+#define DEBUG_MODULE "OW"++#include <string.h>++#include "FreeRTOS.h"+#include "semphr.h"++#include "ow.h"+++void owInit()+{+ owCommonInit();+}++bool owTest()+{+ return owCommonTest();+}++void owSyslinkRecieve(SyslinkPacket *slp)+{+}++bool owScan(uint8_t *nMem)+{+ return true;+}++bool owGetinfo(uint8_t selectMem, OwSerialNum *serialNum)+{+ return false;+}++bool owRead(uint8_t selectMem, uint16_t address, uint8_t length, uint8_t *data)+{+ return false;+}++bool owWrite(uint8_t selectMem, uint16_t address, uint8_t length, const uint8_t *data)+{+ return false;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/ow_syslink.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/ow_syslink.cnew file mode 100644index 0000000..ba6fb74--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/ow_syslink.c@@ -0,0 +1,322 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * ow.c - One-wire functions+ */+#define DEBUG_MODULE "OW"++#include <string.h>++#include "FreeRTOS.h"+#include "semphr.h"++#include "ow.h"+#include "assert.h"+#include "debug_cf.h"++static xSemaphoreHandle waitForReply;+static xSemaphoreHandle lockCmdBuf;+static StaticSemaphore_t lockCmdBufBuffer;+static OwCommand owCmdBuf;+static bool owDataIsValid;++static bool owSyslinkTransfer(uint8_t type, uint8_t length);++#ifdef OW_WRITE_TEST+static uint8_t bqtestData[] =+{+ 0xEB, 0x00, 0x00, 0x00, 0x00, 0xBC, 0xFE, 0x3C, 0x00, 0x0D, 0x01, 0x08,+ 0x62, 0x63, 0x42, 0x51, 0x74, 0x65, 0x73, 0x74, 0x02, 0x01, 0x61, 0x70+};+#endif+++void owInit()+{+ syslinkInit();+ vSemaphoreCreateBinary(waitForReply);+ lockCmdBuf = xSemaphoreCreateMutexStatic(&lockCmdBufBuffer);++ // Put reply semaphore in right state.+ xSemaphoreTake(waitForReply, portMAX_DELAY);++ owCommonInit();+}++bool owTest()+{+ uint8_t nOwMem = 0;+ uint8_t nOwIter = 0;+ OwSerialNum sn;++ if (owScan(&nOwMem))+ {+ DEBUG_PRINT("Found %d.\n", nOwMem);+ }+ else+ {+ DEBUG_PRINT("Scan [FAILED].\n");+ }++ for (nOwIter = 0; nOwIter < nOwMem; nOwIter++)+ {+ if (owGetinfo(nOwIter, &sn))+ {+ DEBUG_PRINT("Serial 0x%X %X %X %X %X %X %X %X.\n",+ sn.type, sn.id[0], sn.id[1], sn.id[2],+ sn.id[3], sn.id[4], sn.id[5], sn.crc);+ }+ else+ {+ DEBUG_PRINT("Mem:%d Getinfo [FAILED].\n", nOwIter);+ }+ }++#ifdef OW_READ_TEST+ {+ static uint8_t testbuf[129];++ if (owRead(0, 0, OW_MAX_SIZE, testbuf))+ {+ for (nOwIter = 0; nOwIter < OW_MAX_SIZE; nOwIter++)+ {+ consolePrintf("%X ", testbuf[nOwIter]);+ testbuf[nOwIter] = nOwIter;+ }+ consolePrintf("\n");+ }+ }+#endif+#ifdef OW_WRITE_TEST+ if (owWrite(0, 0, sizeof(bqtestData), bqtestData))+ {+ DEBUG_PRINT("Write [OK].\n");+ }+ else+ {+ DEBUG_PRINT("Write [FAIL].\n");+ }+#endif++ return owCommonTest();+}++void owSyslinkRecieve(SyslinkPacket *slp)+{+ switch (slp->type)+ {+ case SYSLINK_OW_SCAN:+ case SYSLINK_OW_GETINFO:+ case SYSLINK_OW_READ:+ case SYSLINK_OW_WRITE:+ memcpy(&owCmdBuf, slp->data, sizeof(OwCommand));+ //DEBUG_PRINT("t:%X n:%d:%X\n", slp->type, owCmdBuf.nmem, owCmdBuf.info.memId[0]);+ owDataIsValid = true;+ break;+ default:+ // Unknown reply+ owDataIsValid = false;+ break;+ }+ xSemaphoreGive(waitForReply);+}++static bool owSyslinkTransfer(uint8_t type, uint8_t length)+{+ SyslinkPacket slp;++ ASSERT(length <= SYSLINK_MTU);++ slp.type = type;+ slp.length = length;+ memcpy(slp.data, &owCmdBuf, length);++ syslinkSendPacket(&slp);+ // Wait for reply+ if (xSemaphoreTake(waitForReply, M2T(5000)) == pdTRUE)+ //if (xSemaphoreTake(waitForReply, portMAX_DELAY))+ {+ // We have now got a reply and *owCmd has been filled with data+ if (owDataIsValid)+ {+ owDataIsValid = false;+ return true;+ }+ }+ else+ {+ DEBUG_PRINT("Cmd 0x%X timeout.\n", slp.type);+ }++ return false;+}++bool owScan(uint8_t *nMem)+{+ bool status = false;++ xSemaphoreTake(lockCmdBuf, portMAX_DELAY);++ if (owSyslinkTransfer(SYSLINK_OW_SCAN, 0))+ {+ *nMem = owCmdBuf.nmem;+ status = true;+ }+ else+ {+ status = false;+ }++ xSemaphoreGive(lockCmdBuf);++ return status;+}++bool owGetinfo(uint8_t selectMem, OwSerialNum *serialNum)+{+ bool status = false;++ xSemaphoreTake(lockCmdBuf, portMAX_DELAY);+ owCmdBuf.nmem = selectMem;++ if (owSyslinkTransfer(SYSLINK_OW_GETINFO, 1))+ {+ memcpy(serialNum, owCmdBuf.info.memId, sizeof(OwSerialNum));+ if (owCmdBuf.nmem != 0xFF)+ {+ status = true;+ }+ }+ else+ {+ status = false;+ }++ xSemaphoreGive(lockCmdBuf);++ return status;+}++bool owRead(uint8_t selectMem, uint16_t address, uint8_t length, uint8_t *data)+{+ bool status = true;+ uint16_t currAddr = address;+ uint16_t endAddr = address + length;+ uint8_t bytesRead = 0;++ ASSERT(length <= OW_MAX_SIZE);++ xSemaphoreTake(lockCmdBuf, portMAX_DELAY);+ owCmdBuf.nmem = selectMem;++ while (currAddr < endAddr)+ {+ if (endAddr - currAddr < OW_READ_SIZE)+ {+ owCmdBuf.read.address = currAddr;+ if (owSyslinkTransfer(SYSLINK_OW_READ, 3 + endAddr - currAddr))+ {+ memcpy(data + bytesRead, owCmdBuf.read.data, endAddr - currAddr);+ currAddr += endAddr - currAddr;+ bytesRead += endAddr - currAddr;+ }+ else+ {+ status = false;+ break;+ }+ }+ else // Size is bigger then OW_READ_SIZE+ {+ owCmdBuf.read.address = currAddr;+ if (owSyslinkTransfer(SYSLINK_OW_READ, 3 + OW_READ_SIZE))+ {+ memcpy(data + bytesRead, owCmdBuf.read.data, OW_READ_SIZE);+ currAddr += OW_READ_SIZE;+ bytesRead += OW_READ_SIZE;+ }+ else+ {+ status = false;+ break;+ }+ }+ }++ xSemaphoreGive(lockCmdBuf);++ return status;+}++bool owWrite(uint8_t selectMem, uint16_t address, uint8_t length, const uint8_t *data)+{+ bool status = true;+ uint16_t currAddr = address;+ uint16_t endAddr = address + length;+ uint8_t bytesWritten = 0;++ ASSERT(length <= OW_MAX_SIZE);++ xSemaphoreTake(lockCmdBuf, portMAX_DELAY);+ owCmdBuf.nmem = selectMem;++ while (currAddr < endAddr)+ {+ if (endAddr - currAddr < OW_MAX_WRITE_SIZE)+ {+ owCmdBuf.write.address = currAddr;+ owCmdBuf.write.length = endAddr - currAddr;+ memcpy(owCmdBuf.write.data, data + bytesWritten, owCmdBuf.write.length);+ if (owSyslinkTransfer(SYSLINK_OW_WRITE, 5 + owCmdBuf.write.length))+ {+ currAddr += endAddr - currAddr;+ bytesWritten += endAddr - currAddr;+ }+ else+ {+ status = false;+ break;+ }+ }+ else // Size is bigger then OW_MAX_WRITE_SIZE+ {+ owCmdBuf.write.address = currAddr;+ owCmdBuf.write.length = OW_MAX_WRITE_SIZE;+ memcpy(owCmdBuf.write.data, data + bytesWritten, owCmdBuf.write.length);+ if (owSyslinkTransfer(SYSLINK_OW_WRITE, 5 + owCmdBuf.write.length))+ {+ currAddr += OW_MAX_WRITE_SIZE;+ bytesWritten += OW_MAX_WRITE_SIZE;+ }+ else+ {+ status = false;+ break;+ }+ }+ }++ xSemaphoreGive(lockCmdBuf);++ return status;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/pca9555.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/pca9555.cnew file mode 100644index 0000000..693c148--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/pca9555.c@@ -0,0 +1,116 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2017 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * pca9555.c - Functions for interfacing PCA9555 I2C GPIO extender+ */+#define DEBUG_MODULE "PCA9555"++#include "i2cdev.h"++#include "pca9555.h"++#include "debug_cf.h"++static uint8_t devAddr;+static I2C_Dev *I2Cx;++void pca9555Init()+{+ i2cdevInit(I2C1_DEV);+ I2Cx = I2C1_DEV;+ devAddr = PCA9555_DEFAULT_ADDRESS;+}++/**+ * Reads the config registers and checks if there are any errors in reading+ * the registers+ */+bool pca9555Test()+{+ uint8_t tb;+ bool pass_set1, pass_set2;++ // Test reading the config registers+ pass_set1 = i2cdevReadByte(I2Cx, devAddr, PCA9555_CONFIG_REGA, &tb);+ pass_set2 = i2cdevReadByte(I2Cx, devAddr, PCA9555_CONFIG_REGB, &tb);++ return pass_set1 & pass_set2;+}++bool pca9555ConfigOutputRegA(uint32_t val)+{+ return i2cdevWriteByte(I2Cx, devAddr, PCA9555_CONFIG_REGA, val);+}++bool pca9555ConfigOutputRegB(uint32_t val)+{+ return i2cdevWriteByte(I2Cx, devAddr, PCA9555_CONFIG_REGB, val);+}++bool pca9555SetOutputRegA(uint32_t mask)+{+ uint8_t val;+ bool pass;++ pass = i2cdevReadByte(I2Cx, devAddr, PCA9555_OUTPUT_REGA, &val);+ val |= mask;+ pass = i2cdevWriteByte(I2Cx, devAddr, PCA9555_OUTPUT_REGA, val);++ return pass;+}++bool pca9555SetOutputRegB(uint32_t mask)+{+ uint8_t val;+ bool pass;++ pass = i2cdevReadByte(I2Cx, devAddr, PCA9555_OUTPUT_REGB, &val);+ val |= mask;+ pass = i2cdevWriteByte(I2Cx, devAddr, PCA9555_OUTPUT_REGB, val);++ return pass;+}++bool pca9555ClearOutputRegA(uint32_t mask)+{+ uint8_t val;+ bool pass;++ pass = i2cdevReadByte(I2Cx, devAddr, PCA9555_OUTPUT_REGA, &val);+ val &= ~mask;+ pass = i2cdevWriteByte(I2Cx, devAddr, PCA9555_OUTPUT_REGA, val);++ return pass;+}++bool pca9555ClearOutputRegB(uint32_t mask)+{+ uint8_t val;+ bool pass;++ pass = i2cdevReadByte(I2Cx, devAddr, PCA9555_OUTPUT_REGB, &val);+ val &= ~mask;+ pass = i2cdevWriteByte(I2Cx, devAddr, PCA9555_OUTPUT_REGB, val);++ return pass;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/pca95x4.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/pca95x4.cnew file mode 100644index 0000000..df3c36b--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/pca95x4.c@@ -0,0 +1,82 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2017 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * pca95x4.c - Functions for interfacing PCA95X4 I2C GPIO extender+ */+#define DEBUG_MODULE "PCA95X4"++#include "i2cdev.h"++#include "pca95x4.h"++#include "debug_cf.h"++static uint8_t devAddr;+static I2C_Dev *I2Cx;++void pca95x4Init()+{+ i2cdevInit(I2C1_DEV);+ I2Cx = I2C1_DEV;+ devAddr = PCA95X4_DEFAULT_ADDRESS;+}++bool pca95x4Test()+{+ uint8_t tb;+ bool pass;++ // Test reading the config register+ pass = i2cdevReadByte(I2Cx, devAddr, PCA95X4_CONFIG_REG, &tb);++ return pass;+}++bool pca95x4ConfigOutput(uint32_t val) {+ bool pass;++ pass = i2cdevWriteByte(I2Cx, devAddr, PCA95X4_CONFIG_REG, val);+ return pass;+}++bool pca95x4SetOutput(uint32_t mask) {+ uint8_t val;+ bool pass;++ pass = i2cdevReadByte(I2Cx, devAddr, PCA95X4_OUTPUT_REG, &val);+ val |= mask;+ pass = i2cdevWriteByte(I2Cx, devAddr, PCA95X4_OUTPUT_REG, val);++ return pass;+}++bool pca95x4ClearOutput(uint32_t mask) {+ uint8_t val;+ bool pass;++ pass = i2cdevReadByte(I2Cx, devAddr, PCA95X4_OUTPUT_REG, &val);+ val &= ~mask;+ pass = i2cdevWriteByte(I2Cx, devAddr, PCA95X4_OUTPUT_REG, val);++ return pass;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/pm_esplane.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/pm_esplane.cnew file mode 100644index 0000000..7ce40e1--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/pm_esplane.c@@ -0,0 +1,439 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * pm.c - Power Management driver and functions.+ */++#include <string.h>+#include <stdbool.h>++#include "FreeRTOS.h"+#include "task.h"++#include "config.h"+#include "system.h"+#include "pm_esplane.h"+#include "adc_esp32.h"+#include "led.h"+#include "log.h"+#include "ledseq.h"+#include "commander.h"+#include "sound.h"+#include "stm32_legacy.h"+//#include "deck.h"+#define DEBUG_MODULE "PM"+#include "debug_cf.h"+#include "static_mem.h"++typedef struct _PmSyslinkInfo+{+ union+ {+ uint8_t flags;+ struct+ {+ uint8_t chg : 1;+ uint8_t pgood : 1;+ uint8_t unused : 6;+ };+ };+ float vBat;+ float chargeCurrent;+#ifdef PM_SYSTLINK_INLCUDE_TEMP+ float temp;+#endif+} __attribute__((packed)) PmSyslinkInfo;++static float batteryVoltage;+static uint16_t batteryVoltageMV;+static float batteryVoltageMin = 6.0;+static float batteryVoltageMax = 0.0;++static float extBatteryVoltage;+static uint16_t extBatteryVoltageMV;+static uint16_t extBatVoltDeckPin;+static bool isExtBatVoltDeckPinSet = false;+static float extBatVoltMultiplier;+static float extBatteryCurrent;+static uint16_t extBatCurrDeckPin;+static bool isExtBatCurrDeckPinSet = false;+static float extBatCurrAmpPerVolt;++#ifdef PM_SYSTLINK_INLCUDE_TEMP+// nRF51 internal temp+static float temp;+#endif++static uint32_t batteryLowTimeStamp;+static uint32_t batteryCriticalLowTimeStamp;+static bool isInit;+static PMStates pmState;+static PmSyslinkInfo pmSyslinkInfo;++static uint8_t batteryLevel;++static void pmSetBatteryVoltage(float voltage);++const static float bat671723HS25C[10] =+{+ 3.00, // 00%+ 3.78, // 10%+ 3.83, // 20%+ 3.87, // 30%+ 3.89, // 40%+ 3.92, // 50%+ 3.96, // 60%+ 4.00, // 70%+ 4.04, // 80%+ 4.10 // 90%+};++STATIC_MEM_TASK_ALLOC(pmTask, PM_TASK_STACKSIZE);++void pmInit(void)+{+ if(isInit) {+ return;+ }++ pmEnableExtBatteryVoltMeasuring(CONFIG_ADC1_PIN, 2); // ADC1 PIN is fixed to ADC channel++ pmSyslinkInfo.pgood = false;+ pmSyslinkInfo.chg = false;+ pmSyslinkInfo.vBat = 3.7f;+ pmSetBatteryVoltage(pmSyslinkInfo.vBat);++ STATIC_MEM_TASK_CREATE(pmTask, pmTask, PM_TASK_NAME, NULL, PM_TASK_PRI);+ isInit = true;++}++bool pmTest(void)+{+ return isInit;+}++/**+ * Sets the battery voltage and its min and max values+ */+static void pmSetBatteryVoltage(float voltage)+{+ batteryVoltage = voltage;+ batteryVoltageMV = (uint16_t)(voltage * 1000);+ if (batteryVoltageMax < voltage)+ {+ batteryVoltageMax = voltage;+ }+ if (batteryVoltageMin > voltage)+ {+ batteryVoltageMin = voltage;+ }+}++/**+ * Shutdown system+ */+static void pmSystemShutdown(void)+{+#ifdef ACTIVATE_AUTO_SHUTDOWN+//TODO: Implement syslink call to shutdown+#endif+}++/**+ * Returns a number from 0 to 9 where 0 is completely discharged+ * and 9 is 90% charged.+ */+static int32_t pmBatteryChargeFromVoltage(float voltage)+{+ int charge = 0;++ if (voltage < bat671723HS25C[0])+ {+ return 0;+ }+ if (voltage > bat671723HS25C[9])+ {+ return 9;+ }+ while (voltage > bat671723HS25C[charge])+ {+ charge++;+ }++ return charge;+}+++float pmGetBatteryVoltage(void)+{+ return batteryVoltage;+}++float pmGetBatteryVoltageMin(void)+{+ return batteryVoltageMin;+}++float pmGetBatteryVoltageMax(void)+{+ return batteryVoltageMax;+}++void pmSyslinkUpdate(SyslinkPacket *slp)+{+ if (slp->type == SYSLINK_PM_BATTERY_STATE) {+ memcpy(&pmSyslinkInfo, &slp->data[0], sizeof(pmSyslinkInfo));+ pmSetBatteryVoltage(pmSyslinkInfo.vBat);+#ifdef PM_SYSTLINK_INLCUDE_TEMP+ temp = pmSyslinkInfo.temp;+#endif+ }+}++void pmSetChargeState(PMChargeStates chgState)+{+ // TODO: Send syslink packafe with charge state+}++PMStates pmUpdateState()+{+ PMStates state;+ bool isCharging = pmSyslinkInfo.chg;+ bool isPgood = pmSyslinkInfo.pgood;+ uint32_t batteryLowTime;++ batteryLowTime = xTaskGetTickCount() - batteryLowTimeStamp;++ if (isPgood && !isCharging)+ {+ state = charged;+ }+ else if (isPgood && isCharging)+ {+ state = charging;+ }+ else if (!isPgood && !isCharging && (batteryLowTime > PM_BAT_LOW_TIMEOUT))+ {+ state = lowPower;+ }+ else+ {+ state = battery;+ }++ return state;+}++void pmEnableExtBatteryCurrMeasuring(uint8_t pin, float ampPerVolt)+{+ extBatCurrDeckPin = pin;+ isExtBatCurrDeckPinSet = true;+ extBatCurrAmpPerVolt = ampPerVolt;+}++float pmMeasureExtBatteryCurrent(void)+{+ float current;++ if (isExtBatCurrDeckPinSet)+ {+ current = analogReadVoltage(extBatCurrDeckPin) * extBatCurrAmpPerVolt;+ }+ else+ {+ current = 0.0;+ }++ return current;+}++void pmEnableExtBatteryVoltMeasuring(uint8_t pin, float multiplier)+{+ extBatVoltDeckPin = pin;+ isExtBatVoltDeckPinSet = true;+ extBatVoltMultiplier = multiplier;+}++float pmMeasureExtBatteryVoltage(void)+{+ float voltage;++ if (isExtBatVoltDeckPinSet)+ {+ voltage = analogReadVoltage(extBatVoltDeckPin) * extBatVoltMultiplier;+ }+ else+ {+ voltage = 0.0;+ }++ return voltage;+}++bool pmIsBatteryLow(void) {+ return (pmState == lowPower);+}++bool pmIsChargerConnected(void) {+ return (pmState == charging) || (pmState == charged);+}++bool pmIsCharging(void) {+ return (pmState == charging);+}+// return true if battery discharging+bool pmIsDischarging(void)+{+ PMStates pmState;+ pmState = pmUpdateState();+ return (pmState == lowPower) || (pmState == battery);+}++void pmTask(void *param)+{+ PMStates pmStateOld = battery;+ uint32_t tickCount = 0;++#ifdef configUSE_APPLICATION_TASK_TAG+ #if configUSE_APPLICATION_TASK_TAG == 1+ vTaskSetApplicationTaskTag(0, (void *)TASK_PM_ID_NBR);+ #endif+#endif++ tickCount = xTaskGetTickCount();+ batteryLowTimeStamp = tickCount;+ batteryCriticalLowTimeStamp = tickCount;+ pmSetChargeState(charge300mA);+ systemWaitStart();++ while (1) {+ vTaskDelay(M2T(100));+ extBatteryVoltage = pmMeasureExtBatteryVoltage();+ extBatteryVoltageMV = (uint16_t)(extBatteryVoltage * 1000);+ extBatteryCurrent = pmMeasureExtBatteryCurrent();+ pmSetBatteryVoltage(extBatteryVoltage);+ batteryLevel = pmBatteryChargeFromVoltage(pmGetBatteryVoltage()) * 10;+#ifdef DEBUG_EP2+ DEBUG_PRINTD("batteryLevel=%u extBatteryVoltageMV=%u \n", batteryLevel, extBatteryVoltageMV);+#endif+ tickCount = xTaskGetTickCount();++ if (pmGetBatteryVoltage() > PM_BAT_LOW_VOLTAGE)+ {+ batteryLowTimeStamp = tickCount;+ }+ if (pmGetBatteryVoltage() > PM_BAT_CRITICAL_LOW_VOLTAGE)+ {+ batteryCriticalLowTimeStamp = tickCount;+ }++ pmState = pmUpdateState();++ if (pmState != pmStateOld)+ {+ // Actions on state change+ switch (pmState)+ {+ case charged:+ //ledseqStop(&seq_charging);+ //ledseqRunBlocking(&seq_charged);+ soundSetEffect(SND_BAT_FULL);+ systemSetCanFly(false);+ break;+ case charging:+ //ledseqStop(&seq_lowbat);+ //ledseqStop(&seq_charged);+ ledseqRunBlocking(&seq_charging);+ soundSetEffect(SND_USB_CONN);+ systemSetCanFly(false);+ break;++ case lowPower:+ ledseqRunBlocking(&seq_lowbat);+ soundSetEffect(SND_BAT_LOW);+ systemSetCanFly(true);+ break;+ case battery:+ //ledseqRunBlocking(&seq_charging);+ //ledseqRun(&seq_charged);+ soundSetEffect(SND_USB_DISC);+ systemSetCanFly(true);+ break;+ default:+ systemSetCanFly(true);+ break;+ }+ pmStateOld = pmState;+ }+ // Actions during state+ switch (pmState)+ {+ case charged:+ break;+ case charging:+ {+ // Charge level between 0.0 and 1.0+ float chargeLevel = pmBatteryChargeFromVoltage(pmGetBatteryVoltage()) / 10.0f;+ ledseqSetChargeLevel(chargeLevel);+ }+ break;+ case lowPower:+ {+ uint32_t batteryCriticalLowTime;++ batteryCriticalLowTime = tickCount - batteryCriticalLowTimeStamp;+ if (batteryCriticalLowTime > PM_BAT_CRITICAL_LOW_TIMEOUT)+ {+ pmSystemShutdown();+ }+ }+ break;+ case battery:+ {+ if ((commanderGetInactivityTime() > PM_SYSTEM_SHUTDOWN_TIMEOUT))+ {+ pmSystemShutdown();+ }+ }+ break;+ default:+ break;+ }+ }+}++LOG_GROUP_START(pm)+LOG_ADD(LOG_FLOAT, vbat, &batteryVoltage)+LOG_ADD(LOG_UINT16, vbatMV, &batteryVoltageMV)+LOG_ADD(LOG_FLOAT, extVbat, &extBatteryVoltage)+LOG_ADD(LOG_UINT16, extVbatMV, &extBatteryVoltageMV)+LOG_ADD(LOG_FLOAT, extCurr, &extBatteryCurrent)+LOG_ADD(LOG_FLOAT, chargeCurrent, &pmSyslinkInfo.chargeCurrent)+LOG_ADD(LOG_INT8, state, &pmState)+LOG_ADD(LOG_UINT8, batteryLevel, &batteryLevel)+#ifdef PM_SYSTLINK_INLCUDE_TEMP+LOG_ADD(LOG_FLOAT, temp, &temp)+#endif+LOG_GROUP_STOP(pm)diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/pm_stm32f4.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/pm_stm32f4.cnew file mode 100644index 0000000..e70dbd7--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/pm_stm32f4.c@@ -0,0 +1,423 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * pm.c - Power Management driver and functions.+ */++#include "stm32fxxx.h"+#include <string.h>+#include <stdbool.h>++#include "FreeRTOS.h"+#include "task.h"++#include "config.h"+#include "system.h"+#include "pm.h"+#include "led.h"+#include "log.h"+#include "ledseq.h"+#include "commander.h"+#include "sound.h"+#include "deck.h"+#include "static_mem.h"++typedef struct _PmSyslinkInfo+{+ union+ {+ uint8_t flags;+ struct+ {+ uint8_t chg : 1;+ uint8_t pgood : 1;+ uint8_t unused : 6;+ };+ };+ float vBat;+ float chargeCurrent;+#ifdef PM_SYSTLINK_INLCUDE_TEMP+ float temp;+#endif+} __attribute__((packed)) PmSyslinkInfo;++static float batteryVoltage;+static uint16_t batteryVoltageMV;+static float batteryVoltageMin = 6.0;+static float batteryVoltageMax = 0.0;++static float extBatteryVoltage;+static uint16_t extBatteryVoltageMV;+static deckPin_t extBatVoltDeckPin;+static bool isExtBatVoltDeckPinSet = false;+static float extBatVoltMultiplier;+static float extBatteryCurrent;+static deckPin_t extBatCurrDeckPin;+static bool isExtBatCurrDeckPinSet = false;+static float extBatCurrAmpPerVolt;++#ifdef PM_SYSTLINK_INLCUDE_TEMP+// nRF51 internal temp+static float temp;+#endif++static uint32_t batteryLowTimeStamp;+static uint32_t batteryCriticalLowTimeStamp;+static bool isInit;+static PMStates pmState;+static PmSyslinkInfo pmSyslinkInfo;++static uint8_t batteryLevel;++static void pmSetBatteryVoltage(float voltage);++const static float bat671723HS25C[10] =+{+ 3.00, // 00%+ 3.78, // 10%+ 3.83, // 20%+ 3.87, // 30%+ 3.89, // 40%+ 3.92, // 50%+ 3.96, // 60%+ 4.00, // 70%+ 4.04, // 80%+ 4.10 // 90%+};++STATIC_MEM_TASK_ALLOC(pmTask, PM_TASK_STACKSIZE);++void pmInit(void)+{+ if(isInit) {+ return;+ }++ STATIC_MEM_TASK_CREATE(pmTask, pmTask, PM_TASK_NAME, NULL, PM_TASK_PRI);++ isInit = true;++ pmSyslinkInfo.vBat = 3.7f;+ pmSetBatteryVoltage(pmSyslinkInfo.vBat); //TODO remove+}++bool pmTest(void)+{+ return isInit;+}++/**+ * Sets the battery voltage and its min and max values+ */+static void pmSetBatteryVoltage(float voltage)+{+ batteryVoltage = voltage;+ batteryVoltageMV = (uint16_t)(voltage * 1000);+ if (batteryVoltageMax < voltage)+ {+ batteryVoltageMax = voltage;+ }+ if (batteryVoltageMin > voltage)+ {+ batteryVoltageMin = voltage;+ }+}++/**+ * Shutdown system+ */+static void pmSystemShutdown(void)+{+#ifdef ACTIVATE_AUTO_SHUTDOWN+//TODO: Implement syslink call to shutdown+#endif+}++/**+ * Returns a number from 0 to 9 where 0 is completely discharged+ * and 9 is 90% charged.+ */+static int32_t pmBatteryChargeFromVoltage(float voltage)+{+ int charge = 0;++ if (voltage < bat671723HS25C[0])+ {+ return 0;+ }+ if (voltage > bat671723HS25C[9])+ {+ return 9;+ }+ while (voltage > bat671723HS25C[charge])+ {+ charge++;+ }++ return charge;+}+++float pmGetBatteryVoltage(void)+{+ return batteryVoltage;+}++float pmGetBatteryVoltageMin(void)+{+ return batteryVoltageMin;+}++float pmGetBatteryVoltageMax(void)+{+ return batteryVoltageMax;+}++void pmSyslinkUpdate(SyslinkPacket *slp)+{+ if (slp->type == SYSLINK_PM_BATTERY_STATE) {+ memcpy(&pmSyslinkInfo, &slp->data[0], sizeof(pmSyslinkInfo));+ pmSetBatteryVoltage(pmSyslinkInfo.vBat);+#ifdef PM_SYSTLINK_INLCUDE_TEMP+ temp = pmSyslinkInfo.temp;+#endif+ }+}++void pmSetChargeState(PMChargeStates chgState)+{+ // TODO: Send syslink packafe with charge state+}++PMStates pmUpdateState()+{+ PMStates state;+ bool isCharging = pmSyslinkInfo.chg;+ bool isPgood = pmSyslinkInfo.pgood;+ uint32_t batteryLowTime;++ batteryLowTime = xTaskGetTickCount() - batteryLowTimeStamp;++ if (isPgood && !isCharging)+ {+ state = charged;+ }+ else if (isPgood && isCharging)+ {+ state = charging;+ }+ else if (!isPgood && !isCharging && (batteryLowTime > PM_BAT_LOW_TIMEOUT))+ {+ state = lowPower;+ }+ else+ {+ state = battery;+ }++ return state;+}++void pmEnableExtBatteryCurrMeasuring(const deckPin_t pin, float ampPerVolt)+{+ extBatCurrDeckPin = pin;+ isExtBatCurrDeckPinSet = true;+ extBatCurrAmpPerVolt = ampPerVolt;+}++float pmMeasureExtBatteryCurrent(void)+{+ float current;++ if (isExtBatCurrDeckPinSet)+ {+ current = analogReadVoltage(extBatCurrDeckPin) * extBatCurrAmpPerVolt;+ }+ else+ {+ current = 0.0;+ }++ return current;+}++void pmEnableExtBatteryVoltMeasuring(const deckPin_t pin, float multiplier)+{+ extBatVoltDeckPin = pin;+ isExtBatVoltDeckPinSet = true;+ extBatVoltMultiplier = multiplier;+}++float pmMeasureExtBatteryVoltage(void)+{+ float voltage;++ if (isExtBatVoltDeckPinSet)+ {+ voltage = analogReadVoltage(extBatVoltDeckPin) * extBatVoltMultiplier;+ }+ else+ {+ voltage = 0.0;+ }++ return voltage;+}++bool pmIsBatteryLow(void) {+ return (pmState == lowPower);+}++bool pmIsChargerConnected(void) {+ return (pmState == charging) || (pmState == charged);+}++bool pmIsCharging(void) {+ return (pmState == charging);+}++// return true if battery discharging+bool pmIsDischarging(void) {+ return (pmState == lowPower) || (pmState == battery);+}++void pmTask(void *param)+{+ PMStates pmStateOld = battery;+ uint32_t tickCount;++ vTaskSetApplicationTaskTag(0, (void*)TASK_PM_ID_NBR);++ tickCount = xTaskGetTickCount();+ batteryLowTimeStamp = tickCount;+ batteryCriticalLowTimeStamp = tickCount;++ pmSetChargeState(charge500mA);+ systemWaitStart();++ while(1)+ {+ vTaskDelay(100);+ tickCount = xTaskGetTickCount();++ extBatteryVoltage = pmMeasureExtBatteryVoltage();+ extBatteryVoltageMV = (uint16_t)(extBatteryVoltage * 1000);+ extBatteryCurrent = pmMeasureExtBatteryCurrent();+ batteryLevel = pmBatteryChargeFromVoltage(pmGetBatteryVoltage()) * 10;++ if (pmGetBatteryVoltage() > PM_BAT_LOW_VOLTAGE)+ {+ batteryLowTimeStamp = tickCount;+ }+ if (pmGetBatteryVoltage() > PM_BAT_CRITICAL_LOW_VOLTAGE)+ {+ batteryCriticalLowTimeStamp = tickCount;+ }++ pmState = pmUpdateState();++ if (pmState != pmStateOld)+ {+ // Actions on state change+ switch (pmState)+ {+ case charged:+ ledseqStop(&seq_charging);+ ledseqRunBlocking(&seq_charged);+ soundSetEffect(SND_BAT_FULL);+ systemSetCanFly(false);+ break;+ case charging:+ ledseqStop(&seq_lowbat);+ ledseqStop(&seq_charged);+ ledseqRunBlocking(&seq_charging);+ soundSetEffect(SND_USB_CONN);+ systemSetCanFly(false);+ break;+ case lowPower:+ ledseqRunBlocking(&seq_lowbat);+ soundSetEffect(SND_BAT_LOW);+ systemSetCanFly(true);+ break;+ case battery:+ ledseqRunBlocking(&seq_charging);+ ledseqRun(&seq_charged);+ soundSetEffect(SND_USB_DISC);+ systemSetCanFly(true);+ break;+ default:+ systemSetCanFly(true);+ break;+ }+ pmStateOld = pmState;+ }+ // Actions during state+ switch (pmState)+ {+ case charged:+ break;+ case charging:+ {+ // Charge level between 0.0 and 1.0+ float chargeLevel = pmBatteryChargeFromVoltage(pmGetBatteryVoltage()) / 10.0f;+ ledseqSetChargeLevel(chargeLevel);+ }+ break;+ case lowPower:+ {+ uint32_t batteryCriticalLowTime;++ batteryCriticalLowTime = tickCount - batteryCriticalLowTimeStamp;+ if (batteryCriticalLowTime > PM_BAT_CRITICAL_LOW_TIMEOUT)+ {+ pmSystemShutdown();+ }+ }+ break;+ case battery:+ {+ if ((commanderGetInactivityTime() > PM_SYSTEM_SHUTDOWN_TIMEOUT))+ {+ pmSystemShutdown();+ }+ }+ break;+ default:+ break;+ }+ }+}++LOG_GROUP_START(pm)+LOG_ADD(LOG_FLOAT, vbat, &batteryVoltage)+LOG_ADD(LOG_UINT16, vbatMV, &batteryVoltageMV)+LOG_ADD(LOG_FLOAT, extVbat, &extBatteryVoltage)+LOG_ADD(LOG_UINT16, extVbatMV, &extBatteryVoltageMV)+LOG_ADD(LOG_FLOAT, extCurr, &extBatteryCurrent)+LOG_ADD(LOG_FLOAT, chargeCurrent, &pmSyslinkInfo.chargeCurrent)+LOG_ADD(LOG_INT8, state, &pmState)+LOG_ADD(LOG_UINT8, batteryLevel, &batteryLevel)+#ifdef PM_SYSTLINK_INLCUDE_TEMP+LOG_ADD(LOG_FLOAT, temp, &temp)+#endif+LOG_GROUP_STOP(pm)diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/proximity.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/proximity.cnew file mode 100644index 0000000..bc3e7cb--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/proximity.c@@ -0,0 +1,229 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2015 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * proximity.c - Implementation of hardware abstraction layer for proximity sensors+ */++#include <string.h>+#include "FreeRTOS.h"+#include "task.h"++#include "config.h"+#include "deck.h"+#include "proximity.h"+#include "maxsonar.h"+#include "system.h"+#include "param.h"+#include "log.h"++#include "stm32_legacy.h"+#include "static_mem.h"++/* Flag indicating if the proximityInit() function has been called or not. */+static bool isInit = false;++/* Internal values exported by functions below. */+static uint32_t proximityDistance = 0; /* The distance measured in millimeters for the latest sample. */+static uint32_t proximityDistanceAvg = 0; /* Average distance in millimeters, initialized to zero. */+static uint32_t proximityDistanceMedian = 0; /* Median distance in millimeters, initialized to zero. */+static uint32_t proximityAccuracy = 0; /* The accuracy as reported by the sensor driver for the latest sample. */++/* The most recent samples in chronological order. Must be initialized before use. */+static uint32_t proximitySWin[PROXIMITY_SWIN_SIZE];++#if defined(PROXIMITY_ENABLED)++#if defined(PROXIMITY_LOG_ENABLED)+/* Define a log group. */+LOG_GROUP_START(proximity)+LOG_ADD(LOG_UINT32, distance, &proximityDistance)+LOG_ADD(LOG_UINT32, distanceAvg, &proximityDistanceAvg)+LOG_ADD(LOG_UINT32, distanceMed, &proximityDistanceMedian)+LOG_ADD(LOG_UINT32, accuracy, &proximityAccuracy)+LOG_GROUP_STOP(proximity)+#endif++STATIC_MEM_TASK_ALLOC(proximityTask, PROXIMITY_TASK_STACKSIZE);++/**+ * This function returns the median value of an array.+ *+ * Internal sorting function by Bill Gentles Nov. 12 2010, seen+ * on http://forum.arduino.cc/index.php?topic=20920.0+ *+ * @param proximitySWin Array of chronologically sequenced samples.+ *+ * @return Median value from the array.+ */+static uint32_t proximitySWinMedian(uint32_t *proximitySWin)+{+ /* The most recent samples, sorted in increasing sample value order. Must be initialized before use. */+ uint32_t proximitySorted[PROXIMITY_SWIN_SIZE];++ /* Create a copy of the chronologically sequenced buffer. */+ memcpy(proximitySorted, proximitySWin, sizeof(uint32_t)*PROXIMITY_SWIN_SIZE);++ /* Now sort this copy. */+ uint8_t n;+ for (n = 1; n < PROXIMITY_SWIN_SIZE; ++n) {+ uint32_t valn = proximitySorted[n];+ int8_t m; /* May reach value of -1 */+ for (m = n - 1; (m >= 0) && (valn < proximitySorted[m]); m--)+ {+ proximitySorted[m + 1] = proximitySorted[m];+ }+ proximitySorted[m + 1] = valn;+ }++ /* Return the median value of the samples. */+ return proximitySorted[PROXIMITY_SWIN_SIZE / 2];+}++/**+ * This function adds a distance measurement to the sliding window, discarding the oldest sample.+ * After having added the new sample, a new average value of the samples is calculated and returned.+ *+ * @param distance The new sample to add to the sliding window.+ *+ * @return The new average value of the samples in the sliding window (after adding the new sample).+ */+static uint32_t proximitySWinAdd(uint32_t distance)+{+ /* Discard oldest sample, move remaining samples one slot to the left. */+ memmove(&proximitySWin[0], &proximitySWin[1], (PROXIMITY_SWIN_SIZE - 1) * sizeof(uint32_t));++ /* Add the new sample in the last (right-most) slot. */+ proximitySWin[PROXIMITY_SWIN_SIZE - 1] = distance;++ /**+ * Calculate the new average distance. Sum all the samples into a uint64_t,+ * so that we only do a single division at the end.+ */+ uint64_t proximityNewAvg = 0;+ uint8_t n;+ for (n = 0; n < PROXIMITY_SWIN_SIZE; n++) {+ proximityNewAvg += proximitySWin[n];+ }+ proximityNewAvg = proximityNewAvg / PROXIMITY_SWIN_SIZE;++ return (uint32_t)proximityNewAvg;+}++/**+ * Proximity task running at PROXIMITY_TASK_FREQ Hz.+ *+ * @param param Currently unused.+ */+static void proximityTask(void* param)+{+ uint32_t lastWakeTime;++#ifdef configUSE_APPLICATION_TASK_TAG+ #if configUSE_APPLICATION_TASK_TAG == 1+ vTaskSetApplicationTaskTag(0, (void*)TASK_PROXIMITY_ID_NBR);+ #endif+#endif++ //Wait for the system to be fully started to start stabilization loop+ systemWaitStart();++ lastWakeTime = xTaskGetTickCount();++ while(1)+ {+ vTaskDelayUntil(&lastWakeTime, F2T(PROXIMITY_TASK_FREQ));++#if defined(MAXSONAR_ENABLED)+ /* Read the MaxBotix sensor. */+ proximityDistance = maxSonarReadDistance(MAXSONAR_MB1040_AN, &proximityAccuracy);+#endif++ /* Get the latest average value calculated. */+ proximityDistanceAvg = proximitySWinAdd(proximityDistance);++ /* Get the latest median value calculated. */+ proximityDistanceMedian = proximitySWinMedian(proximitySWin);+ }+}+#endif++/**+ * Initialization of the proximity task.+ */+void proximityInit(void)+{+ if(isInit)+ return;++ /* Initialise the sliding window to zero. */+ memset(&proximitySWin, 0, sizeof(uint32_t)*PROXIMITY_SWIN_SIZE);++#if defined(PROXIMITY_ENABLED)+ /* Only start the task if the proximity subsystem is enabled in conf.h */+ STATIC_MEM_TASK_CREATE(proximityTask, proximityTask, PROXIMITY_TASK_NAME, NULL, PROXIMITY_TASK_PRI);+#endif++ isInit = true;+}++/**+ * Function returning the last proximity measurement.+ *+ * @return The last proximity measurement made.+ */+uint32_t proximityGetDistance(void)+{+ return proximityDistance;+}++/**+ * Function returning the result of the last, average proximity calculation.+ * The calculation is a simple average of the last PROXIMITY_SWIN_SIZE samples.+ *+ * @return The result from the last, average proximity calculation.+ */+uint32_t proximityGetDistanceAvg(void)+{+ return proximityDistanceAvg;+}++/**+ * Function returning the result of the last, median proximity calculation.+ * The calculation is the median of the last PROXIMITY_SWIN_SIZE samples.+ *+ * @return The result from the last, median proximity calculation.+ */+uint32_t proximityGetDistanceMedian(void)+{+ return proximityDistanceMedian;+}++/**+ * Function returning the accuracy of the last proximity measurement.+ *+ * @return The accuracy of the last proximity measurement made.+ */+uint32_t proximityGetAccuracy(void)+{+ return proximityAccuracy;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/radiolink.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/radiolink.cnew file mode 100644index 0000000..3b2dc3e--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/radiolink.c@@ -0,0 +1,258 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * radiolink.c - Radio link layer+ */++#include <string.h>+#include <stdint.h>++/*FreeRtos includes*/+#include "FreeRTOS.h"+#include "task.h"+#include "semphr.h"+#include "queue.h"++#include "config.h"+#include "radiolink.h"+#include "syslink.h"+#include "crtp.h"+#include "configblock.h"+#include "log.h"+#include "led.h"+#include "ledseq.h"+#include "queuemonitor.h"+#include "static_mem.h"++#define RADIOLINK_TX_QUEUE_SIZE (1)+#define RADIOLINK_CRTP_QUEUE_SIZE (5)+#define RADIO_ACTIVITY_TIMEOUT_MS (1000)++#define RADIOLINK_P2P_QUEUE_SIZE (5)++static xQueueHandle txQueue;+STATIC_MEM_QUEUE_ALLOC(txQueue, RADIOLINK_TX_QUEUE_SIZE, sizeof(SyslinkPacket));++static xQueueHandle crtpPacketDelivery;+STATIC_MEM_QUEUE_ALLOC(crtpPacketDelivery, RADIOLINK_CRTP_QUEUE_SIZE, sizeof(CRTPPacket));++static bool isInit;++static int radiolinkSendCRTPPacket(CRTPPacket *p);+static int radiolinkSetEnable(bool enable);+static int radiolinkReceiveCRTPPacket(CRTPPacket *p);++//Local RSSI variable used to enable logging of RSSI values from Radio+static uint8_t rssi;+static bool isConnected;+static uint32_t lastPacketTick;++static volatile P2PCallback p2p_callback;++static bool radiolinkIsConnected(void) {+ return (xTaskGetTickCount() - lastPacketTick) < M2T(RADIO_ACTIVITY_TIMEOUT_MS);+}++static struct crtpLinkOperations radiolinkOp =+{+ .setEnable = radiolinkSetEnable,+ .sendPacket = radiolinkSendCRTPPacket,+ .receivePacket = radiolinkReceiveCRTPPacket,+ .isConnected = radiolinkIsConnected+};++void radiolinkInit(void)+{+ if (isInit)+ return;++ txQueue = STATIC_MEM_QUEUE_CREATE(txQueue);+ DEBUG_QUEUE_MONITOR_REGISTER(txQueue);+ crtpPacketDelivery = STATIC_MEM_QUEUE_CREATE(crtpPacketDelivery);+ DEBUG_QUEUE_MONITOR_REGISTER(crtpPacketDelivery);++ ASSERT(crtpPacketDelivery);++ syslinkInit();++ radiolinkSetChannel(configblockGetRadioChannel());+ radiolinkSetDatarate(configblockGetRadioSpeed());+ radiolinkSetAddress(configblockGetRadioAddress());++ isInit = true;+}++bool radiolinkTest(void)+{+ return syslinkTest();+}++void radiolinkSetChannel(uint8_t channel)+{+ SyslinkPacket slp;++ slp.type = SYSLINK_RADIO_CHANNEL;+ slp.length = 1;+ slp.data[0] = channel;+ syslinkSendPacket(&slp);+}++void radiolinkSetDatarate(uint8_t datarate)+{+ SyslinkPacket slp;++ slp.type = SYSLINK_RADIO_DATARATE;+ slp.length = 1;+ slp.data[0] = datarate;+ syslinkSendPacket(&slp);+}++void radiolinkSetAddress(uint64_t address)+{+ SyslinkPacket slp;++ slp.type = SYSLINK_RADIO_ADDRESS;+ slp.length = 5;+ memcpy(&slp.data[0], &address, 5);+ syslinkSendPacket(&slp);+}++void radiolinkSetPowerDbm(int8_t powerDbm)+{+ SyslinkPacket slp;++ slp.type = SYSLINK_RADIO_POWER;+ slp.length = 1;+ slp.data[0] = powerDbm;+ syslinkSendPacket(&slp);+}+++void radiolinkSyslinkDispatch(SyslinkPacket *slp)+{+ static SyslinkPacket txPacket;++ if (slp->type == SYSLINK_RADIO_RAW || slp->type == SYSLINK_RADIO_RAW_BROADCAST) {+ lastPacketTick = xTaskGetTickCount();+ }++ if (slp->type == SYSLINK_RADIO_RAW)+ {+ slp->length--; // Decrease to get CRTP size.+ xQueueSend(crtpPacketDelivery, &slp->length, 0);+ ledseqRun(&seq_linkUp);+ // If a radio packet is received, one can be sent+ if (xQueueReceive(txQueue, &txPacket, 0) == pdTRUE)+ {+ ledseqRun(&seq_linkDown);+ syslinkSendPacket(&txPacket);+ }+ } else if (slp->type == SYSLINK_RADIO_RAW_BROADCAST)+ {+ slp->length--; // Decrease to get CRTP size.+ xQueueSend(crtpPacketDelivery, &slp->length, 0);+ ledseqRun(&seq_linkUp);+ // no ack for broadcasts+ } else if (slp->type == SYSLINK_RADIO_RSSI)+ {+ //Extract RSSI sample sent from radio+ memcpy(&rssi, slp->data, sizeof(uint8_t)); //rssi will not change on disconnect+ } else if (slp->type == SYSLINK_RADIO_P2P_BROADCAST)+ {+ ledseqRun(&seq_linkUp);+ P2PPacket p2pp;+ p2pp.port=slp->data[0];+ p2pp.rssi = slp->data[1];+ memcpy(&p2pp.data[0], &slp->data[2],slp->length-2);+ p2pp.size=slp->length;+ if (p2p_callback)+ p2p_callback(&p2pp);+ }++ isConnected = radiolinkIsConnected();+}++static int radiolinkReceiveCRTPPacket(CRTPPacket *p)+{+ if (xQueueReceive(crtpPacketDelivery, p, M2T(100)) == pdTRUE)+ {+ return 0;+ }++ return -1;+}++void p2pRegisterCB(P2PCallback cb)+{+ p2p_callback = cb;+}++static int radiolinkSendCRTPPacket(CRTPPacket *p)+{+ static SyslinkPacket slp;++ ASSERT(p->size <= CRTP_MAX_DATA_SIZE);++ slp.type = SYSLINK_RADIO_RAW;+ slp.length = p->size + 1;+ memcpy(slp.data, &p->header, p->size + 1);++ if (xQueueSend(txQueue, &slp, M2T(100)) == pdTRUE)+ {+ return true;+ }++ return false;+}++bool radiolinkSendP2PPacketBroadcast(P2PPacket *p)+{+ static SyslinkPacket slp;++ ASSERT(p->size <= P2P_MAX_DATA_SIZE);++ slp.type = SYSLINK_RADIO_P2P_BROADCAST;+ slp.length = p->size + 1;+ memcpy(slp.data, p->raw, p->size + 1);++ syslinkSendPacket(&slp);+ ledseqRun(&seq_linkDown);++ return true;+}+++struct crtpLinkOperations * radiolinkGetLink()+{+ return &radiolinkOp;+}++static int radiolinkSetEnable(bool enable)+{+ return 0;+}++LOG_GROUP_START(radio)+LOG_ADD(LOG_UINT8, rssi, &rssi)+LOG_ADD(LOG_UINT8, isConnected, &isConnected)+LOG_GROUP_STOP(radio)diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors.cnew file mode 100644index 0000000..42b07c4--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors.c@@ -0,0 +1,246 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2018 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * sensors.c - Abstraction layer for sensors on a platform. It acts as a+ * proxy to use the correct sensor based on device type.+ */++#define DEBUG_MODULE "SENSORS"++#include "sensors.h"+#include "platform.h"+#include "debug_cf.h"++// https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html+#define xstr(s) str(s)+#define str(s) #s++#ifdef SENSOR_INCLUDED_BMI088_BMP388+ #include "sensors_bmi088_bmp388.h"+#endif++#ifdef SENSOR_INCLUDED_BMI088_SPI_BMP388+ #include "sensors_bmi088_spi_bmp388.h"+#endif++#ifdef SENSOR_INCLUDED_MPU9250_LPS25H+ #include "sensors_mpu9250_lps25h.h"+#endif++#ifdef SENSOR_INCLUDED_BOSCH+ #include "sensors_bosch.h"+#endif++#ifdef SENSOR_INCLUDED_MPU6050_HMC5883L_MS5611+#include "sensors_mpu6050_hm5883L_ms5611.h"+#endif++typedef struct {+ SensorImplementation_t implements;+ void (*init)(void);+ bool (*test)(void);+ bool (*areCalibrated)(void);+ bool (*manufacturingTest)(void);+ void (*acquire)(sensorData_t *sensors, const uint32_t tick);+ void (*waitDataReady)(void);+ bool (*readGyro)(Axis3f *gyro);+ bool (*readAcc)(Axis3f *acc);+ bool (*readMag)(Axis3f *mag);+ bool (*readBaro)(baro_t *baro);+ void (*setAccMode)(accModes accMode);+ void (*dataAvailableCallback)(void);+} sensorsImplementation_t;++#pragma GCC diagnostic push+#pragma GCC diagnostic ignored "-Wunused-function"+static void nullFunction(void) {}+#pragma GCC diagnostic pop++static const sensorsImplementation_t sensorImplementations[SensorImplementation_COUNT] = {+#ifdef SENSOR_INCLUDED_BMI088_BMP388+ {+ .implements = SensorImplementation_bmi088_bmp388,+ .init = sensorsBmi088Bmp388Init,+ .test = sensorsBmi088Bmp388Test,+ .areCalibrated = sensorsBmi088Bmp388AreCalibrated,+ .manufacturingTest = sensorsBmi088Bmp388ManufacturingTest,+ .acquire = sensorsBmi088Bmp388Acquire,+ .waitDataReady = sensorsBmi088Bmp388WaitDataReady,+ .readGyro = sensorsBmi088Bmp388ReadGyro,+ .readAcc = sensorsBmi088Bmp388ReadAcc,+ .readMag = sensorsBmi088Bmp388ReadMag,+ .readBaro = sensorsBmi088Bmp388ReadBaro,+ .setAccMode = sensorsBmi088Bmp388SetAccMode,+ .dataAvailableCallback = sensorsBmi088Bmp388DataAvailableCallback,+ },+#endif+#ifdef SENSOR_INCLUDED_BMI088_SPI_BMP388+ {+ .implements = SensorImplementation_bmi088_spi_bmp388,+ .init = sensorsBmi088SpiBmp388Init,+ .test = sensorsBmi088SpiBmp388Test,+ .areCalibrated = sensorsBmi088SpiBmp388AreCalibrated,+ .manufacturingTest = sensorsBmi088SpiBmp388ManufacturingTest,+ .acquire = sensorsBmi088SpiBmp388Acquire,+ .waitDataReady = sensorsBmi088SpiBmp388WaitDataReady,+ .readGyro = sensorsBmi088SpiBmp388ReadGyro,+ .readAcc = sensorsBmi088SpiBmp388ReadAcc,+ .readMag = sensorsBmi088SpiBmp388ReadMag,+ .readBaro = sensorsBmi088SpiBmp388ReadBaro,+ .setAccMode = sensorsBmi088SpiBmp388SetAccMode,+ .dataAvailableCallback = sensorsBmi088SpiBmp388DataAvailableCallback,+ },+#endif+#ifdef SENSOR_INCLUDED_MPU6050_HMC5883L_MS5611+ {+ .implements = SensorImplementation_mpu6050_HMC5883L_MS5611,+ .init = sensorsMpu6050Hmc5883lMs5611Init,+ .test = sensorsMpu6050Hmc5883lMs5611Test,+ .areCalibrated = sensorsMpu6050Hmc5883lMs5611AreCalibrated,+ .manufacturingTest = sensorsMpu6050Hmc5883lMs5611ManufacturingTest,+ .acquire = sensorsMpu6050Hmc5883lMs5611Acquire,+ .waitDataReady = sensorsMpu6050Hmc5883lMs5611WaitDataReady,+ .readGyro = sensorsMpu6050Hmc5883lMs5611ReadGyro,+ .readAcc = sensorsMpu6050Hmc5883lMs5611ReadAcc,+ .readMag = sensorsMpu6050Hmc5883lMs5611ReadMag,+ .readBaro = sensorsMpu6050Hmc5883lMs5611ReadBaro,+ .setAccMode = sensorsMpu6050Hmc5883lMs5611SetAccMode,+ .dataAvailableCallback = nullFunction,+ }+#endif+#ifdef SENSOR_INCLUDED_MPU9250_LPS25H+ {+ .implements = SensorImplementation_mpu9250_lps25h,+ .init = sensorsMpu9250Lps25hInit,+ .test = sensorsMpu9250Lps25hTest,+ .areCalibrated = sensorsMpu9250Lps25hAreCalibrated,+ .manufacturingTest = sensorsMpu9250Lps25hManufacturingTest,+ .acquire = sensorsMpu9250Lps25hAcquire,+ .waitDataReady = sensorsMpu9250Lps25hWaitDataReady,+ .readGyro = sensorsMpu9250Lps25hReadGyro,+ .readAcc = sensorsMpu9250Lps25hReadAcc,+ .readMag = sensorsMpu9250Lps25hReadMag,+ .readBaro = sensorsMpu9250Lps25hReadBaro,+ .setAccMode = sensorsMpu9250Lps25hSetAccMode,+ .dataAvailableCallback = nullFunction,+ },+#endif+#ifdef SENSOR_INCLUDED_BOSCH+ {+ .implements = SensorImplementation_bosch,+ .init = sensorsBoschInit,+ .test = sensorsBoschTest,+ .areCalibrated = sensorsBoschAreCalibrated,+ .manufacturingTest = sensorsBoschManufacturingTest,+ .acquire = sensorsBoschAcquire,+ .waitDataReady = sensorsBoschWaitDataReady,+ .readGyro = sensorsBoschReadGyro,+ .readAcc = sensorsBoschReadAcc,+ .readMag = sensorsBoschReadMag,+ .readBaro = sensorsBoschReadBaro,+ .setAccMode = sensorsBoschSetAccMode,+ .dataAvailableCallback = nullFunction,+ },+#endif+};++static const sensorsImplementation_t* activeImplementation;+static bool isInit = false;+static const sensorsImplementation_t* findImplementation(SensorImplementation_t implementation);++void sensorsInit(void) {+ if (isInit) {+ return;+ }++#ifndef SENSORS_FORCE+ SensorImplementation_t sensorImplementation = platformConfigGetSensorImplementation();+#else+ SensorImplementation_t sensorImplementation = SENSORS_FORCE;+ DEBUG_PRINTD("Forcing sensors to " xstr(SENSORS_FORCE) "\n");+#endif++ activeImplementation = findImplementation(sensorImplementation);++ activeImplementation->init();++ isInit = true;+}++bool sensorsTest(void) {+ return activeImplementation->test();+}++bool sensorsAreCalibrated(void) {+ return activeImplementation->areCalibrated();+}++bool sensorsManufacturingTest(void){+ return activeImplementation->manufacturingTest;+}++void sensorsAcquire(sensorData_t *sensors, const uint32_t tick) {+ activeImplementation->acquire(sensors, tick);+}++void sensorsWaitDataReady(void) {+ activeImplementation->waitDataReady();+}++bool sensorsReadGyro(Axis3f *gyro) {+ return activeImplementation->readGyro(gyro);+}++bool sensorsReadAcc(Axis3f *acc) {+ return activeImplementation->readAcc(acc);+}++bool sensorsReadMag(Axis3f *mag) {+ return activeImplementation->readMag(mag);+}++bool sensorsReadBaro(baro_t *baro) {+ return activeImplementation->readBaro(baro);+}++void sensorsSetAccMode(accModes accMode) {+ activeImplementation->setAccMode(accMode);+}++void __attribute__((used)) EXTI14_Callback(void) {+ activeImplementation->dataAvailableCallback();+}++static const sensorsImplementation_t* findImplementation(SensorImplementation_t implementation) {+ const sensorsImplementation_t* result = 0;++ for (int i = 0; i < SensorImplementation_COUNT; i++) {+ if (sensorImplementations[i].implements == implementation) {+ result = &sensorImplementations[i];+ break;+ }+ }++ return result;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_bmi088_bmp388.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_bmi088_bmp388.cnew file mode 100644index 0000000..79b048d--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_bmi088_bmp388.c@@ -0,0 +1,924 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2018 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * sensors_bmi088_bmp388.c: IMU sensor driver for the *88 bosch sensors+ */++#define DEBUG_MODULE "IMU"++#include <math.h>++#include "sensors_bmi088_bmp388.h"+#include "stm32fxxx.h"++#include "imu.h"++#include "FreeRTOS.h"+#include "semphr.h"+#include "task.h"++#include "system.h"+#include "configblock.h"+#include "param.h"+#include "log.h"+#include "debug.h"+#include "nvicconf.h"+#include "ledseq.h"+#include "sound.h"+#include "filter.h"+#include "i2cdev.h"+#include "bmi088.h"+#include "bmp3.h"+#include "bstdr_types.h"+#include "static_mem.h"++#define GYRO_ADD_RAW_AND_VARIANCE_LOG_VALUES++#define SENSORS_READ_RATE_HZ 1000+#define SENSORS_STARTUP_TIME_MS 1000+#define SENSORS_READ_BARO_HZ 50+#define SENSORS_READ_MAG_HZ 20+#define SENSORS_DELAY_BARO (SENSORS_READ_RATE_HZ/SENSORS_READ_BARO_HZ)+#define SENSORS_DELAY_MAG (SENSORS_READ_RATE_HZ/SENSORS_READ_MAG_HZ)++#define SENSORS_BMI088_GYRO_FS_CFG BMI088_GYRO_RANGE_2000_DPS+#define SENSORS_BMI088_DEG_PER_LSB_CFG (2.0f *2000.0f) / 65536.0f++#define SENSORS_BMI088_ACCEL_CFG 24+#define SENSORS_BMI088_ACCEL_FS_CFG BMI088_ACCEL_RANGE_24G+#define SENSORS_BMI088_G_PER_LSB_CFG (2.0f * (float)SENSORS_BMI088_ACCEL_CFG) / 65536.0f+#define SENSORS_BMI088_1G_IN_LSB (65536 / SENSORS_BMI088_ACCEL_CFG / 2)++#define SENSORS_VARIANCE_MAN_TEST_TIMEOUT M2T(1000) // Timeout in ms+#define SENSORS_MAN_TEST_LEVEL_MAX 5.0f // Max degrees off++#define GYRO_NBR_OF_AXES 3+#define GYRO_MIN_BIAS_TIMEOUT_MS M2T(1*1000)++// Number of samples used in variance calculation. Changing this effects the threshold+#define SENSORS_NBR_OF_BIAS_SAMPLES 512++// Variance threshold to take zero bias for gyro+#define GYRO_VARIANCE_BASE 10000+#define GYRO_VARIANCE_THRESHOLD_X (GYRO_VARIANCE_BASE)+#define GYRO_VARIANCE_THRESHOLD_Y (GYRO_VARIANCE_BASE)+#define GYRO_VARIANCE_THRESHOLD_Z (GYRO_VARIANCE_BASE)++#define SENSORS_ACC_SCALE_SAMPLES 200++typedef struct+{+ Axis3f bias;+ Axis3f variance;+ Axis3f mean;+ bool isBiasValueFound;+ bool isBufferFilled;+ Axis3i16* bufHead;+ Axis3i16 buffer[SENSORS_NBR_OF_BIAS_SAMPLES];+} BiasObj;++/* initialize necessary variables */+static struct bmi088_dev bmi088Dev;+static struct bmp3_dev bmp388Dev;++static xQueueHandle accelerometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(accelerometerDataQueue, 1, sizeof(Axis3f));+static xQueueHandle gyroDataQueue;+STATIC_MEM_QUEUE_ALLOC(gyroDataQueue, 1, sizeof(Axis3f));+static xQueueHandle magnetometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(magnetometerDataQueue, 1, sizeof(Axis3f));+static xQueueHandle barometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(barometerDataQueue, 1, sizeof(baro_t));++static xSemaphoreHandle sensorsDataReady;+static StaticSemaphore_t sensorsDataReadyBuffer;+static xSemaphoreHandle dataReady;+static StaticSemaphore_t dataReadyBuffer;++static bool isInit = false;+static sensorData_t sensorData;+static volatile uint64_t imuIntTimestamp;++static Axis3i16 gyroRaw;+static Axis3i16 accelRaw;+NO_DMA_CCM_SAFE_ZERO_INIT static BiasObj gyroBiasRunning;+static Axis3f gyroBias;+#if defined(SENSORS_GYRO_BIAS_CALCULATE_STDDEV) && defined (GYRO_BIAS_LIGHT_WEIGHT)+static Axis3f gyroBiasStdDev;+#endif+static bool gyroBiasFound = false;+static float accScaleSum = 0;+static float accScale = 1;+static bool accScaleFound = false;+static uint32_t accScaleSumCount = 0;++// Low Pass filtering+#define GYRO_LPF_CUTOFF_FREQ 80+#define ACCEL_LPF_CUTOFF_FREQ 30+static lpf2pData accLpf[3];+static lpf2pData gyroLpf[3];+static void applyAxis3fLpf(lpf2pData *data, Axis3f* in);++static bool isBarometerPresent = false;+static uint8_t baroMeasDelayMin = SENSORS_DELAY_BARO;++// Pre-calculated values for accelerometer alignment+static float cosPitch;+static float sinPitch;+static float cosRoll;+static float sinRoll;++#ifdef GYRO_GYRO_BIAS_LIGHT_WEIGHT+static bool processGyroBiasNoBuffer(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut);+#else+static bool processGyroBias(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut);+#endif+static bool processAccScale(int16_t ax, int16_t ay, int16_t az);+static void sensorsBiasObjInit(BiasObj* bias);+static void sensorsCalculateVarianceAndMean(BiasObj* bias, Axis3f* varOut, Axis3f* meanOut);+static void sensorsCalculateBiasMean(BiasObj* bias, Axis3i32* meanOut);+static void sensorsAddBiasValue(BiasObj* bias, int16_t x, int16_t y, int16_t z);+static bool sensorsFindBiasValue(BiasObj* bias);+static void sensorsAccAlignToGravity(Axis3f* in, Axis3f* out);++STATIC_MEM_TASK_ALLOC(sensorsTask, SENSORS_TASK_STACKSIZE);++// Communication routines++/*!+ * @brief Generic burst read+ *+ * @param [out] dev_id I2C address, SPI chip select or user desired identifier+ *+ * @return Zero if successful, otherwise an error code+ */+static bstdr_ret_t bmi088_burst_read(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, uint16_t len)+{+ /**< Burst read code comes here */+ if (i2cdevReadReg8(I2C3_DEV, dev_id, reg_addr, (uint16_t) len, reg_data))+ {+ return BSTDR_OK;+ }+ else+ {+ return BSTDR_E_CON_ERROR;+ }+}++/*!+ * @brief Generic burst write+ *+ * @param [out] dev_id I2C address, SPI chip select or user desired identifier+ *+ * @return Zero if successful, otherwise an error code+ */+static bstdr_ret_t bmi088_burst_write(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, uint16_t len)+{+ /**< Burst write code comes here */+ if (i2cdevWriteReg8(I2C3_DEV, dev_id,reg_addr,(uint16_t) len, reg_data))+ {+ return BSTDR_OK;+ }+ else+ {+ return BSTDR_E_CON_ERROR;+ }+}++/*!+ * @brief Generic burst read+ *+ * @param [in] period Delay period in milliseconds+ *+ * @return None+ */+static void bmi088_ms_delay(uint32_t period)+{+ /**< Delay code comes */+ vTaskDelay(M2T(period)); // Delay a while to let the device stabilize+}++static uint16_t sensorsGyroGet(Axis3i16* dataOut)+{+ return bmi088_get_gyro_data((struct bmi088_sensor_data*)dataOut, &bmi088Dev);+}++static void sensorsAccelGet(Axis3i16* dataOut)+{+ bmi088_get_accel_data((struct bmi088_sensor_data*)dataOut, &bmi088Dev);+}++static void sensorsScaleBaro(baro_t* baroScaled, float pressure,+ float temperature)+{+ baroScaled->pressure = pressure*0.01f;+ baroScaled->temperature = temperature;+ baroScaled->asl = ((powf((1015.7f / baroScaled->pressure), 0.1902630958f)+ - 1.0f) * (25.0f + 273.15f)) / 0.0065f;+}++bool sensorsBmi088Bmp388ReadGyro(Axis3f *gyro)+{+ return (pdTRUE == xQueueReceive(gyroDataQueue, gyro, 0));+}++bool sensorsBmi088Bmp388ReadAcc(Axis3f *acc)+{+ return (pdTRUE == xQueueReceive(accelerometerDataQueue, acc, 0));+}++bool sensorsBmi088Bmp388ReadMag(Axis3f *mag)+{+ return (pdTRUE == xQueueReceive(magnetometerDataQueue, mag, 0));+}++bool sensorsBmi088Bmp388ReadBaro(baro_t *baro)+{+ return (pdTRUE == xQueueReceive(barometerDataQueue, baro, 0));+}++void sensorsBmi088Bmp388Acquire(sensorData_t *sensors, const uint32_t tick)+{+ sensorsReadGyro(&sensors->gyro);+ sensorsReadAcc(&sensors->acc);+ sensorsReadMag(&sensors->mag);+ sensorsReadBaro(&sensors->baro);+ sensors->interruptTimestamp = sensorData.interruptTimestamp;+}++bool sensorsBmi088Bmp388AreCalibrated()+{+ return gyroBiasFound;+}++static void sensorsTask(void *param)+{+ systemWaitStart();++ Axis3f accScaled;+ /* wait an additional second the keep bus free+ * this is only required by the z-ranger, since the+ * configuration will be done after system start-up */+ //vTaskDelayUntil(&lastWakeTime, M2T(1500));+ while (1)+ {+ if (pdTRUE == xSemaphoreTake(sensorsDataReady, portMAX_DELAY))+ {+ sensorData.interruptTimestamp = imuIntTimestamp;++ /* get data from chosen sensors */+ sensorsGyroGet(&gyroRaw);+ sensorsAccelGet(&accelRaw);++ /* calibrate if necessary */+#ifdef GYRO_BIAS_LIGHT_WEIGHT+ gyroBiasFound = processGyroBiasNoBuffer(gyroRaw.x, gyroRaw.y, gyroRaw.z, &gyroBias);+#else+ gyroBiasFound = processGyroBias(gyroRaw.x, gyroRaw.y, gyroRaw.z, &gyroBias);+#endif+ if (gyroBiasFound)+ {+ processAccScale(accelRaw.x, accelRaw.y, accelRaw.z);+ }+ /* Gyro */+ sensorData.gyro.x = (gyroRaw.x - gyroBias.x) * SENSORS_BMI088_DEG_PER_LSB_CFG;+ sensorData.gyro.y = (gyroRaw.y - gyroBias.y) * SENSORS_BMI088_DEG_PER_LSB_CFG;+ sensorData.gyro.z = (gyroRaw.z - gyroBias.z) * SENSORS_BMI088_DEG_PER_LSB_CFG;+ applyAxis3fLpf((lpf2pData*)(&gyroLpf), &sensorData.gyro);++ /* Acelerometer */+ accScaled.x = accelRaw.x * SENSORS_BMI088_G_PER_LSB_CFG / accScale;+ accScaled.y = accelRaw.y * SENSORS_BMI088_G_PER_LSB_CFG / accScale;+ accScaled.z = accelRaw.z * SENSORS_BMI088_G_PER_LSB_CFG / accScale;+ sensorsAccAlignToGravity(&accScaled, &sensorData.acc);+ applyAxis3fLpf((lpf2pData*)(&accLpf), &sensorData.acc);+ }++ if (isBarometerPresent)+ {+ static uint8_t baroMeasDelay = SENSORS_DELAY_BARO;+ if (--baroMeasDelay == 0)+ {+ uint8_t sensor_comp = BMP3_PRESS | BMP3_TEMP;+ struct bmp3_data data;+ baro_t* baro388 = &sensorData.baro;+ /* Temperature and Pressure data are read and stored in the bmp3_data instance */+ bmp3_get_sensor_data(sensor_comp, &data, &bmp388Dev);+ sensorsScaleBaro(baro388, data.pressure, data.temperature);+ baroMeasDelay = baroMeasDelayMin;+ }+ }+ xQueueOverwrite(accelerometerDataQueue, &sensorData.acc);+ xQueueOverwrite(gyroDataQueue, &sensorData.gyro);+ if (isBarometerPresent)+ {+ xQueueOverwrite(barometerDataQueue, &sensorData.baro);+ }++ xSemaphoreGive(dataReady);+ }+}++void sensorsBmi088Bmp388WaitDataReady(void)+{+ xSemaphoreTake(dataReady, portMAX_DELAY);+}++static void sensorsDeviceInit(void)+{+ if (isInit)+ return;++ bstdr_ret_t rslt;+ isBarometerPresent = false;++ // Wait for sensors to startup+ vTaskDelay(M2T(SENSORS_STARTUP_TIME_MS));++ /* BMI088 */+ bmi088Dev.accel_id = BMI088_ACCEL_I2C_ADDR_PRIMARY;+ bmi088Dev.gyro_id = BMI088_GYRO_I2C_ADDR_SECONDARY;+ bmi088Dev.interface = BMI088_I2C_INTF;+ bmi088Dev.read = bmi088_burst_read;+ bmi088Dev.write = bmi088_burst_write;+ bmi088Dev.delay_ms = bmi088_ms_delay;++ /* BMI088 GYRO */+ rslt = bmi088_gyro_init(&bmi088Dev); // initialize the device+ if (rslt == BSTDR_OK)+ {+ struct bmi088_int_cfg intConfig;++ DEBUG_PRINT("BMI088 Gyro I2C connection [OK].\n");+ /* set power mode of gyro */+ bmi088Dev.gyro_cfg.power = BMI088_GYRO_PM_NORMAL;+ rslt |= bmi088_set_gyro_power_mode(&bmi088Dev);+ /* set bandwidth and range of gyro */+ bmi088Dev.gyro_cfg.bw = BMI088_GYRO_BW_116_ODR_1000_HZ;+ bmi088Dev.gyro_cfg.range = SENSORS_BMI088_GYRO_FS_CFG;+ bmi088Dev.gyro_cfg.odr = BMI088_GYRO_BW_116_ODR_1000_HZ;+ rslt |= bmi088_set_gyro_meas_conf(&bmi088Dev);++ intConfig.gyro_int_channel = BMI088_INT_CHANNEL_3;+ intConfig.gyro_int_type = BMI088_GYRO_DATA_RDY_INT;+ intConfig.gyro_int_pin_3_cfg.enable_int_pin = 1;+ intConfig.gyro_int_pin_3_cfg.lvl = 1;+ intConfig.gyro_int_pin_3_cfg.output_mode = 0;+ /* Setting the interrupt configuration */+ rslt = bmi088_set_gyro_int_config(&intConfig, &bmi088Dev);++ bmi088Dev.delay_ms(50);+ struct bmi088_sensor_data gyr;+ rslt |= bmi088_get_gyro_data(&gyr, &bmi088Dev);+ }+ else+ {+#ifndef SENSORS_IGNORE_IMU_FAIL+ DEBUG_PRINT("BMI088 Gyro I2C connection [FAIL]\n");+ isInit = false;+#endif+ }++ /* BMI088 ACCEL */+ rslt |= bmi088_accel_switch_control(&bmi088Dev, BMI088_ACCEL_POWER_ENABLE);+ bmi088Dev.delay_ms(5);++ rslt = bmi088_accel_init(&bmi088Dev); // initialize the device+ if (rslt == BSTDR_OK)+ {+ DEBUG_PRINT("BMI088 Accel I2C connection [OK]\n");+ /* set power mode of accel */+ bmi088Dev.accel_cfg.power = BMI088_ACCEL_PM_ACTIVE;+ rslt |= bmi088_set_accel_power_mode(&bmi088Dev);+ bmi088Dev.delay_ms(10);++ /* set bandwidth and range of accel */+ bmi088Dev.accel_cfg.bw = BMI088_ACCEL_BW_OSR4;+ bmi088Dev.accel_cfg.range = SENSORS_BMI088_ACCEL_FS_CFG;+ bmi088Dev.accel_cfg.odr = BMI088_ACCEL_ODR_1600_HZ;+ rslt |= bmi088_set_accel_meas_conf(&bmi088Dev);++ struct bmi088_sensor_data acc;+ rslt |= bmi088_get_accel_data(&acc, &bmi088Dev);+ }+ else+ {+#ifndef SENSORS_IGNORE_IMU_FAIL+ DEBUG_PRINT("BMI088 Accel I2C connection [FAIL]\n");+ isInit = false;+#endif+ }++ /* BMP388 */+ bmp388Dev.dev_id = BMP3_I2C_ADDR_SEC;+ bmp388Dev.intf = BMP3_I2C_INTF;+ bmp388Dev.read = bmi088_burst_read;+ bmp388Dev.write = bmi088_burst_write;+ bmp388Dev.delay_ms = bmi088_ms_delay;++ int i = 3;+ do {+ bmp388Dev.delay_ms(1);+ // For some reason it often doesn't work first time+ rslt = bmp3_init(&bmp388Dev);+ } while (rslt != BMP3_OK && i-- > 0);++ if (rslt == BMP3_OK)+ {+ isBarometerPresent = true;+ DEBUG_PRINT("BMP388 I2C connection [OK]\n");+ /* Used to select the settings user needs to change */+ uint16_t settings_sel;+ /* Select the pressure and temperature sensor to be enabled */+ bmp388Dev.settings.press_en = BMP3_ENABLE;+ bmp388Dev.settings.temp_en = BMP3_ENABLE;+ /* Select the output data rate and oversampling settings for pressure and temperature */+ bmp388Dev.settings.odr_filter.press_os = BMP3_OVERSAMPLING_8X;+ bmp388Dev.settings.odr_filter.temp_os = BMP3_NO_OVERSAMPLING;+ bmp388Dev.settings.odr_filter.odr = BMP3_ODR_50_HZ;+ bmp388Dev.settings.odr_filter.iir_filter = BMP3_IIR_FILTER_COEFF_3;+ /* Assign the settings which needs to be set in the sensor */+ settings_sel = BMP3_PRESS_EN_SEL | BMP3_TEMP_EN_SEL | BMP3_PRESS_OS_SEL | BMP3_TEMP_OS_SEL | BMP3_ODR_SEL | BMP3_IIR_FILTER_SEL;+ rslt = bmp3_set_sensor_settings(settings_sel, &bmp388Dev);++ /* Set the power mode to normal mode */+ bmp388Dev.settings.op_mode = BMP3_NORMAL_MODE;+ rslt = bmp3_set_op_mode(&bmp388Dev);+++ bmp388Dev.delay_ms(20); // wait before first read out+ // read out data+ /* Variable used to select the sensor component */+ uint8_t sensor_comp;+ /* Variable used to store the compensated data */+ struct bmp3_data data;++ /* Sensor component selection */+ sensor_comp = BMP3_PRESS | BMP3_TEMP;+ /* Temperature and Pressure data are read and stored in the bmp3_data instance */+ rslt = bmp3_get_sensor_data(sensor_comp, &data, &bmp388Dev);++ /* Print the temperature and pressure data */+// DEBUG_PRINT("BMP388 T:%0.2f P:%0.2f\n",data.temperature, data.pressure/100.0f);+ baroMeasDelayMin = SENSORS_DELAY_BARO;+ }+ else+ {+#ifndef SENSORS_IGNORE_BAROMETER_FAIL+ DEBUG_PRINT("BMP388 I2C connection [FAIL]\n");+ isInit = false;+ return;+#endif+ }++ // Init second order filer for accelerometer and gyro+ for (uint8_t i = 0; i < 3; i++)+ {+ lpf2pInit(&gyroLpf[i], 1000, GYRO_LPF_CUTOFF_FREQ);+ lpf2pInit(&accLpf[i], 1000, ACCEL_LPF_CUTOFF_FREQ);+ }++ cosPitch = cosf(configblockGetCalibPitch() * (float) M_PI / 180);+ sinPitch = sinf(configblockGetCalibPitch() * (float) M_PI / 180);+ cosRoll = cosf(configblockGetCalibRoll() * (float) M_PI / 180);+ sinRoll = sinf(configblockGetCalibRoll() * (float) M_PI / 180);++ isInit = true;+}++static void sensorsTaskInit(void)+{+ accelerometerDataQueue = STATIC_MEM_QUEUE_CREATE(accelerometerDataQueue);+ gyroDataQueue = STATIC_MEM_QUEUE_CREATE(gyroDataQueue);+ magnetometerDataQueue = STATIC_MEM_QUEUE_CREATE(magnetometerDataQueue);+ barometerDataQueue = STATIC_MEM_QUEUE_CREATE(barometerDataQueue);++ STATIC_MEM_TASK_CREATE(sensorsTask, sensorsTask, SENSORS_TASK_NAME, NULL, SENSORS_TASK_PRI);+}++static void sensorsInterruptInit(void)+{+ GPIO_InitTypeDef GPIO_InitStructure;+ EXTI_InitTypeDef EXTI_InitStructure;++ sensorsDataReady = xSemaphoreCreateBinaryStatic(&sensorsDataReadyBuffer);+ dataReady = xSemaphoreCreateBinaryStatic(&dataReadyBuffer);++ // Enable the interrupt on PC14+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;+ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; //GPIO_PuPd_DOWN;+ GPIO_Init(GPIOC, &GPIO_InitStructure);++ SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC, EXTI_PinSource14);++ EXTI_InitStructure.EXTI_Line = EXTI_Line14;+ EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;+ EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;+ EXTI_InitStructure.EXTI_LineCmd = ENABLE;+ portDISABLE_INTERRUPTS();+ EXTI_Init(&EXTI_InitStructure);+ EXTI_ClearITPendingBit(EXTI_Line14);+ portENABLE_INTERRUPTS();+}++void sensorsBmi088Bmp388Init(void)+{+ if (isInit)+ {+ return;+ }++ i2cdevInit(I2C3_DEV);++ sensorsBiasObjInit(&gyroBiasRunning);+ sensorsDeviceInit();+ sensorsInterruptInit();+ sensorsTaskInit();+}++static bool gyroSelftest()+{+ bool testStatus = true;++ int i = 3;+ uint16_t readResult = BMI088_OK;+ do {+ // For some reason it often doesn't work first time on the Roadrunner+ readResult = sensorsGyroGet(&gyroRaw);+ } while (readResult != BMI088_OK && i-- > 0);++ if ((readResult != BMI088_OK) || (gyroRaw.x == 0 && gyroRaw.y == 0 && gyroRaw.z == 0))+ {+ DEBUG_PRINT("BMI088 gyro returning x=0 y=0 z=0 [FAILED]\n");+ testStatus = false;+ }++ int8_t gyroResult = 0;+ bmi088_perform_gyro_selftest(&gyroResult, &bmi088Dev);+ if (gyroResult == BMI088_SELFTEST_PASS)+ {+ DEBUG_PRINT("BMI088 gyro self-test [OK]\n");+ }+ else+ {+ DEBUG_PRINT("BMI088 gyro self-test [FAILED]\n");+ testStatus = false;+ }++ return testStatus;+}++bool sensorsBmi088Bmp388Test(void)+{+ bool testStatus = true;++ if (!isInit)+ {+ DEBUG_PRINT("Uninitialized\n");+ testStatus = false;+ }++ if (! gyroSelftest())+ {+ testStatus = false;+ }++ return testStatus;+}++/**+ * Calculates accelerometer scale out of SENSORS_ACC_SCALE_SAMPLES samples. Should be called when+ * platform is stable.+ */+static bool processAccScale(int16_t ax, int16_t ay, int16_t az)+{+ if (!accScaleFound)+ {+ accScaleSum += sqrtf(powf(ax * SENSORS_BMI088_G_PER_LSB_CFG, 2) + powf(ay * SENSORS_BMI088_G_PER_LSB_CFG, 2) + powf(az * SENSORS_BMI088_G_PER_LSB_CFG, 2));+ accScaleSumCount++;++ if (accScaleSumCount == SENSORS_ACC_SCALE_SAMPLES)+ {+ accScale = accScaleSum / SENSORS_ACC_SCALE_SAMPLES;+ accScaleFound = true;+ }+ }++ return accScaleFound;+}++#ifdef GYRO_BIAS_LIGHT_WEIGHT++#define SENSORS_BIAS_SAMPLES 1000+/**+ * Calculates the bias out of the first SENSORS_BIAS_SAMPLES gathered. Requires no buffer+ * but needs platform to be stable during startup.+ */+static bool processGyroBiasNoBuffer(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut)+{+ static uint32_t gyroBiasSampleCount = 0;+ static bool gyroBiasNoBuffFound = false;+ static Axis3i64 gyroBiasSampleSum;+ static Axis3i64 gyroBiasSampleSumSquares;++ if (!gyroBiasNoBuffFound)+ {+ // If the gyro has not yet been calibrated:+ // Add the current sample to the running mean and variance+ gyroBiasSampleSum.x += gx;+ gyroBiasSampleSum.y += gy;+ gyroBiasSampleSum.z += gz;+#ifdef SENSORS_GYRO_BIAS_CALCULATE_STDDEV+ gyroBiasSampleSumSquares.x += gx * gx;+ gyroBiasSampleSumSquares.y += gy * gy;+ gyroBiasSampleSumSquares.z += gz * gz;+#endif+ gyroBiasSampleCount += 1;++ // If we then have enough samples, calculate the mean and standard deviation+ if (gyroBiasSampleCount == SENSORS_BIAS_SAMPLES)+ {+ gyroBiasOut->x = (float)(gyroBiasSampleSum.x) / SENSORS_BIAS_SAMPLES;+ gyroBiasOut->y = (float)(gyroBiasSampleSum.y) / SENSORS_BIAS_SAMPLES;+ gyroBiasOut->z = (float)(gyroBiasSampleSum.z) / SENSORS_BIAS_SAMPLES;++#ifdef SENSORS_GYRO_BIAS_CALCULATE_STDDEV+ gyroBiasStdDev.x = sqrtf((float)(gyroBiasSampleSumSquares.x) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->x * gyroBiasOut->x));+ gyroBiasStdDev.y = sqrtf((float)(gyroBiasSampleSumSquares.y) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->y * gyroBiasOut->y));+ gyroBiasStdDev.z = sqrtf((float)(gyroBiasSampleSumSquares.z) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->z * gyroBiasOut->z));+#endif+ gyroBiasNoBuffFound = true;+ }+ }++ return gyroBiasNoBuffFound;+}+#else+/**+ * Calculates the bias first when the gyro variance is below threshold. Requires a buffer+ * but calibrates platform first when it is stable.+ */+static bool processGyroBias(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut)+{+ sensorsAddBiasValue(&gyroBiasRunning, gx, gy, gz);++ if (!gyroBiasRunning.isBiasValueFound)+ {+ sensorsFindBiasValue(&gyroBiasRunning);+ if (gyroBiasRunning.isBiasValueFound)+ {+ soundSetEffect(SND_CALIB);+ ledseqRun(&seq_calibrated);+ }+ }++ gyroBiasOut->x = gyroBiasRunning.bias.x;+ gyroBiasOut->y = gyroBiasRunning.bias.y;+ gyroBiasOut->z = gyroBiasRunning.bias.z;++ return gyroBiasRunning.isBiasValueFound;+}+#endif++static void sensorsBiasObjInit(BiasObj* bias)+{+ bias->isBufferFilled = false;+ bias->bufHead = bias->buffer;+}++/**+ * Calculates the variance and mean for the bias buffer.+ */+static void sensorsCalculateVarianceAndMean(BiasObj* bias, Axis3f* varOut, Axis3f* meanOut)+{+ uint32_t i;+ int64_t sum[GYRO_NBR_OF_AXES] = {0};+ int64_t sumSq[GYRO_NBR_OF_AXES] = {0};++ for (i = 0; i < SENSORS_NBR_OF_BIAS_SAMPLES; i++)+ {+ sum[0] += bias->buffer[i].x;+ sum[1] += bias->buffer[i].y;+ sum[2] += bias->buffer[i].z;+ sumSq[0] += bias->buffer[i].x * bias->buffer[i].x;+ sumSq[1] += bias->buffer[i].y * bias->buffer[i].y;+ sumSq[2] += bias->buffer[i].z * bias->buffer[i].z;+ }++ varOut->x = (sumSq[0] - ((int64_t)sum[0] * sum[0]) / SENSORS_NBR_OF_BIAS_SAMPLES);+ varOut->y = (sumSq[1] - ((int64_t)sum[1] * sum[1]) / SENSORS_NBR_OF_BIAS_SAMPLES);+ varOut->z = (sumSq[2] - ((int64_t)sum[2] * sum[2]) / SENSORS_NBR_OF_BIAS_SAMPLES);++ meanOut->x = (float)sum[0] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->y = (float)sum[1] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->z = (float)sum[2] / SENSORS_NBR_OF_BIAS_SAMPLES;+}++/**+ * Calculates the mean for the bias buffer.+ */+static void __attribute__((used)) sensorsCalculateBiasMean(BiasObj* bias, Axis3i32* meanOut)+{+ uint32_t i;+ int32_t sum[GYRO_NBR_OF_AXES] = {0};++ for (i = 0; i < SENSORS_NBR_OF_BIAS_SAMPLES; i++)+ {+ sum[0] += bias->buffer[i].x;+ sum[1] += bias->buffer[i].y;+ sum[2] += bias->buffer[i].z;+ }++ meanOut->x = sum[0] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->y = sum[1] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->z = sum[2] / SENSORS_NBR_OF_BIAS_SAMPLES;+}++/**+ * Adds a new value to the variance buffer and if it is full+ * replaces the oldest one. Thus a circular buffer.+ */+static void sensorsAddBiasValue(BiasObj* bias, int16_t x, int16_t y, int16_t z)+{+ bias->bufHead->x = x;+ bias->bufHead->y = y;+ bias->bufHead->z = z;+ bias->bufHead++;++ if (bias->bufHead >= &bias->buffer[SENSORS_NBR_OF_BIAS_SAMPLES])+ {+ bias->bufHead = bias->buffer;+ bias->isBufferFilled = true;+ }+}++/**+ * Checks if the variances is below the predefined thresholds.+ * The bias value should have been added before calling this.+ * @param bias The bias object+ */+static bool sensorsFindBiasValue(BiasObj* bias)+{+ static int32_t varianceSampleTime;+ bool foundBias = false;++ if (bias->isBufferFilled)+ {+ sensorsCalculateVarianceAndMean(bias, &bias->variance, &bias->mean);++ if (bias->variance.x < GYRO_VARIANCE_THRESHOLD_X &&+ bias->variance.y < GYRO_VARIANCE_THRESHOLD_Y &&+ bias->variance.z < GYRO_VARIANCE_THRESHOLD_Z &&+ (varianceSampleTime + GYRO_MIN_BIAS_TIMEOUT_MS < xTaskGetTickCount()))+ {+ varianceSampleTime = xTaskGetTickCount();+ bias->bias.x = bias->mean.x;+ bias->bias.y = bias->mean.y;+ bias->bias.z = bias->mean.z;+ foundBias = true;+ bias->isBiasValueFound = true;+ }+ }++ return foundBias;+}++bool sensorsBmi088Bmp388ManufacturingTest(void)+{+ bool testStatus = true;+ if (! gyroSelftest())+ {+ testStatus = false;+ }++ int8_t accResult = 0;+ bmi088_perform_accel_selftest(&accResult, &bmi088Dev);+ if (accResult == BMI088_SELFTEST_PASS)+ {+ DEBUG_PRINT("BMI088 acc self-test [OK]\n");+ }+ else+ {+ DEBUG_PRINT("BMI088 acc self-test [FAILED]\n");+ testStatus = false;+ }++ return testStatus;+}++/**+ * Compensate for a miss-aligned accelerometer. It uses the trim+ * data gathered from the UI and written in the config-block to+ * rotate the accelerometer to be aligned with gravity.+ */+static void sensorsAccAlignToGravity(Axis3f* in, Axis3f* out)+{+ Axis3f rx;+ Axis3f ry;++ // Rotate around x-axis+ rx.x = in->x;+ rx.y = in->y * cosRoll - in->z * sinRoll;+ rx.z = in->y * sinRoll + in->z * cosRoll;++ // Rotate around y-axis+ ry.x = rx.x * cosPitch - rx.z * sinPitch;+ ry.y = rx.y;+ ry.z = -rx.x * sinPitch + rx.z * cosPitch;++ out->x = ry.x;+ out->y = ry.y;+ out->z = ry.z;+}++void sensorsBmi088Bmp388SetAccMode(accModes accMode)+{+ switch (accMode)+ {+ case ACC_MODE_PROPTEST:+// bmi088_accel_soft_reset(&bmi088Dev);+ /* set bandwidth and range of accel (280Hz cut-off according to datasheet) */+ bmi088Dev.accel_cfg.bw = BMI088_ACCEL_BW_NORMAL;+ bmi088Dev.accel_cfg.range = SENSORS_BMI088_ACCEL_FS_CFG;+ bmi088Dev.accel_cfg.odr = BMI088_ACCEL_ODR_1600_HZ;+ if (bmi088_set_accel_meas_conf(&bmi088Dev) != BMI088_OK)+ {+ DEBUG_PRINT("ACC config [FAIL]\n");+ }+ for (uint8_t i = 0; i < 3; i++)+ {+ lpf2pInit(&accLpf[i], 1000, 500);+ }+ break;+ case ACC_MODE_FLIGHT:+ default:+ /* set bandwidth and range of accel (145Hz cut-off according to datasheet) */+ bmi088Dev.accel_cfg.bw = BMI088_ACCEL_BW_OSR4;+ bmi088Dev.accel_cfg.range = SENSORS_BMI088_ACCEL_FS_CFG;+ bmi088Dev.accel_cfg.odr = BMI088_ACCEL_ODR_1600_HZ;+ if (bmi088_set_accel_meas_conf(&bmi088Dev) != BMI088_OK)+ {+ DEBUG_PRINT("ACC config [FAIL]\n");+ }+ for (uint8_t i = 0; i < 3; i++)+ {+ lpf2pInit(&accLpf[i], 1000, ACCEL_LPF_CUTOFF_FREQ);+ }+ break;+ }+}++static void applyAxis3fLpf(lpf2pData *data, Axis3f* in)+{+ for (uint8_t i = 0; i < 3; i++) {+ in->axis[i] = lpf2pApply(&data[i], in->axis[i]);+ }+}++void sensorsBmi088Bmp388DataAvailableCallback(void)+{+ portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;+ imuIntTimestamp = usecTimestamp();+ xSemaphoreGiveFromISR(sensorsDataReady, &xHigherPriorityTaskWoken);++ if (xHigherPriorityTaskWoken)+ {+ portYIELD();+ }+}++#ifdef GYRO_ADD_RAW_AND_VARIANCE_LOG_VALUES+LOG_GROUP_START(gyro)+LOG_ADD(LOG_INT16, xRaw, &gyroRaw.x)+LOG_ADD(LOG_INT16, yRaw, &gyroRaw.y)+LOG_ADD(LOG_INT16, zRaw, &gyroRaw.z)+LOG_ADD(LOG_FLOAT, xVariance, &gyroBiasRunning.variance.x)+LOG_ADD(LOG_FLOAT, yVariance, &gyroBiasRunning.variance.y)+LOG_ADD(LOG_FLOAT, zVariance, &gyroBiasRunning.variance.z)+LOG_GROUP_STOP(gyro)+#endif++PARAM_GROUP_START(imu_sensors)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, BMP388, &isBarometerPresent)+PARAM_GROUP_STOP(imu_sensors)diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_bmi088_spi_bmp388.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_bmi088_spi_bmp388.cnew file mode 100644index 0000000..7fb2ff9--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_bmi088_spi_bmp388.c@@ -0,0 +1,1259 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * sensors_bmi088_bmp388.c: IMU sensor accusation for the *88 bosch sensors+ */++#define DEBUG_MODULE "IMU"++#include <math.h>+#include <string.h>++#include "stm32fxxx.h"++#include "sensors_bmi088_spi_bmp388.h"+#include "imu.h"++#include "FreeRTOS.h"+#include "semphr.h"+#include "task.h"++#include "system.h"+#include "configblock.h"+#include "param.h"+#include "log.h"+#include "debug.h"+#include "imu.h"+#include "nvicconf.h"+#include "ledseq.h"+#include "sound.h"+#include "filter.h"+#include "i2cdev.h"+#include "bmi088.h"+#include "bmp3.h"+#include "bstdr_types.h"+#include "static_mem.h"++/* Defines for the SPI and GPIO pins used to drive the SPI Flash */+#define BMI088_ACC_GPIO_CS GPIO_Pin_1+#define BMI088_ACC_GPIO_CS_PORT GPIOB+#define BMI088_ACC_GPIO_CS_PERIF RCC_AHB1Periph_GPIOB+#define BMI088_GYR_GPIO_CS GPIO_Pin_0+#define BMI088_GYR_GPIO_CS_PORT GPIOB+#define BMI088_GYR_GPIO_CS_PERIF RCC_AHB1Periph_GPIOB++#define BMI088_SPI SPI2+#define BMI088_SPI_AF GPIO_AF_SPI2+#define BMI088_SPI_CLK RCC_APB1Periph_SPI2+#define BMI088_GPIO_SPI_PORT GPIOB+#define BMI088_GPIO_SPI_CLK RCC_AHB1Periph_GPIOB+#define BMI088_GPIO_SPI_SCK GPIO_Pin_13+#define BMI088_GPIO_SPI_SCK_SRC GPIO_PinSource13+#define BMI088_GPIO_SPI_MISO GPIO_Pin_14+#define BMI088_GPIO_SPI_MISO_SRC GPIO_PinSource14+#define BMI088_GPIO_SPI_MOSI GPIO_Pin_15+#define BMI088_GPIO_SPI_MOSI_SRC GPIO_PinSource15++#define BMI088_SPI_DMA_IRQ_PRIO NVIC_HIGH_PRI+#define BMI088_SPI_DMA DMA1+#define BMI088_SPI_DMA_CLK RCC_AHB1Periph_DMA1+#define BMI088_SPI_DMA_CLK_INIT RCC_AHB1PeriphClockCmd++#define BMI088_SPI_RX_DMA_STREAM DMA1_Stream3+#define BMI088_SPI_RX_DMA_IRQ DMA1_Stream3_IRQn+#define BMI088_SPI_RX_DMA_IRQHandler DMA1_Stream3_IRQHandler+#define BMI088_SPI_RX_DMA_CHANNEL DMA_Channel_0+#define BMI088_SPI_RX_DMA_FLAG_TCIF DMA_FLAG_TCIF3++#define BMI088_SPI_TX_DMA_STREAM DMA1_Stream4+#define BMI088_SPI_TX_DMA_IRQ DMA1_Stream4_IRQn+#define BMI088_SPI_TX_DMA_IRQHandler DMA1_Stream4_IRQHandler+#define BMI088_SPI_TX_DMA_CHANNEL DMA_Channel_0+#define BMI088_SPI_TX_DMA_FLAG_TCIF DMA_FLAG_TCIF4++#define DUMMY_BYTE 0x00++#define SENSORS_READ_RATE_HZ 1000+#define SENSORS_STARTUP_TIME_MS 1000+#define SENSORS_READ_BARO_HZ 50+#define SENSORS_READ_MAG_HZ 20+#define SENSORS_DELAY_BARO (SENSORS_READ_RATE_HZ/SENSORS_READ_BARO_HZ)+#define SENSORS_DELAY_MAG (SENSORS_READ_RATE_HZ/SENSORS_READ_MAG_HZ)++#define SENSORS_BMI088_GYRO_FS_CFG BMI088_GYRO_RANGE_2000_DPS+#define SENSORS_BMI088_DEG_PER_LSB_CFG (2.0f *2000.0f) / 65536.0f++#define SENSORS_BMI088_ACCEL_CFG 24+#define SENSORS_BMI088_ACCEL_FS_CFG BMI088_ACCEL_RANGE_24G+#define SENSORS_BMI088_G_PER_LSB_CFG (2.0f * (float)SENSORS_BMI088_ACCEL_CFG) / 65536.0f+#define SENSORS_BMI088_1G_IN_LSB (65536 / SENSORS_BMI088_ACCEL_CFG / 2)++#define SENSORS_VARIANCE_MAN_TEST_TIMEOUT M2T(1000) // Timeout in ms+#define SENSORS_MAN_TEST_LEVEL_MAX 5.0f // Max degrees off++#define GYRO_NBR_OF_AXES 3+#define GYRO_MIN_BIAS_TIMEOUT_MS M2T(1*1000)++// Number of samples used in variance calculation. Changing this effects the threshold+#define SENSORS_NBR_OF_BIAS_SAMPLES 512++// Variance threshold to take zero bias for gyro+#define GYRO_VARIANCE_BASE 10000+#define GYRO_VARIANCE_THRESHOLD_X (GYRO_VARIANCE_BASE)+#define GYRO_VARIANCE_THRESHOLD_Y (GYRO_VARIANCE_BASE)+#define GYRO_VARIANCE_THRESHOLD_Z (GYRO_VARIANCE_BASE)++#define SENSORS_ACC_SCALE_SAMPLES 200++/* Usefull macro */+#define ACC_EN_CS() GPIO_ResetBits(BMI088_ACC_GPIO_CS_PORT, BMI088_ACC_GPIO_CS)+#define ACC_DIS_CS() GPIO_SetBits(BMI088_ACC_GPIO_CS_PORT, BMI088_ACC_GPIO_CS)+#define GYR_EN_CS() GPIO_ResetBits(BMI088_GYR_GPIO_CS_PORT, BMI088_GYR_GPIO_CS)+#define GYR_DIS_CS() GPIO_SetBits(BMI088_GYR_GPIO_CS_PORT, BMI088_GYR_GPIO_CS)++/* Defines and buffers for full duplex SPI DMA transactions */+/* The buffers must not be placed in CCM */+#define SPI_MAX_DMA_TRANSACTION_SIZE 15+static uint8_t spiTxBuffer[SPI_MAX_DMA_TRANSACTION_SIZE + 1];+static uint8_t spiRxBuffer[SPI_MAX_DMA_TRANSACTION_SIZE + 1];+static xSemaphoreHandle spiTxDMAComplete;+static StaticSemaphore_t spiTxDMACompleteBuffer;+static xSemaphoreHandle spiRxDMAComplete;+static StaticSemaphore_t spiRxDMACompleteBuffer;++typedef struct+{+ Axis3f bias;+ Axis3f variance;+ Axis3f mean;+ bool isBiasValueFound;+ bool isBufferFilled;+ Axis3i16* bufHead;+ Axis3i16 buffer[SENSORS_NBR_OF_BIAS_SAMPLES];+} BiasObj;++/* initialize necessary variables */+static struct bmi088_dev bmi088Dev;+static struct bmp3_dev bmp388Dev;++static xQueueHandle accelerometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(accelerometerDataQueue, 1, sizeof(Axis3f));+static xQueueHandle gyroDataQueue;+STATIC_MEM_QUEUE_ALLOC(gyroDataQueue, 1, sizeof(Axis3f));+static xQueueHandle magnetometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(magnetometerDataQueue, 1, sizeof(Axis3f));+static xQueueHandle barometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(barometerDataQueue, 1, sizeof(baro_t));++static xSemaphoreHandle sensorsDataReady;+static StaticSemaphore_t sensorsDataReadyBuffer;+static xSemaphoreHandle dataReady;+static StaticSemaphore_t dataReadyBuffer;++static bool isInit = false;+static sensorData_t sensorData;+static volatile uint64_t imuIntTimestamp;++static Axis3i16 gyroRaw;+static Axis3i16 accelRaw;+NO_DMA_CCM_SAFE_ZERO_INIT static BiasObj gyroBiasRunning;+static Axis3f gyroBias;+#if defined(SENSORS_GYRO_BIAS_CALCULATE_STDDEV) && defined (GYRO_BIAS_LIGHT_WEIGHT)+static Axis3f gyroBiasStdDev;+#endif+static bool gyroBiasFound = false;+static float accScaleSum = 0;+static float accScale = 1;+static bool accScaleFound = false;+static uint32_t accScaleSumCount = 0;+++// Low Pass filtering+#define GYRO_LPF_CUTOFF_FREQ 80+#define ACCEL_LPF_CUTOFF_FREQ 30+static lpf2pData accLpf[3];+static lpf2pData gyroLpf[3];+static void applyAxis3fLpf(lpf2pData *data, Axis3f* in);++static bool isBarometerPresent = false;+static uint8_t baroMeasDelayMin = SENSORS_DELAY_BARO;++// Pre-calculated values for accelerometer alignment+static float cosPitch;+static float sinPitch;+static float cosRoll;+static float sinRoll;++#ifdef GYRO_GYRO_BIAS_LIGHT_WEIGHT+static bool processGyroBiasNoBuffer(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut);+#else+static bool processGyroBias(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut);+#endif+static bool processAccScale(int16_t ax, int16_t ay, int16_t az);+static void sensorsBiasObjInit(BiasObj* bias);+static void sensorsCalculateVarianceAndMean(BiasObj* bias, Axis3f* varOut, Axis3f* meanOut);+static void sensorsCalculateBiasMean(BiasObj* bias, Axis3i32* meanOut);+static void sensorsAddBiasValue(BiasObj* bias, int16_t x, int16_t y, int16_t z);+static bool sensorsFindBiasValue(BiasObj* bias);+static void sensorsAccAlignToGravity(Axis3f* in, Axis3f* out);++STATIC_MEM_TASK_ALLOC(sensorsTask, SENSORS_TASK_STACKSIZE);++/***********************+ * SPI private methods *+ ***********************/+static char spiSendByte(char byte)+{+ /* Loop while DR register in not emplty */+ while (SPI_I2S_GetFlagStatus(BMI088_SPI, SPI_I2S_FLAG_TXE) == RESET);++ /* Send byte through the SPI peripheral */+ SPI_I2S_SendData(BMI088_SPI, byte);++ /* Wait to receive a byte */+ while (SPI_I2S_GetFlagStatus(BMI088_SPI, SPI_I2S_FLAG_RXNE) == RESET);++ /* Return the byte read from the SPI bus */+ return SPI_I2S_ReceiveData(BMI088_SPI);+}++static char spiReceiveByte()+{+ return spiSendByte(DUMMY_BYTE);+}++static void spiDMATransaction(uint8_t reg_addr, uint8_t *reg_data, uint16_t len)+{+ ASSERT(len < SPI_MAX_DMA_TRANSACTION_SIZE);++ // Disable peripheral before setting up for duplex DMA+ SPI_Cmd(BMI088_SPI, DISABLE);++ // DMA already configured, just need to set memory addresses and read command byte+ spiTxBuffer[0] = reg_addr;+ BMI088_SPI_TX_DMA_STREAM->M0AR = (uint32_t)&spiTxBuffer[0];+ BMI088_SPI_TX_DMA_STREAM->NDTR = len + 1;++ BMI088_SPI_RX_DMA_STREAM->M0AR = (uint32_t)&spiRxBuffer[0];+ BMI088_SPI_RX_DMA_STREAM->NDTR = len + 1;++ // Enable SPI DMA Interrupts+ DMA_ITConfig(BMI088_SPI_TX_DMA_STREAM, DMA_IT_TC, ENABLE);+ DMA_ITConfig(BMI088_SPI_RX_DMA_STREAM, DMA_IT_TC, ENABLE);++ // Clear DMA Flags+ DMA_ClearFlag(BMI088_SPI_TX_DMA_STREAM, DMA_FLAG_FEIF4|DMA_FLAG_DMEIF4|+ DMA_FLAG_TEIF4|DMA_FLAG_HTIF4|DMA_FLAG_TCIF4);+ DMA_ClearFlag(BMI088_SPI_RX_DMA_STREAM, DMA_FLAG_FEIF3|DMA_FLAG_DMEIF3|+ DMA_FLAG_TEIF3|DMA_FLAG_HTIF3|DMA_FLAG_TCIF3);++ // Enable DMA Streams+ DMA_Cmd(BMI088_SPI_TX_DMA_STREAM,ENABLE);+ DMA_Cmd(BMI088_SPI_RX_DMA_STREAM,ENABLE);++ // Enable SPI DMA requests+ SPI_I2S_DMACmd(BMI088_SPI, SPI_I2S_DMAReq_Tx, ENABLE);+ SPI_I2S_DMACmd(BMI088_SPI, SPI_I2S_DMAReq_Rx, ENABLE);++ // Enable peripheral to begin the transaction+ SPI_Cmd(BMI088_SPI, ENABLE);++ // Wait for completion+ // TODO: Better error handling rather than passing up invalid data+ xSemaphoreTake(spiTxDMAComplete, portMAX_DELAY);+ xSemaphoreTake(spiRxDMAComplete, portMAX_DELAY);++ // Copy the data (discarding the dummy byte) into the buffer+ // TODO: Avoid this memcpy either by figuring out how to configure the STM SPI to discard the byte or handle it higher up+ memcpy(reg_data, &spiRxBuffer[1], len);+}++// Communication routines++static bstdr_ret_t spi_burst_read(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, uint16_t len)+{+ /**< Burst read code comes here */+ if (dev_id == BMI088_ACCEL_I2C_ADDR_PRIMARY)+ {+ ACC_EN_CS();+ }+ else+ {+ GYR_EN_CS();+ }++ if (len <= 1 || len > SPI_MAX_DMA_TRANSACTION_SIZE)+ {+ spiSendByte(reg_addr);+ for (int i = 0; i < len; i++)+ {+ reg_data[i] = spiReceiveByte();+ }+ }+ else+ {+ spiDMATransaction(reg_addr, reg_data, len);+ }++ if (dev_id == BMI088_ACCEL_I2C_ADDR_PRIMARY)+ {+ ACC_DIS_CS();+ }+ else+ {+ GYR_DIS_CS();+ }++ return BSTDR_OK;+}++static bstdr_ret_t spi_burst_write(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, uint16_t len)+{+ if (dev_id == BMI088_ACCEL_I2C_ADDR_PRIMARY)+ {+ ACC_EN_CS();+ }+ else+ {+ GYR_EN_CS();+ }+ spiSendByte(reg_addr);+ for (int i = 0; i < len; i++)+ {+ spiSendByte(reg_data[i]);+ }++ if (dev_id == BMI088_ACCEL_I2C_ADDR_PRIMARY)+ {+ ACC_DIS_CS();+ }+ else+ {+ GYR_DIS_CS();+ }++ return BSTDR_OK;+}++/***********************+ * I2C private methods *+ ***********************/+static bstdr_ret_t i2c_burst_read(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, uint16_t len)+{+ /**< Burst read code comes here */+ if (i2cdevReadReg8(I2C3_DEV, dev_id, reg_addr, (uint16_t) len, reg_data))+ {+ return BSTDR_OK;+ }+ else+ {+ return BSTDR_E_CON_ERROR;+ }+}++static bstdr_ret_t i2c_burst_write(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, uint16_t len)+{+ /**< Burst write code comes here */+ if (i2cdevWriteReg8(I2C3_DEV, dev_id,reg_addr,(uint16_t) len, reg_data))+ {+ return BSTDR_OK;+ }+ else+ {+ return BSTDR_E_CON_ERROR;+ }+}+++static void bmi088_ms_delay(uint32_t period)+{+ /**< Delay code comes */+ vTaskDelay(M2T(period));+}++static void spiConfigure(void)+{+ SPI_InitTypeDef SPI_InitStructure;++ SPI_Cmd(BMI088_SPI, DISABLE);+ SPI_I2S_DeInit(BMI088_SPI);++ SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;+ SPI_InitStructure.SPI_Mode = SPI_Mode_Master;+ SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;+ SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;+ SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;+ SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;+ SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;+ SPI_InitStructure.SPI_CRCPolynomial = 0; // Not used++ SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4; //~10.5 MHz+ SPI_Init(BMI088_SPI, &SPI_InitStructure);+ /* Enable the SPI */+ SPI_Cmd(BMI088_SPI, ENABLE);+}++/* Initialisation */+static void spiInit(void)+{+ GPIO_InitTypeDef GPIO_InitStructure;++ if (isInit)+ return;++ /* Enable SPI and GPIO clocks */+ RCC_AHB1PeriphClockCmd(BMI088_GPIO_SPI_CLK | BMI088_ACC_GPIO_CS_PERIF, ENABLE);+ /* Enable SPI and GPIO clocks */+ RCC_APB1PeriphClockCmd(BMI088_SPI_CLK, ENABLE);++ /* Configure SPI pins: SCK, MISO and MOSI */+ GPIO_InitStructure.GPIO_Pin = BMI088_GPIO_SPI_SCK | BMI088_GPIO_SPI_MOSI;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;+ GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;+ GPIO_Init(BMI088_GPIO_SPI_PORT, &GPIO_InitStructure);++ //* Configure MISO */+ GPIO_InitStructure.GPIO_Pin = BMI088_GPIO_SPI_MISO;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;+ GPIO_Init(BMI088_GPIO_SPI_PORT, &GPIO_InitStructure);++ /* Configure I/O for the Chip select */+ GPIO_InitStructure.GPIO_Pin = BMI088_ACC_GPIO_CS;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;+ GPIO_Init(BMI088_ACC_GPIO_CS_PORT, &GPIO_InitStructure);+ /* Configure I/O for the Chip select */+ GPIO_InitStructure.GPIO_Pin = BMI088_GYR_GPIO_CS;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;+ GPIO_Init(BMI088_GYR_GPIO_CS_PORT, &GPIO_InitStructure);+++ /*!< Connect SPI pins to AF5 */+ GPIO_PinAFConfig(BMI088_GPIO_SPI_PORT, BMI088_GPIO_SPI_SCK_SRC, BMI088_SPI_AF);+ GPIO_PinAFConfig(BMI088_GPIO_SPI_PORT, BMI088_GPIO_SPI_MISO_SRC, BMI088_SPI_AF);+ GPIO_PinAFConfig(BMI088_GPIO_SPI_PORT, BMI088_GPIO_SPI_MOSI_SRC, BMI088_SPI_AF);++ /* disable the chip select */+ ACC_DIS_CS();++ spiConfigure();+}++static void spiDMAInit(void)+{+ DMA_InitTypeDef DMA_InitStructure;+ NVIC_InitTypeDef NVIC_InitStructure;++ /*!< Enable DMA Clocks */+ BMI088_SPI_DMA_CLK_INIT(BMI088_SPI_DMA_CLK, ENABLE);++ /* Configure DMA Initialization Structure */+ DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;+ DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_1QuarterFull;+ DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;+ DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;+ DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;+ DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;+ DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)(&(BMI088_SPI->DR));+ DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;+ DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;+ DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;+ DMA_InitStructure.DMA_Priority = DMA_Priority_High;+ DMA_InitStructure.DMA_BufferSize = 0; // set later+ DMA_InitStructure.DMA_Memory0BaseAddr = 0; // set later++ // Configure TX DMA+ DMA_InitStructure.DMA_Channel = BMI088_SPI_TX_DMA_CHANNEL;+ DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;+ DMA_Cmd(BMI088_SPI_TX_DMA_STREAM,DISABLE);+ DMA_Init(BMI088_SPI_TX_DMA_STREAM, &DMA_InitStructure);++ // Configure RX DMA+ DMA_InitStructure.DMA_Channel = BMI088_SPI_RX_DMA_CHANNEL;+ DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;+ DMA_Cmd(BMI088_SPI_RX_DMA_STREAM, DISABLE);+ DMA_Init(BMI088_SPI_RX_DMA_STREAM, &DMA_InitStructure);++ // Configure interrupts+ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_HIGH_PRI;+ NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;+ NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;++ NVIC_InitStructure.NVIC_IRQChannel = BMI088_SPI_TX_DMA_IRQ;+ NVIC_Init(&NVIC_InitStructure);++ NVIC_InitStructure.NVIC_IRQChannel = BMI088_SPI_RX_DMA_IRQ;+ NVIC_Init(&NVIC_InitStructure);++ spiTxDMAComplete = xSemaphoreCreateBinaryStatic(&spiTxDMACompleteBuffer);+ spiRxDMAComplete = xSemaphoreCreateBinaryStatic(&spiRxDMACompleteBuffer);+}++static uint16_t sensorsGyroGet(Axis3i16* dataOut)+{+ return bmi088_get_gyro_data((struct bmi088_sensor_data*)dataOut, &bmi088Dev);+}++static void sensorsAccelGet(Axis3i16* dataOut)+{+ bmi088_get_accel_data((struct bmi088_sensor_data*)dataOut, &bmi088Dev);+}++static void sensorsScaleBaro(baro_t* baroScaled, float pressure,+ float temperature)+{+ baroScaled->pressure = pressure*0.01f;+ baroScaled->temperature = temperature;+ baroScaled->asl = ((powf((1015.7f / baroScaled->pressure), 0.1902630958f)+ - 1.0f) * (25.0f + 273.15f)) / 0.0065f;+}++bool sensorsBmi088SpiBmp388ReadGyro(Axis3f *gyro)+{+ return (pdTRUE == xQueueReceive(gyroDataQueue, gyro, 0));+}++bool sensorsBmi088SpiBmp388ReadAcc(Axis3f *acc)+{+ return (pdTRUE == xQueueReceive(accelerometerDataQueue, acc, 0));+}++bool sensorsBmi088SpiBmp388ReadMag(Axis3f *mag)+{+ return (pdTRUE == xQueueReceive(magnetometerDataQueue, mag, 0));+}++bool sensorsBmi088SpiBmp388ReadBaro(baro_t *baro)+{+ return (pdTRUE == xQueueReceive(barometerDataQueue, baro, 0));+}++void sensorsBmi088SpiBmp388Acquire(sensorData_t *sensors, const uint32_t tick)+{+ sensorsReadGyro(&sensors->gyro);+ sensorsReadAcc(&sensors->acc);+ sensorsReadMag(&sensors->mag);+ sensorsReadBaro(&sensors->baro);+ sensors->interruptTimestamp = sensorData.interruptTimestamp;+}++bool sensorsBmi088SpiBmp388AreCalibrated()+{+ return gyroBiasFound;+}++static void sensorsTask(void *param)+{+ systemWaitStart();++ Axis3f accScaled;+ /* wait an additional second the keep bus free+ * this is only required by the z-ranger, since the+ * configuration will be done after system start-up */+ //vTaskDelayUntil(&lastWakeTime, M2T(1500));+ while (1)+ {+ if (pdTRUE == xSemaphoreTake(sensorsDataReady, portMAX_DELAY))+ {+ sensorData.interruptTimestamp = imuIntTimestamp;++ /* get data from chosen sensors */+ sensorsGyroGet(&gyroRaw);+ sensorsAccelGet(&accelRaw);++ /* calibrate if necessary */+#ifdef GYRO_BIAS_LIGHT_WEIGHT+ gyroBiasFound = processGyroBiasNoBuffer(gyroRaw.x, gyroRaw.y, gyroRaw.z, &gyroBias);+#else+ gyroBiasFound = processGyroBias(gyroRaw.x, gyroRaw.y, gyroRaw.z, &gyroBias);+#endif+ if (gyroBiasFound)+ {+ processAccScale(accelRaw.x, accelRaw.y, accelRaw.z);+ }+ /* Gyro */+ sensorData.gyro.x = (gyroRaw.x - gyroBias.x) * SENSORS_BMI088_DEG_PER_LSB_CFG;+ sensorData.gyro.y = (gyroRaw.y - gyroBias.y) * SENSORS_BMI088_DEG_PER_LSB_CFG;+ sensorData.gyro.z = (gyroRaw.z - gyroBias.z) * SENSORS_BMI088_DEG_PER_LSB_CFG;+ applyAxis3fLpf((lpf2pData*)(&gyroLpf), &sensorData.gyro);++ /* Acelerometer */+ accScaled.x = accelRaw.x * SENSORS_BMI088_G_PER_LSB_CFG / accScale;+ accScaled.y = accelRaw.y * SENSORS_BMI088_G_PER_LSB_CFG / accScale;+ accScaled.z = accelRaw.z * SENSORS_BMI088_G_PER_LSB_CFG / accScale;+ sensorsAccAlignToGravity(&accScaled, &sensorData.acc);+ applyAxis3fLpf((lpf2pData*)(&accLpf), &sensorData.acc);+ }++ if (isBarometerPresent)+ {+ static uint8_t baroMeasDelay = SENSORS_DELAY_BARO;+ if (--baroMeasDelay == 0)+ {+ uint8_t sensor_comp = BMP3_PRESS | BMP3_TEMP;+ struct bmp3_data data;+ baro_t* baro388 = &sensorData.baro;+ /* Temperature and Pressure data are read and stored in the bmp3_data instance */+ bmp3_get_sensor_data(sensor_comp, &data, &bmp388Dev);+ sensorsScaleBaro(baro388, data.pressure, data.temperature);+ baroMeasDelay = baroMeasDelayMin;+ }+ }+ xQueueOverwrite(accelerometerDataQueue, &sensorData.acc);+ xQueueOverwrite(gyroDataQueue, &sensorData.gyro);+ if (isBarometerPresent)+ {+ xQueueOverwrite(barometerDataQueue, &sensorData.baro);+ }++ xSemaphoreGive(dataReady);+ }+}++void sensorsBmi088SpiBmp388WaitDataReady(void)+{+ xSemaphoreTake(dataReady, portMAX_DELAY);+}++static void sensorsDeviceInit(void)+{+ if (isInit)+ return;++ bstdr_ret_t rslt;+ isBarometerPresent = false;++ // Wait for sensors to startup+ vTaskDelay(M2T(SENSORS_STARTUP_TIME_MS));++ /* BMI088 */+ bmi088Dev.accel_id = BMI088_ACCEL_I2C_ADDR_PRIMARY;+ bmi088Dev.gyro_id = BMI088_GYRO_I2C_ADDR_PRIMARY;+ bmi088Dev.interface = BMI088_SPI_INTF;+ bmi088Dev.read = spi_burst_read;+ bmi088Dev.write = spi_burst_write;+ bmi088Dev.delay_ms = bmi088_ms_delay;++ /* BMI088 GYRO */+ rslt = bmi088_gyro_init(&bmi088Dev); // initialize the device+ if (rslt == BSTDR_OK)+ {+ struct bmi088_int_cfg intConfig;++ DEBUG_PRINT("BMI088 Gyro SPI connection [OK].\n");+ /* set power mode of gyro */+ bmi088Dev.gyro_cfg.power = BMI088_GYRO_PM_NORMAL;+ rslt |= bmi088_set_gyro_power_mode(&bmi088Dev);+ /* set bandwidth and range of gyro */+ bmi088Dev.gyro_cfg.bw = BMI088_GYRO_BW_116_ODR_1000_HZ;+ bmi088Dev.gyro_cfg.range = SENSORS_BMI088_GYRO_FS_CFG;+ bmi088Dev.gyro_cfg.odr = BMI088_GYRO_BW_116_ODR_1000_HZ;+ rslt |= bmi088_set_gyro_meas_conf(&bmi088Dev);++ intConfig.gyro_int_channel = BMI088_INT_CHANNEL_3;+ intConfig.gyro_int_type = BMI088_GYRO_DATA_RDY_INT;+ intConfig.gyro_int_pin_3_cfg.enable_int_pin = 1;+ intConfig.gyro_int_pin_3_cfg.lvl = 1;+ intConfig.gyro_int_pin_3_cfg.output_mode = 0;+ /* Setting the interrupt configuration */+ rslt = bmi088_set_gyro_int_config(&intConfig, &bmi088Dev);++ bmi088Dev.delay_ms(50);+ struct bmi088_sensor_data gyr;+ rslt |= bmi088_get_gyro_data(&gyr, &bmi088Dev);++ }+ else+ {+#ifndef SENSORS_IGNORE_IMU_FAIL+ DEBUG_PRINT("BMI088 Gyro SPI connection [FAIL]\n");+ isInit = false;+#endif+ }++ /* BMI088 ACCEL */+ rslt |= bmi088_accel_switch_control(&bmi088Dev, BMI088_ACCEL_POWER_ENABLE);+ bmi088Dev.delay_ms(5);++ rslt = bmi088_accel_init(&bmi088Dev); // initialize the device+ if (rslt == BSTDR_OK)+ {+ DEBUG_PRINT("BMI088 Accel SPI connection [OK]\n");+ /* set power mode of accel */+ bmi088Dev.accel_cfg.power = BMI088_ACCEL_PM_ACTIVE;+ rslt |= bmi088_set_accel_power_mode(&bmi088Dev);+ bmi088Dev.delay_ms(10);++ /* set bandwidth and range of accel */+ bmi088Dev.accel_cfg.bw = BMI088_ACCEL_BW_OSR4;+ bmi088Dev.accel_cfg.range = SENSORS_BMI088_ACCEL_FS_CFG;+ bmi088Dev.accel_cfg.odr = BMI088_ACCEL_ODR_1600_HZ;+ rslt |= bmi088_set_accel_meas_conf(&bmi088Dev);++ struct bmi088_sensor_data acc;+ rslt |= bmi088_get_accel_data(&acc, &bmi088Dev);+ }+ else+ {+#ifndef SENSORS_IGNORE_IMU_FAIL+ DEBUG_PRINT("BMI088 Accel SPI connection [FAIL]\n");+ isInit = false;+#endif+ }++ /* BMP388 */+ bmp388Dev.dev_id = BMP3_I2C_ADDR_SEC;+ bmp388Dev.intf = BMP3_I2C_INTF;+ bmp388Dev.read = i2c_burst_read;+ bmp388Dev.write = i2c_burst_write;+ bmp388Dev.delay_ms = bmi088_ms_delay;++ int i = 3;+ do {+ bmp388Dev.delay_ms(1);+ // For some reason it often doesn't work first time+ rslt = bmp3_init(&bmp388Dev);+ } while (rslt != BMP3_OK && i-- > 0);++ if (rslt == BMP3_OK)+ {+ isBarometerPresent = true;+ DEBUG_PRINT("BMP388 I2C connection [OK]\n");+ /* Used to select the settings user needs to change */+ uint16_t settings_sel;+ /* Select the pressure and temperature sensor to be enabled */+ bmp388Dev.settings.press_en = BMP3_ENABLE;+ bmp388Dev.settings.temp_en = BMP3_ENABLE;+ /* Select the output data rate and oversampling settings for pressure and temperature */+ bmp388Dev.settings.odr_filter.press_os = BMP3_OVERSAMPLING_8X;+ bmp388Dev.settings.odr_filter.temp_os = BMP3_NO_OVERSAMPLING;+ bmp388Dev.settings.odr_filter.odr = BMP3_ODR_50_HZ;+ bmp388Dev.settings.odr_filter.iir_filter = BMP3_IIR_FILTER_COEFF_3;+ /* Assign the settings which needs to be set in the sensor */+ settings_sel = BMP3_PRESS_EN_SEL | BMP3_TEMP_EN_SEL | BMP3_PRESS_OS_SEL | BMP3_TEMP_OS_SEL | BMP3_ODR_SEL | BMP3_IIR_FILTER_SEL;+ rslt = bmp3_set_sensor_settings(settings_sel, &bmp388Dev);++ /* Set the power mode to normal mode */+ bmp388Dev.settings.op_mode = BMP3_NORMAL_MODE;+ rslt = bmp3_set_op_mode(&bmp388Dev);+++ bmp388Dev.delay_ms(20); // wait before first read out+ // read out data+ /* Variable used to select the sensor component */+ uint8_t sensor_comp;+ /* Variable used to store the compensated data */+ struct bmp3_data data;++ /* Sensor component selection */+ sensor_comp = BMP3_PRESS | BMP3_TEMP;+ /* Temperature and Pressure data are read and stored in the bmp3_data instance */+ rslt = bmp3_get_sensor_data(sensor_comp, &data, &bmp388Dev);++ /* Print the temperature and pressure data */+// DEBUG_PRINT("BMP388 T:%0.2f P:%0.2f\n",data.temperature, data.pressure/100.0f);+ baroMeasDelayMin = SENSORS_DELAY_BARO;+ }+ else+ {+#ifndef SENSORS_IGNORE_BAROMETER_FAIL+ DEBUG_PRINT("BMP388 I2C connection [FAIL]\n");+ isInit = false;+ return;+#endif+ }++ // Init second order filer for accelerometer and gyro+ for (uint8_t i = 0; i < 3; i++)+ {+ lpf2pInit(&gyroLpf[i], 1000, GYRO_LPF_CUTOFF_FREQ);+ lpf2pInit(&accLpf[i], 1000, ACCEL_LPF_CUTOFF_FREQ);+ }++ cosPitch = cosf(configblockGetCalibPitch() * (float) M_PI / 180);+ sinPitch = sinf(configblockGetCalibPitch() * (float) M_PI / 180);+ cosRoll = cosf(configblockGetCalibRoll() * (float) M_PI / 180);+ sinRoll = sinf(configblockGetCalibRoll() * (float) M_PI / 180);++ isInit = true;+}++static void sensorsTaskInit(void)+{+ accelerometerDataQueue = STATIC_MEM_QUEUE_CREATE(accelerometerDataQueue);+ gyroDataQueue = STATIC_MEM_QUEUE_CREATE(gyroDataQueue);+ magnetometerDataQueue = STATIC_MEM_QUEUE_CREATE(magnetometerDataQueue);+ barometerDataQueue = STATIC_MEM_QUEUE_CREATE(barometerDataQueue);++ STATIC_MEM_TASK_CREATE(sensorsTask, sensorsTask, SENSORS_TASK_NAME, NULL, SENSORS_TASK_PRI);+}++static void sensorsInterruptInit(void)+{+ GPIO_InitTypeDef GPIO_InitStructure;+ EXTI_InitTypeDef EXTI_InitStructure;++ sensorsDataReady = xSemaphoreCreateBinaryStatic(&sensorsDataReadyBuffer);+ dataReady = xSemaphoreCreateBinaryStatic(&dataReadyBuffer);++ // Enable the interrupt on PC14+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;+ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; //GPIO_PuPd_DOWN;+ GPIO_Init(GPIOC, &GPIO_InitStructure);++ SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC, EXTI_PinSource14);++ EXTI_InitStructure.EXTI_Line = EXTI_Line14;+ EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;+ EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;+ EXTI_InitStructure.EXTI_LineCmd = ENABLE;+ portDISABLE_INTERRUPTS();+ EXTI_Init(&EXTI_InitStructure);+ EXTI_ClearITPendingBit(EXTI_Line14);+ portENABLE_INTERRUPTS();+}++void sensorsBmi088SpiBmp388Init(void)+{+ if (isInit)+ {+ return;+ }++ i2cdevInit(I2C3_DEV);+ spiInit();+ spiDMAInit();++ sensorsBiasObjInit(&gyroBiasRunning);+ sensorsDeviceInit();+ sensorsInterruptInit();+ sensorsTaskInit();+}++static bool gyroSelftest()+{+ bool testStatus = true;++ int i = 3;+ uint16_t readResult = BMI088_OK;+ do {+ readResult = sensorsGyroGet(&gyroRaw);+ } while (readResult != BMI088_OK && i-- > 0);++ if ((readResult != BMI088_OK) || (gyroRaw.x == 0 && gyroRaw.y == 0 && gyroRaw.z == 0))+ {+ DEBUG_PRINT("BMI088 gyro returning x=0 y=0 z=0 [FAILED]\n");+ testStatus = false;+ }++ int8_t gyroResult = 0;+ bmi088_perform_gyro_selftest(&gyroResult, &bmi088Dev);+ if (gyroResult == BMI088_SELFTEST_PASS)+ {+ DEBUG_PRINT("BMI088 gyro self-test [OK]\n");+ }+ else+ {+ DEBUG_PRINT("BMI088 gyro self-test [FAILED]\n");+ testStatus = false;+ }++ return testStatus;+}++bool sensorsBmi088SpiBmp388Test(void)+{+ bool testStatus = true;++ if (!isInit)+ {+ DEBUG_PRINT("Uninitialized\n");+ testStatus = false;+ }++ if (! gyroSelftest())+ {+ testStatus = false;+ }++ return testStatus;+}++/**+ * Calculates accelerometer scale out of SENSORS_ACC_SCALE_SAMPLES samples. Should be called when+ * platform is stable.+ */+static bool processAccScale(int16_t ax, int16_t ay, int16_t az)+{+ if (!accScaleFound)+ {+ accScaleSum += sqrtf(powf(ax * SENSORS_BMI088_G_PER_LSB_CFG, 2) + powf(ay * SENSORS_BMI088_G_PER_LSB_CFG, 2) + powf(az * SENSORS_BMI088_G_PER_LSB_CFG, 2));+ accScaleSumCount++;++ if (accScaleSumCount == SENSORS_ACC_SCALE_SAMPLES)+ {+ accScale = accScaleSum / SENSORS_ACC_SCALE_SAMPLES;+ accScaleFound = true;+ }+ }++ return accScaleFound;+}++#ifdef GYRO_BIAS_LIGHT_WEIGHT++#define SENSORS_BIAS_SAMPLES 1000+/**+ * Calculates the bias out of the first SENSORS_BIAS_SAMPLES gathered. Requires no buffer+ * but needs platform to be stable during startup.+ */+static bool processGyroBiasNoBuffer(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut)+{+ static uint32_t gyroBiasSampleCount = 0;+ static bool gyroBiasNoBuffFound = false;+ static Axis3i64 gyroBiasSampleSum;+ static Axis3i64 gyroBiasSampleSumSquares;++ if (!gyroBiasNoBuffFound)+ {+ // If the gyro has not yet been calibrated:+ // Add the current sample to the running mean and variance+ gyroBiasSampleSum.x += gx;+ gyroBiasSampleSum.y += gy;+ gyroBiasSampleSum.z += gz;+#ifdef SENSORS_GYRO_BIAS_CALCULATE_STDDEV+ gyroBiasSampleSumSquares.x += gx * gx;+ gyroBiasSampleSumSquares.y += gy * gy;+ gyroBiasSampleSumSquares.z += gz * gz;+#endif+ gyroBiasSampleCount += 1;++ // If we then have enough samples, calculate the mean and standard deviation+ if (gyroBiasSampleCount == SENSORS_BIAS_SAMPLES)+ {+ gyroBiasOut->x = (float)(gyroBiasSampleSum.x) / SENSORS_BIAS_SAMPLES;+ gyroBiasOut->y = (float)(gyroBiasSampleSum.y) / SENSORS_BIAS_SAMPLES;+ gyroBiasOut->z = (float)(gyroBiasSampleSum.z) / SENSORS_BIAS_SAMPLES;++#ifdef SENSORS_GYRO_BIAS_CALCULATE_STDDEV+ gyroBiasStdDev.x = sqrtf((float)(gyroBiasSampleSumSquares.x) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->x * gyroBiasOut->x));+ gyroBiasStdDev.y = sqrtf((float)(gyroBiasSampleSumSquares.y) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->y * gyroBiasOut->y));+ gyroBiasStdDev.z = sqrtf((float)(gyroBiasSampleSumSquares.z) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->z * gyroBiasOut->z));+#endif+ gyroBiasNoBuffFound = true;+ }+ }++ return gyroBiasNoBuffFound;+}+#else+/**+ * Calculates the bias first when the gyro variance is below threshold. Requires a buffer+ * but calibrates platform first when it is stable.+ */+static bool processGyroBias(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut)+{+ sensorsAddBiasValue(&gyroBiasRunning, gx, gy, gz);++ if (!gyroBiasRunning.isBiasValueFound)+ {+ sensorsFindBiasValue(&gyroBiasRunning);+ if (gyroBiasRunning.isBiasValueFound)+ {+ soundSetEffect(SND_CALIB);+ ledseqRun(&seq_calibrated);+ }+ }++ gyroBiasOut->x = gyroBiasRunning.bias.x;+ gyroBiasOut->y = gyroBiasRunning.bias.y;+ gyroBiasOut->z = gyroBiasRunning.bias.z;++ return gyroBiasRunning.isBiasValueFound;+}+#endif++static void sensorsBiasObjInit(BiasObj* bias)+{+ bias->isBufferFilled = false;+ bias->bufHead = bias->buffer;+}++/**+ * Calculates the variance and mean for the bias buffer.+ */+static void sensorsCalculateVarianceAndMean(BiasObj* bias, Axis3f* varOut, Axis3f* meanOut)+{+ uint32_t i;+ int64_t sum[GYRO_NBR_OF_AXES] = {0};+ int64_t sumSq[GYRO_NBR_OF_AXES] = {0};++ for (i = 0; i < SENSORS_NBR_OF_BIAS_SAMPLES; i++)+ {+ sum[0] += bias->buffer[i].x;+ sum[1] += bias->buffer[i].y;+ sum[2] += bias->buffer[i].z;+ sumSq[0] += bias->buffer[i].x * bias->buffer[i].x;+ sumSq[1] += bias->buffer[i].y * bias->buffer[i].y;+ sumSq[2] += bias->buffer[i].z * bias->buffer[i].z;+ }++ varOut->x = (sumSq[0] - ((int64_t)sum[0] * sum[0]) / SENSORS_NBR_OF_BIAS_SAMPLES);+ varOut->y = (sumSq[1] - ((int64_t)sum[1] * sum[1]) / SENSORS_NBR_OF_BIAS_SAMPLES);+ varOut->z = (sumSq[2] - ((int64_t)sum[2] * sum[2]) / SENSORS_NBR_OF_BIAS_SAMPLES);++ meanOut->x = (float)sum[0] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->y = (float)sum[1] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->z = (float)sum[2] / SENSORS_NBR_OF_BIAS_SAMPLES;+}++/**+ * Calculates the mean for the bias buffer.+ */+static void __attribute__((used)) sensorsCalculateBiasMean(BiasObj* bias, Axis3i32* meanOut)+{+ uint32_t i;+ int32_t sum[GYRO_NBR_OF_AXES] = {0};++ for (i = 0; i < SENSORS_NBR_OF_BIAS_SAMPLES; i++)+ {+ sum[0] += bias->buffer[i].x;+ sum[1] += bias->buffer[i].y;+ sum[2] += bias->buffer[i].z;+ }++ meanOut->x = sum[0] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->y = sum[1] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->z = sum[2] / SENSORS_NBR_OF_BIAS_SAMPLES;+}++/**+ * Adds a new value to the variance buffer and if it is full+ * replaces the oldest one. Thus a circular buffer.+ */+static void sensorsAddBiasValue(BiasObj* bias, int16_t x, int16_t y, int16_t z)+{+ bias->bufHead->x = x;+ bias->bufHead->y = y;+ bias->bufHead->z = z;+ bias->bufHead++;++ if (bias->bufHead >= &bias->buffer[SENSORS_NBR_OF_BIAS_SAMPLES])+ {+ bias->bufHead = bias->buffer;+ bias->isBufferFilled = true;+ }+}++/**+ * Checks if the variances is below the predefined thresholds.+ * The bias value should have been added before calling this.+ * @param bias The bias object+ */+static bool sensorsFindBiasValue(BiasObj* bias)+{+ static int32_t varianceSampleTime;+ bool foundBias = false;++ if (bias->isBufferFilled)+ {+ sensorsCalculateVarianceAndMean(bias, &bias->variance, &bias->mean);++ if (bias->variance.x < GYRO_VARIANCE_THRESHOLD_X &&+ bias->variance.y < GYRO_VARIANCE_THRESHOLD_Y &&+ bias->variance.z < GYRO_VARIANCE_THRESHOLD_Z &&+ (varianceSampleTime + GYRO_MIN_BIAS_TIMEOUT_MS < xTaskGetTickCount()))+ {+ varianceSampleTime = xTaskGetTickCount();+ bias->bias.x = bias->mean.x;+ bias->bias.y = bias->mean.y;+ bias->bias.z = bias->mean.z;+ foundBias = true;+ bias->isBiasValueFound = true;+ }+ }++ return foundBias;+}++bool sensorsBmi088SpiBmp388ManufacturingTest(void)+{+ bool testStatus = true;+ if (! gyroSelftest())+ {+ testStatus = false;+ }++ int8_t accResult = 0;+ bmi088_perform_accel_selftest(&accResult, &bmi088Dev);+ if (accResult == BMI088_SELFTEST_PASS)+ {+ DEBUG_PRINT("BMI088 acc self-test [OK]\n");+ }+ else+ {+ DEBUG_PRINT("BMI088 acc self-test [FAILED]\n");+ testStatus = false;+ }++ return testStatus;+}++/**+ * Compensate for a miss-aligned accelerometer. It uses the trim+ * data gathered from the UI and written in the config-block to+ * rotate the accelerometer to be aligned with gravity.+ */+static void sensorsAccAlignToGravity(Axis3f* in, Axis3f* out)+{+ Axis3f rx;+ Axis3f ry;++ // Rotate around x-axis+ rx.x = in->x;+ rx.y = in->y * cosRoll - in->z * sinRoll;+ rx.z = in->y * sinRoll + in->z * cosRoll;++ // Rotate around y-axis+ ry.x = rx.x * cosPitch - rx.z * sinPitch;+ ry.y = rx.y;+ ry.z = -rx.x * sinPitch + rx.z * cosPitch;++ out->x = ry.x;+ out->y = ry.y;+ out->z = ry.z;+}++void sensorsBmi088SpiBmp388SetAccMode(accModes accMode)+{+ switch (accMode)+ {+ case ACC_MODE_PROPTEST:+// bmi088_accel_soft_reset(&bmi088Dev);+ /* set bandwidth and range of accel (280Hz cut-off according to datasheet) */+ bmi088Dev.accel_cfg.bw = BMI088_ACCEL_BW_NORMAL;+ bmi088Dev.accel_cfg.range = SENSORS_BMI088_ACCEL_FS_CFG;+ bmi088Dev.accel_cfg.odr = BMI088_ACCEL_ODR_1600_HZ;+ if (bmi088_set_accel_meas_conf(&bmi088Dev) != BMI088_OK)+ {+ DEBUG_PRINT("ACC config [FAIL]\n");+ }+ for (uint8_t i = 0; i < 3; i++)+ {+ lpf2pInit(&accLpf[i], 1000, 500);+ }+ break;+ case ACC_MODE_FLIGHT:+ default:+ /* set bandwidth and range of accel (145Hz cut-off according to datasheet) */+ bmi088Dev.accel_cfg.bw = BMI088_ACCEL_BW_OSR4;+ bmi088Dev.accel_cfg.range = SENSORS_BMI088_ACCEL_FS_CFG;+ bmi088Dev.accel_cfg.odr = BMI088_ACCEL_ODR_1600_HZ;+ if (bmi088_set_accel_meas_conf(&bmi088Dev) != BMI088_OK)+ {+ DEBUG_PRINT("ACC config [FAIL]\n");+ }+ for (uint8_t i = 0; i < 3; i++)+ {+ lpf2pInit(&accLpf[i], 1000, ACCEL_LPF_CUTOFF_FREQ);+ }+ break;+ }+}++static void applyAxis3fLpf(lpf2pData *data, Axis3f* in)+{+ for (uint8_t i = 0; i < 3; i++) {+ in->axis[i] = lpf2pApply(&data[i], in->axis[i]);+ }+}++void sensorsBmi088SpiBmp388DataAvailableCallback(void)+{+ portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;+ imuIntTimestamp = usecTimestamp();+ xSemaphoreGiveFromISR(sensorsDataReady, &xHigherPriorityTaskWoken);++ if (xHigherPriorityTaskWoken)+ {+ portYIELD();+ }+}++void __attribute__((used)) BMI088_SPI_TX_DMA_IRQHandler(void)+{+ portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;++ // Stop and cleanup DMA stream+ DMA_ITConfig(BMI088_SPI_TX_DMA_STREAM, DMA_IT_TC, DISABLE);+ DMA_ClearITPendingBit(BMI088_SPI_TX_DMA_STREAM, BMI088_SPI_TX_DMA_FLAG_TCIF);++ // Clear stream flags+ DMA_ClearFlag(BMI088_SPI_TX_DMA_STREAM,BMI088_SPI_TX_DMA_FLAG_TCIF);++ // Disable SPI DMA requests+ SPI_I2S_DMACmd(BMI088_SPI, SPI_I2S_DMAReq_Tx, DISABLE);++ // Disable streams+ DMA_Cmd(BMI088_SPI_TX_DMA_STREAM, DISABLE);++ // Give the semaphore, allowing the SPI transaction to complete+ xSemaphoreGiveFromISR(spiTxDMAComplete, &xHigherPriorityTaskWoken);++ if (xHigherPriorityTaskWoken)+ {+ portYIELD();+ }+}++void __attribute__((used)) BMI088_SPI_RX_DMA_IRQHandler(void)+{+ portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;++ // Stop and cleanup DMA stream+ DMA_ITConfig(BMI088_SPI_RX_DMA_STREAM, DMA_IT_TC, DISABLE);+ DMA_ClearITPendingBit(BMI088_SPI_RX_DMA_STREAM, BMI088_SPI_RX_DMA_FLAG_TCIF);++ // Clear stream flags+ DMA_ClearFlag(BMI088_SPI_RX_DMA_STREAM, BMI088_SPI_RX_DMA_FLAG_TCIF);++ // Disable SPI DMA requests+ SPI_I2S_DMACmd(BMI088_SPI, SPI_I2S_DMAReq_Rx, DISABLE);++ // Disable streams+ DMA_Cmd(BMI088_SPI_RX_DMA_STREAM, DISABLE);++ // Give the semaphore, allowing the SPI transaction to complete+ xSemaphoreGiveFromISR(spiRxDMAComplete, &xHigherPriorityTaskWoken);++ if (xHigherPriorityTaskWoken)+ {+ portYIELD();+ }+}++PARAM_GROUP_START(imu_sensors)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, BMP388, &isBarometerPresent)+PARAM_GROUP_STOP(imu_sensors)diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_bosch.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_bosch.cnew file mode 100644index 0000000..72f9b93--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_bosch.c@@ -0,0 +1,950 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * sensors_bosch.c+ */++/*********************************************+ * IMPORTANT NOTE relating to sensor_deck v1 *+ * Don't miss to align the axes correctly! *+ *********************************************/+#define DEBUG_MODULE "IMU"++#include "sensors_bosch.h"++#include <math.h>++#include "stm32fxxx.h"++#include "imu.h"++#include "FreeRTOS.h"+#include "semphr.h"+#include "task.h"++#include "system.h"+#include "configblock.h"+#include "param.h"+#include "debug.h"+#include "nvicconf.h"+#include "ledseq.h"+#include "sound.h"+#include "filter.h"++/* Bosch Sensortec Drivers */+#include "bmi055.h"+#include "bmi088.h"+#include "bmi160.h"+#include "bmm150.h"+#include "bmp280.h"+#include "bmp3.h"+#include "bstdr_comm_support.h"+#include "static_mem.h"++#define SENSORS_READ_RATE_HZ 1000+#define SENSORS_STARTUP_TIME_MS 1000+#define SENSORS_READ_BARO_HZ 50+#define SENSORS_READ_MAG_HZ 20+#define SENSORS_DELAY_BARO (SENSORS_READ_RATE_HZ/SENSORS_READ_BARO_HZ)+#define SENSORS_DELAY_MAG (SENSORS_READ_RATE_HZ/SENSORS_READ_MAG_HZ)++/* calculate constants */+/* BMI160 */+#define SENSORS_BMI160_GYRO_FS_CFG BMI160_GYRO_RANGE_2000_DPS+#define SENSORS_BMI160_DEG_PER_LSB_CFG (2.0f *2000.0f) / 65536.0f++#define SENSORS_BMI160_ACCEL_CFG 16+#define SENSORS_BMI160_ACCEL_FS_CFG BMI160_ACCEL_RANGE_16G+#define SENSORS_BMI160_G_PER_LSB_CFG (2.0f * (float)SENSORS_BMI160_ACCEL_CFG) / 65536.0f+#define SENSORS_BMI160_1G_IN_LSB 65536 / SENSORS_BMI160_ACCEL_CFG / 2++/* BMI055 */+#define SENSORS_BMI055_GYRO_FS_CFG BMI055_GYRO_RANGE_2000_DPS+#define SENSORS_BMI055_DEG_PER_LSB_CFG (2.0f *2000.0f) / 65536.0f++#define SENSORS_BMI055_ACCEL_CFG 16+#define SENSORS_BMI055_ACCEL_FS_CFG BMI055_ACCEL_RANGE_16G+#define SENSORS_BMI055_G_PER_LSB_CFG (2.0f * (float)SENSORS_BMI055_ACCEL_CFG) / 65536.0f+#define SENSORS_BMI055_1G_IN_LSB (65536 / SENSORS_BMI055_ACCEL_CFG / 2)++/* BMI088 */+#define SENSORS_BMI088_GYRO_FS_CFG BMI088_GYRO_RANGE_2000_DPS+#define SENSORS_BMI088_DEG_PER_LSB_CFG (2.0f *2000.0f) / 65536.0f++#define SENSORS_BMI088_ACCEL_CFG 24+#define SENSORS_BMI088_ACCEL_FS_CFG BMI088_ACCEL_RANGE_24G+#define SENSORS_BMI088_G_PER_LSB_CFG (2.0f * (float)SENSORS_BMI088_ACCEL_CFG) / 65536.0f+#define SENSORS_BMI088_1G_IN_LSB (65536 / SENSORS_BMI088_ACCEL_CFG / 2)++#define SENSORS_VARIANCE_MAN_TEST_TIMEOUT M2T(1000) // Timeout in ms+#define SENSORS_MAN_TEST_LEVEL_MAX 5.0f // Max degrees off++#define GYRO_NBR_OF_AXES 3+#define GYRO_MIN_BIAS_TIMEOUT_MS M2T(1*1000)++// Number of samples used in variance calculation. Changing this effects the threshold+#define SENSORS_NBR_OF_BIAS_SAMPLES 512++// Variance threshold to take zero bias for gyro+#define GYRO_VARIANCE_BASE 2000+#define GYRO_VARIANCE_THRESHOLD_X (GYRO_VARIANCE_BASE)+#define GYRO_VARIANCE_THRESHOLD_Y (GYRO_VARIANCE_BASE)+#define GYRO_VARIANCE_THRESHOLD_Z (GYRO_VARIANCE_BASE)++++#define SENSORS_TAKE_ACCEL_BIAS++/* available sensors */+#define SENSORS_BMI055 0x01+#define SENSORS_BMI160 0x02+#define SENSORS_BMM150 0x08+#define SENSORS_BMP280 0x10++/* configure sensor's use+ * PRIMARIES are the sensors which are used for stabilization+ * SECONDARIES are only added to the log if compilations is+ * done with CFLAGS += -DLOG_SEC_IMU */+static uint8_t gyroPrimInUse = SENSORS_BMI055;+static uint8_t accelPrimInUse = SENSORS_BMI055;+//static uint8_t baroPrimInUse = SENSORS_BMP280;+#ifdef LOG_SEC_IMU+static uint8_t gyroSecInUse = SENSORS_BMI160;+static uint8_t accelSecInUse = SENSORS_BMI160;+#endif++typedef struct {+ Axis3i16 value;+ Axis3i16* bufStart;+ Axis3i16* bufPtr;+ uint8_t found : 1;+ uint8_t ongoing : 1;+ uint8_t bufIsFull : 1;+} BiasObj;++/* initialize necessary variables */+static struct bmi160_dev bmi160Dev;+static struct bmi055_dev bmi055Dev;+static struct bmp280_t bmp280Dev;+static struct bmm150_dev bmm150Dev;++static xQueueHandle accelPrimDataQueue;+STATIC_MEM_QUEUE_ALLOC(accelPrimDataQueue, 1, sizeof(Axis3f));+static xQueueHandle gyroPrimDataQueue;+STATIC_MEM_QUEUE_ALLOC(gyroPrimDataQueue, 1, sizeof(Axis3f));+#ifdef LOG_SEC_IMU+static xQueueHandle accelSecDataQueue;+STATIC_MEM_QUEUE_ALLOC(accelSecDataQueue, 1, sizeof(Axis3f));+static xQueueHandle gyroSecDataQueue;+STATIC_MEM_QUEUE_ALLOC(gyroSecDataQueue, 1, sizeof(Axis3f));+#endif+static xQueueHandle baroPrimDataQueue;+STATIC_MEM_QUEUE_ALLOC(baroPrimDataQueue, 1, sizeof(Axis3f));+static xQueueHandle magPrimDataQueue;+STATIC_MEM_QUEUE_ALLOC(magPrimDataQueue, 1, sizeof(baro_t));++static xSemaphoreHandle dataReady;+static StaticSemaphore_t dataReadyBuffer;++static bool isInit = false;+static bool allSensorsAreCalibrated = false;+static sensorData_t sensors;++static int32_t varianceSampleTime;+static uint8_t sensorsAccLpfAttFactor;++static bool isBarometerPresent = false;+static bool isMagnetometerPresent = false;+static uint8_t baroMeasDelayMin = SENSORS_DELAY_BARO;++// Pre-calculated values for accelerometer alignment+static float cosPitch;+static float sinPitch;+static float cosRoll;+static float sinRoll;++static void sensorsDeviceInit(void);+static void sensorsTaskInit(void);+static void sensorsTask(void *param);+static void sensorsApplyBiasAndScale(Axis3f* scaled, Axis3i16* aligned,+ Axis3i16* bias, float scale);+static void sensorsScaleBaro(baro_t* baroScaled, float pressure,+ float temperature);+static bool processGyroBias(BiasObj* bias);+static void processAccelBias(BiasObj* bias);++static void sensorsAccIIRLPFilter(Axis3i16* in, Axis3i16* out,+ Axis3i32* storedValues, int32_t attenuation);+static void sensorsAccAlignToGravity(Axis3f* in, Axis3f* out);+static void sensorsBiasReset(BiasObj* bias);+static void sensorsBiasMalloc(BiasObj* bias);+static void sensorsBiasFree(BiasObj* bias);+static void sensorsBiasBufPtrIncrement(BiasObj* bias);++STATIC_MEM_TASK_ALLOC(sensorsTask, SENSORS_TASK_STACKSIZE);++void sensorsBoschInit(void)+{+ if (isInit)+ {+ return;+ }++ dataReady = xSemaphoreCreateBinaryStatic(&dataReadyBuffer);++ sensorsDeviceInit();+ sensorsTaskInit();++ isInit = true;+}++static void sensorsDeviceInit(void)+{+ if (isInit)+ return;++ bstdr_ret_t rslt;+ isBarometerPresent = false;++ // Wait for sensors to startup+ vTaskDelay(M2T(SENSORS_STARTUP_TIME_MS));++ /* BMI160 */+ // assign bus read function+ bmi160Dev.read = (bmi160_com_fptr_t)bstdr_burst_read;+ // assign bus write function+ bmi160Dev.write = (bmi160_com_fptr_t)bstdr_burst_write;+ // assign delay function+ bmi160Dev.delay_ms = (bmi160_delay_fptr_t)bstdr_ms_delay;+ bmi160Dev.id = BMI160_I2C_ADDR+1; // I2C device address++ rslt = bmi160_init(&bmi160Dev); // initialize the device+ if (rslt == BSTDR_OK)+ {+ DEBUG_PRINT("BMI160 I2C connection [OK].\n");+ /* Select the Output data rate, range of Gyroscope sensor+ * ~92Hz BW by OSR4 @ODR=800Hz */+ bmi160Dev.gyro_cfg.odr = BMI160_GYRO_ODR_800HZ;+ bmi160Dev.gyro_cfg.range = SENSORS_BMI160_GYRO_FS_CFG;+ bmi160Dev.gyro_cfg.bw = BMI160_GYRO_BW_OSR4_MODE;++ /* Select the power mode of Gyroscope sensor */+ bmi160Dev.gyro_cfg.power = BMI160_GYRO_NORMAL_MODE;++ /* Select the Output data rate, range of accelerometer sensor+ * ~92Hz BW by OSR4 @ODR=800Hz */+ bmi160Dev.accel_cfg.odr = BMI160_ACCEL_ODR_1600HZ;+ bmi160Dev.accel_cfg.range = SENSORS_BMI160_ACCEL_FS_CFG;+ bmi160Dev.accel_cfg.bw = BMI160_ACCEL_BW_OSR4_AVG1;+ /* Select the power mode of accelerometer sensor */+ bmi160Dev.accel_cfg.power = BMI160_ACCEL_NORMAL_MODE;++ /* Set the sensor configuration */+ rslt |= bmi160_set_sens_conf(&bmi160Dev);+ bmi160Dev.delay_ms(50);++ /* read sensor */+ struct bmi160_sensor_data gyr;+ rslt |= bmi160_get_sensor_data(BMI160_GYRO_ONLY, NULL, &gyr,+ &bmi160Dev);+ struct bmi160_sensor_data acc;+ rslt |= bmi160_get_sensor_data(BMI160_ACCEL_ONLY, &acc, NULL,+ &bmi160Dev);+ }+ else+ {+ DEBUG_PRINT("BMI160 I2C connection [FAIL].\n");+ }++ /* BMI055 */+ bmi055Dev.accel_id = BMI055_ACCEL_I2C_ADDR;+ bmi055Dev.gyro_id = BMI055_GYRO_I2C_ADDR;+ bmi055Dev.interface = BMI055_I2C_INTF;+ bmi055Dev.read = (bmi055_com_fptr_t)bstdr_burst_read;+ bmi055Dev.write = (bmi055_com_fptr_t)bstdr_burst_write;+ bmi055Dev.delay_ms = (bmi055_delay_fptr_t)bstdr_ms_delay;++ /* BMI055 GYRO */+ rslt = bmi055_gyro_init(&bmi055Dev); // initialize the device+ if (rslt == BSTDR_OK)+ {+ DEBUG_PRINT("BMI055 Gyro I2C connection [OK].\n");+ /* set power mode of gyro */+ bmi055Dev.gyro_cfg.power = BMI055_GYRO_PM_NORMAL;+ rslt |= bmi055_set_gyro_power_mode(&bmi055Dev);+ /* set bandwidth and range of gyro */+ bmi055Dev.gyro_cfg.bw = BMI055_GYRO_BW_116_HZ;+ bmi055Dev.gyro_cfg.range = SENSORS_BMI055_GYRO_FS_CFG;+ rslt |= bmi055_set_gyro_sensor_config(CONFIG_ALL, &bmi055Dev);++ bmi055Dev.delay_ms(50);+ struct bmi055_sensor_data gyr;+ rslt |= bmi055_get_gyro_data(&gyr, &bmi055Dev);+ }+ else+ {+ DEBUG_PRINT("BMI055 Gyro I2C connection [FAIL].\n");+ }++ /* BMI055 ACCEL */+ rslt = bmi055_accel_init(&bmi055Dev); // initialize the device+ if (rslt == BSTDR_OK)+ {+ DEBUG_PRINT("BMI055 Accel I2C connection [OK].\n");+ /* set power mode of accel */+ bmi055Dev.accel_cfg.power = BMI055_ACCEL_PM_NORMAL;+ rslt |= bmi055_set_accel_power_mode(&bmi055Dev);+ /* set bandwidth and range of accel */+ bmi055Dev.accel_cfg.bw = BMI055_ACCEL_BW_125_HZ;+ bmi055Dev.accel_cfg.range = SENSORS_BMI055_ACCEL_FS_CFG;+ rslt |= bmi055_set_accel_sensor_config(CONFIG_ALL, &bmi055Dev);++ bmi055Dev.delay_ms(10);+ struct bmi055_sensor_data acc;+ rslt |= bmi055_get_accel_data(&acc, &bmi055Dev);+ }+ else+ {+ DEBUG_PRINT("BMI055 Accel I2C connection [FAIL].\n");+ }++ /* BMM150 */+ rslt = BSTDR_E_GEN_ERROR;++ /* Sensor interface over I2C */+ bmm150Dev.id = BMM150_DEFAULT_I2C_ADDRESS;+ bmm150Dev.interface = BMM150_I2C_INTF;+ bmm150Dev.read = (bmm150_com_fptr_t)bstdr_burst_read;+ bmm150Dev.write = (bmm150_com_fptr_t)bstdr_burst_write;+ bmm150Dev.delay_ms = bstdr_ms_delay;++ rslt = bmm150_init(&bmm150Dev);++ if (rslt == BMM150_OK){+ bmm150Dev.settings.pwr_mode = BMM150_NORMAL_MODE;+ rslt |= bmm150_set_op_mode(&bmm150Dev);+ bmm150Dev.settings.preset_mode = BMM150_PRESETMODE_HIGHACCURACY;+ rslt |= bmm150_set_presetmode(&bmm150Dev);++ DEBUG_PRINT("BMM150 I2C connection [OK].\n");+ isMagnetometerPresent = true;+ }++ /* BMP280 */+ rslt = BSTDR_E_GEN_ERROR;++ bmp280Dev.bus_read = bstdr_burst_read;+ bmp280Dev.bus_write = bstdr_burst_write;+ bmp280Dev.delay_ms = bstdr_ms_delay;+ bmp280Dev.dev_addr = BMP280_I2C_ADDRESS1;+ rslt = bmp280_init(&bmp280Dev);+ if (rslt == BSTDR_OK)+ {+ isBarometerPresent = true;+ DEBUG_PRINT("BMP280 I2C connection [OK].\n");+ bmp280_set_filter(BMP280_FILTER_COEFF_OFF);+ bmp280_set_oversamp_temperature(BMP280_OVERSAMP_2X);+ bmp280_set_oversamp_pressure(BMP280_OVERSAMP_8X);+ bmp280_set_power_mode(BMP280_NORMAL_MODE);+ bmp280Dev.delay_ms(20); // wait before first read out+ // read out data+ int32_t v_temp_s32;+ uint32_t v_pres_u32;+ bmp280_read_pressure_temperature(&v_pres_u32, &v_temp_s32);+ baroMeasDelayMin = SENSORS_DELAY_BARO;+ }++ varianceSampleTime = -GYRO_MIN_BIAS_TIMEOUT_MS + 1;+ sensorsAccLpfAttFactor = IMU_ACC_IIR_LPF_ATT_FACTOR;++ cosPitch = cosf(configblockGetCalibPitch() * (float) M_PI / 180);+ sinPitch = sinf(configblockGetCalibPitch() * (float) M_PI / 180);+ cosRoll = cosf(configblockGetCalibRoll() * (float) M_PI / 180);+ sinRoll = sinf(configblockGetCalibRoll() * (float) M_PI / 180);+}++static void sensorsTaskInit(void)+{+ accelPrimDataQueue = STATIC_MEM_QUEUE_CREATE(accelPrimDataQueue);+ gyroPrimDataQueue = STATIC_MEM_QUEUE_CREATE(gyroPrimDataQueue);+#ifdef LOG_SEC_IMU+ accelSecDataQueue = STATIC_MEM_QUEUE_CREATE(accelSecDataQueue);+ gyroSecDataQueue= STATIC_MEM_QUEUE_CREATE(gyroSecDataQueue);+#endif+ magPrimDataQueue = STATIC_MEM_QUEUE_CREATE(magPrimDataQueue);+ baroPrimDataQueue = STATIC_MEM_QUEUE_CREATE(baroPrimDataQueue);++ STATIC_MEM_TASK_CREATE(sensorsTask, sensorsTask, SENSORS_TASK_NAME, NULL, SENSORS_TASK_PRI);+}++static void sensorsGyroGet(Axis3i16* dataOut, uint8_t device) {+ static struct bmi160_sensor_data temp;+ switch(device) {+ case SENSORS_BMI160:+ bmi160_get_sensor_data(BMI160_GYRO_ONLY, NULL, &temp, &bmi160Dev);+ dataOut->x = temp.x;+ dataOut->y = temp.y;+ dataOut->z = temp.z;+ break;+ case SENSORS_BMI055:+ bmi055_get_gyro_data(+ (struct bmi055_sensor_data*)dataOut, &bmi055Dev);+ break;+ }+}++static void sensorsAccelGet(Axis3i16* dataOut, uint8_t device) {+ static struct bmi160_sensor_data temp;+ switch(device) {+ case SENSORS_BMI160:+ bmi160_get_sensor_data(BMI160_ACCEL_ONLY, &temp, NULL, &bmi160Dev);+ dataOut->x = temp.x;+ dataOut->y = temp.y;+ dataOut->z = temp.z;+ break;+ case SENSORS_BMI055:+ bmi055_get_accel_data(+ (struct bmi055_sensor_data*)dataOut, &bmi055Dev);+ /* scale to 16 bit */+ dataOut->x = dataOut->x << 4;+ dataOut->y = dataOut->y << 4;+ dataOut->z = dataOut->z << 4;+ break;+ }+}++static void sensorsGyroCalibrate(BiasObj* gyro, uint8_t type) {+ if (gyro->found == 0)+ {+ if (gyro->ongoing == 0)+ {+ sensorsBiasMalloc(gyro);+ }+ /* write directly into buffer */+ sensorsGyroGet(gyro->bufPtr, type);+ /* FIXME: for sensor deck v1 realignment has to be added her */+ sensorsBiasBufPtrIncrement(gyro);++ if (gyro->bufIsFull == 1)+ {+ if (processGyroBias(gyro))+ sensorsBiasFree(gyro);+ }+ }+}++static void __attribute__((used))+sensorsAccelCalibrate(BiasObj* accel, BiasObj* gyro, uint8_t type) {+ if (accel->found == 0)+ {+ if (accel->ongoing == 0)+ {+ sensorsBiasMalloc(accel);+ }+ /* write directly into buffer */+ sensorsAccelGet(accel->bufPtr, type);+ /* FIXME: for sensor deck v1 realignment has to be added her */+ sensorsBiasBufPtrIncrement(accel);+ if ( (accel->bufIsFull == 1) && (gyro->found == 1) )+ {+ processAccelBias(accel);+ switch(type) {+ case SENSORS_BMI160:+ accel->value.z -= SENSORS_BMI160_1G_IN_LSB;+ break;+ case SENSORS_BMI055:+ accel->value.z -= SENSORS_BMI055_1G_IN_LSB;+ break;+ }+ sensorsBiasFree(accel);+ }+ }+}++static void sensorsTask(void *param)+{+ systemWaitStart();++ uint32_t lastWakeTime = xTaskGetTickCount();+ static BiasObj bmi160GyroBias;+ static BiasObj bmi055GyroBias;+#ifdef SENSORS_TAKE_ACCEL_BIAS+ static BiasObj bmi160AccelBias;+ static BiasObj bmi055AccelBias;+#endif+ Axis3i16 gyroPrim;+ Axis3i16 accelPrim;+ Axis3f accelPrimScaled;+ Axis3i16 accelPrimLPF;+ Axis3i32 accelPrimStoredFilterValues;+#ifdef LOG_SEC_IMU+ Axis3i16 gyroSec;+ Axis3i16 accelSec;+ Axis3f accelSecScaled;+ Axis3i16 accelSecLPF;+ Axis3i32 accelSecStoredFilterValues;+#endif /* LOG_SEC_IMU */+ /* wait an additional second the keep bus free+ * this is only required by the z-ranger, since the+ * configuration will be done after system start-up */+ //vTaskDelayUntil(&lastWakeTime, M2T(1500));+ while (1)+ {+ vTaskDelayUntil(&lastWakeTime, F2T(SENSORS_READ_RATE_HZ));+ /* calibrate if necessary */+ if (!allSensorsAreCalibrated)+ {+ if (!bmi160GyroBias.found) {+ sensorsGyroCalibrate(&bmi160GyroBias, SENSORS_BMI160);+#ifdef SENSORS_TAKE_ACCEL_BIAS+ sensorsAccelCalibrate(&bmi160AccelBias,+ &bmi160GyroBias, SENSORS_BMI160);+#endif+ }++ if (!bmi055GyroBias.found)+ {+ sensorsGyroCalibrate(&bmi055GyroBias, SENSORS_BMI055);+#ifdef SENSORS_TAKE_ACCEL_BIAS+ sensorsAccelCalibrate(&bmi055AccelBias,+ &bmi055GyroBias, SENSORS_BMI055);+#endif+ }+ if ( bmi160GyroBias.found && bmi055GyroBias.found+#ifdef SENSORS_TAKE_ACCEL_BIAS+ && bmi160AccelBias.found && bmi055AccelBias.found+#endif+ )+ {+ // soundSetEffect(SND_CALIB);+ DEBUG_PRINT("Sensor calibration [OK].\n");+ ledseqRun(&seq_calibrated);+ allSensorsAreCalibrated= true;+ }+ }+ else {+ /* get data from chosen sensors */+ sensorsGyroGet(&gyroPrim, gyroPrimInUse);+ sensorsAccelGet(&accelPrim, accelPrimInUse);+#ifdef LOG_SEC_IMU+ sensorsGyroGet(&gyroSec, gyroSecInUse);+ sensorsAccelGet(&accelSec, accelSecInUse);+#endif+ /* FIXME: for sensor deck v1 realignment has to be added her */++ switch(gyroPrimInUse) {+ case SENSORS_BMI160:+ sensorsApplyBiasAndScale(&sensors.gyro, &gyroPrim,+ &bmi160GyroBias.value,+ SENSORS_BMI160_DEG_PER_LSB_CFG);+ break;+ case SENSORS_BMI055:+ sensorsApplyBiasAndScale(&sensors.gyro, &gyroPrim,+ &bmi055GyroBias.value,+ SENSORS_BMI055_DEG_PER_LSB_CFG);+ break;+ }++ sensorsAccIIRLPFilter(&accelPrim, &accelPrimLPF,+ &accelPrimStoredFilterValues,+ (int32_t)sensorsAccLpfAttFactor);++ switch(accelPrimInUse) {+ case SENSORS_BMI160:+ sensorsApplyBiasAndScale(&accelPrimScaled, &accelPrimLPF,+ &bmi160AccelBias.value,+ SENSORS_BMI160_G_PER_LSB_CFG);+ break;+ case SENSORS_BMI055:+ sensorsApplyBiasAndScale(&accelPrimScaled, &accelPrimLPF,+ &bmi055AccelBias.value,+ SENSORS_BMI055_G_PER_LSB_CFG);+ break;+ }++ sensorsAccAlignToGravity(&accelPrimScaled, &sensors.acc);++#ifdef LOG_SEC_IMU+ switch(gyroSecInUse) {+ case SENSORS_BMI160:+ sensorsApplyBiasAndScale(&sensors.gyroSec, &gyroSec,+ &bmi160GyroBias.value,+ SENSORS_BMI160_DEG_PER_LSB_CFG);+ break;+ case SENSORS_BMI055:+ sensorsApplyBiasAndScale(&sensors.gyroSec, &gyroSec,+ &bmi055GyroBias.value,+ SENSORS_BMI055_DEG_PER_LSB_CFG);+ break;+ }++ sensorsAccIIRLPFilter(&accelSec, &accelSecLPF,+ &accelSecStoredFilterValues,+ (int32_t)sensorsAccLpfAttFactor);++ switch(accelSecInUse) {+ case SENSORS_BMI160:+ sensorsApplyBiasAndScale(&accelSecScaled, &accelSecLPF,+ &bmi160AccelBias.value,+ SENSORS_BMI160_G_PER_LSB_CFG);+ break;+ case SENSORS_BMI055:+ sensorsApplyBiasAndScale(&accelSecScaled, &accelSecLPF,+ &bmi055AccelBias.value,+ SENSORS_BMI055_G_PER_LSB_CFG);+ break;+ }++ sensorsAccAlignToGravity(&accelSecScaled, &sensors.accSec);+#endif+ }+ if (isMagnetometerPresent)+ {+ static uint8_t magMeasDelay = SENSORS_DELAY_MAG;++ if (--magMeasDelay == 0)+ {+ bmm150_read_mag_data(&bmm150Dev);+ sensors.mag.x = bmm150Dev.data.x;+ sensors.mag.y = bmm150Dev.data.y;+ sensors.mag.z = bmm150Dev.data.z;+ magMeasDelay = SENSORS_DELAY_MAG;+ }+ }++ if (isBarometerPresent)+ {+ static uint8_t baroMeasDelay = SENSORS_DELAY_BARO;+ static int32_t v_temp_s32;+ static uint32_t v_pres_u32;+ static baro_t* baro280 = &sensors.baro;++ if (--baroMeasDelay == 0)+ {+ bmp280_read_pressure_temperature(&v_pres_u32, &v_temp_s32);+ sensorsScaleBaro(baro280, (float)v_pres_u32, (float)v_temp_s32/100.0f);+ baroMeasDelay = baroMeasDelayMin;+ }+ }+ xQueueOverwrite(accelPrimDataQueue, &sensors.acc);+ xQueueOverwrite(gyroPrimDataQueue, &sensors.gyro);++#ifdef LOG_SEC_IMU+ xQueueOverwrite(gyroSecDataQueue, &sensors.gyroSec);+ xQueueOverwrite(accelSecDataQueue, &sensors.accSec);+#endif++ if (isBarometerPresent)+ {+ xQueueOverwrite(baroPrimDataQueue, &sensors.baro);+ }++ if (isMagnetometerPresent)+ {+ xQueueOverwrite(magPrimDataQueue, &sensors.mag);+ }++ xSemaphoreGive(dataReady);+ }+}++void sensorsBoschWaitDataReady(void)+{+ xSemaphoreTake(dataReady, portMAX_DELAY);+}++static void sensorsBiasMalloc(BiasObj* bias)+{+ /* allocate memory for buffer */+ bias->bufStart =+ pvPortMalloc(SENSORS_NBR_OF_BIAS_SAMPLES * sizeof(Axis3i16));+ bias->bufPtr = bias->bufStart;+ /* set ongoing bit */+ bias->ongoing = 1;+}++static void __attribute__((used)) sensorsBiasReset(BiasObj* bias)+{+ /* unset bias found and buffer full status bits */+ bias->found = 0;+ bias->bufIsFull = 0;+ /* set bufPtr to start to ensure the buffer has to be refilled+ * completly before bufferIsFull Status bit will be set */+ bias->bufPtr = bias->bufStart;+ /* clear any exisiting bias value */+ bias->value.x = 0;+ bias->value.y = 0;+ bias->value.z = 0;+ allSensorsAreCalibrated = false;+}++static void sensorsBiasFree(BiasObj* bias)+{+ /* unset buffer is full */+ bias->bufIsFull = 0;+ /* free buffer memory */+ vPortFree(bias->bufStart);+ bias->bufStart = NULL;+ bias->bufPtr = NULL;+}++/**+ * Adds a new value to the variance buffer and if it is full+ * replaces the oldest one. Thus a circular buffer.+ */+static void sensorsBiasBufPtrIncrement(BiasObj* bias)+{+ bias->bufPtr++;+ if (bias->bufPtr >= bias->bufStart+SENSORS_NBR_OF_BIAS_SAMPLES)+ {+ bias->bufPtr = bias->bufStart;+ bias->bufIsFull = 1;+ }+}++/**+ * Calculates the mean for the bias buffer.+ */+static void calcMean(BiasObj* bias, Axis3f* mean) {+ Axis3i16* elem;+ int64_t sum[GYRO_NBR_OF_AXES] = {0};++ for (elem = bias->bufStart;+ elem != (bias->bufStart+SENSORS_NBR_OF_BIAS_SAMPLES); elem++)+ {+ sum[0] += elem->x;+ sum[1] += elem->y;+ sum[2] += elem->z;+ }++ mean->x = (float)sum[0] / SENSORS_NBR_OF_BIAS_SAMPLES;+ mean->y = (float)sum[1] / SENSORS_NBR_OF_BIAS_SAMPLES;+ mean->z = (float)sum[2] / SENSORS_NBR_OF_BIAS_SAMPLES;+}++/**+ * Calculates the variance and mean for the bias buffer.+ */+static void calcVarianceAndMean(BiasObj* bias, Axis3f* variance, Axis3f* mean)+{+ Axis3i16* elem;+ int64_t sumSquared[GYRO_NBR_OF_AXES] = {0};++ for (elem = bias->bufStart;+ elem != (bias->bufStart+SENSORS_NBR_OF_BIAS_SAMPLES); elem++)+ {+ sumSquared[0] += elem->x * elem->x;+ sumSquared[1] += elem->y * elem->y;+ sumSquared[2] += elem->z * elem->z;+ }+ calcMean(bias, mean);++ variance->x = fabs(sumSquared[0] / SENSORS_NBR_OF_BIAS_SAMPLES+ - mean->x * mean->x);+ variance->y = fabs(sumSquared[1] / SENSORS_NBR_OF_BIAS_SAMPLES+ - mean->y * mean->y);+ variance->z = fabs(sumSquared[2] / SENSORS_NBR_OF_BIAS_SAMPLES+ - mean->z * mean->z);+}++/**+ * Checks if the variances is below the predefined thresholds.+ * The bias value should have been added before calling this.+ * @param bias The bias object+ */+static bool processGyroBias(BiasObj* bias)+{+ Axis3f mean, variance;+ calcVarianceAndMean(bias, &variance, &mean);++ if (variance.x < GYRO_VARIANCE_THRESHOLD_X+ && variance.y < GYRO_VARIANCE_THRESHOLD_Y+ && variance.z < GYRO_VARIANCE_THRESHOLD_Z+ && (varianceSampleTime + GYRO_MIN_BIAS_TIMEOUT_MS < xTaskGetTickCount()))+ {+ varianceSampleTime = xTaskGetTickCount();+ bias->value.x = (int16_t)(mean.x + 0.5f);+ bias->value.y = (int16_t)(mean.y + 0.5f);+ bias->value.z = (int16_t)(mean.z + 0.5f);+ bias->found = 1;+ return true;+ }+ return false;+}++static void processAccelBias(BiasObj* bias)+{+ Axis3f mean;+ calcMean(bias, &mean);++ varianceSampleTime = xTaskGetTickCount();+ bias->value.x = (int16_t)(mean.x + 0.5f);+ bias->value.y = (int16_t)(mean.y + 0.5f);+ bias->value.z = (int16_t)(mean.z + 0.5f);+ bias->found = 1;+}+static void sensorsApplyBiasAndScale(Axis3f* scaled, Axis3i16* aligned,+ Axis3i16* bias, float scale) {+ scaled->x = ((float)aligned->x - (float)bias->x) * scale;+ scaled->y = ((float)aligned->y - (float)bias->y) * scale;+ scaled->z = ((float)aligned->z - (float)bias->z) * scale;+}++static void sensorsScaleBaro(baro_t* baroScaled, float pressure,+ float temperature) {+ baroScaled->pressure = pressure*0.01f;+ baroScaled->temperature = temperature;+ baroScaled->asl = ((powf((1015.7f / baroScaled->pressure), 0.1902630958f)+ - 1.0f) * (25.0f + 273.15f)) / 0.0065f;+}++bool sensorsBoschReadGyro(Axis3f *gyro)+{+ return (pdTRUE == xQueueReceive(gyroPrimDataQueue, gyro, 0));+}++#ifdef LOG_SEC_IMU+bool sensorsReadGyroSec(Axis3f *gyro)+{+ return (pdTRUE == xQueueReceive(gyroSecDataQueue, gyro, 0));+}++bool sensorsReadAccSec(Axis3f *acc)+{+ return (pdTRUE == xQueueReceive(accelSecDataQueue, acc, 0));+}+#endif++bool sensorsBoschReadAcc(Axis3f *acc)+{+ return (pdTRUE == xQueueReceive(accelPrimDataQueue, acc, 0));+}++bool sensorsBoschReadMag(Axis3f *mag)+{+ return (pdTRUE == xQueueReceive(magPrimDataQueue, mag, 0));+}++bool sensorsBoschReadBaro(baro_t *baro)+{+ return (pdTRUE == xQueueReceive(baroPrimDataQueue, baro, 0));+}++void sensorsBoschAcquire(sensorData_t *sensors, const uint32_t tick)+{+ sensorsReadGyro(&sensors->gyro);+ sensorsReadAcc(&sensors->acc);+ sensorsReadMag(&sensors->mag);+ sensorsReadBaro(&sensors->baro);+#ifdef LOG_SEC_IMU+ sensorsReadGyroSec(&sensors->gyroSec);+ sensorsReadAccSec(&sensors->accSec);+#endif+}++bool sensorsBoschAreCalibrated()+{+ return allSensorsAreCalibrated;+}++bool sensorsBoschTest(void)+{+ bool testStatus = true;++ if (!isInit)+ {+ DEBUG_PRINT("Uninitialized\n");+ testStatus = false;+ }++ return testStatus;+}++bool sensorsBoschManufacturingTest(void)+{+ return true;+}++bool sensorsHasBarometer(void)+{+ return isBarometerPresent;+}++bool sensorsHasMangnetometer(void)+{+ return isMagnetometerPresent;+}++static void sensorsAccIIRLPFilter(Axis3i16* in, Axis3i16* out,+ Axis3i32* storedValues, int32_t attenuation)+{+ out->x = iirLPFilterSingle(in->x, attenuation, &storedValues->x);+ out->y = iirLPFilterSingle(in->y, attenuation, &storedValues->y);+ out->z = iirLPFilterSingle(in->z, attenuation, &storedValues->z);+}++/**+ * Compensate for a miss-aligned accelerometer. It uses the trim+ * data gathered from the UI and written in the config-block to+ * rotate the accelerometer to be aligned with gravity.+ */+static void sensorsAccAlignToGravity(Axis3f* in, Axis3f* out)+{+ Axis3f rx;+ Axis3f ry;++ // Rotate around x-axis+ rx.x = in->x;+ rx.y = in->y * cosRoll - in->z * sinRoll;+ rx.z = in->y * sinRoll + in->z * cosRoll;++ // Rotate around y-axis+ ry.x = rx.x * cosPitch - rx.z * sinPitch;+ ry.y = rx.y;+ ry.z = -rx.x * sinPitch + rx.z * cosPitch;++ out->x = ry.x;+ out->y = ry.y;+ out->z = ry.z;+}++void sensorsBoschSetAccMode(accModes accMode)+{+ // Difficult to switch mode so do nothing.+ switch (accMode)+ {+ case ACC_MODE_PROPTEST:+ break;+ case ACC_MODE_FLIGHT:+ default:+ break;+ }+}++PARAM_GROUP_START(imu_sensors)+PARAM_ADD(PARAM_UINT8, BoschGyrSel, &gyroPrimInUse)+PARAM_ADD(PARAM_UINT8, BoschAccSel, &accelPrimInUse)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, BMM150, &isMagnetometerPresent)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, BMP285, &isBarometerPresent)+PARAM_GROUP_STOP(imu_sensors)diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_mpu6050_hm5883L_ms5611.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_mpu6050_hm5883L_ms5611.cnew file mode 100644index 0000000..2c2f7a4--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_mpu6050_hm5883L_ms5611.c@@ -0,0 +1,1070 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2011-2018 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * Implements HAL for sensors MPU9250 and LPS25H+ *+ * 2016.06.15: Initial version by Mike Hamer, http://mikehamer.info+ */+#include <math.h>++#include "FreeRTOS.h"+#include "semphr.h"+#include "task.h"++#include "queue.h"+#include "projdefs.h"+#include "esp_timer.h"+#include "driver/gpio.h"++#include "sensors_mpu6050_hm5883L_ms5611.h"+#include "system.h"+#include "configblock.h"+#include "param.h"+#include "log.h"++#include "imu.h"+#include "nvicconf.h"+#include "ledseq.h"+#include "sound.h"+#include "filter.h"+#include "config.h"+#include "stm32_legacy.h"++#include "i2cdev.h"+// #include "lps25h.h"+#include "mpu6050.h"+#include "hmc5883l.h"+#include "ms5611.h"+// #include "ak8963.h"+#include "zranger.h"+#include "zranger2.h"+#include "vl53l1x.h"+#include "flowdeck_v1v2.h"+#define DEBUG_MODULE "SENSORS"+#include "debug_cf.h"+#include "static_mem.h"+#include "crtp_commander.h"++/**+ * Enable 250Hz digital LPF mode. However does not work with+ * multiple slave reading through MPU9250 (MAG and BARO), only single for some reason.+ */+//#define SENSORS_mpu6050_DLPF_256HZ++//#define GYRO_ADD_RAW_AND_VARIANCE_LOG_VALUES++#define MAG_GAUSS_PER_LSB 666.7f++/**+ * Enable sensors on board+ */+// #define SENSORS_ENABLE_MAG_HM5883L+// #define SENSORS_ENABLE_PRESSURE_MS5611+//#define SENSORS_ENABLE_RANGE_VL53L0X+#define SENSORS_ENABLE_RANGE_VL53L1X+#define SENSORS_ENABLE_FLOW_PMW3901++#define SENSORS_GYRO_FS_CFG MPU6050_GYRO_FS_2000+#define SENSORS_DEG_PER_LSB_CFG MPU6050_DEG_PER_LSB_2000++#define SENSORS_ACCEL_FS_CFG MPU6050_ACCEL_FS_16+#define SENSORS_G_PER_LSB_CFG MPU6050_G_PER_LSB_16++#define SENSORS_VARIANCE_MAN_TEST_TIMEOUT M2T(2000) // Timeout in ms+#define SENSORS_MAN_TEST_LEVEL_MAX 5.0f // Max degrees off++#define SENSORS_BIAS_SAMPLES 1000+#define SENSORS_ACC_SCALE_SAMPLES 200+#define SENSORS_GYRO_BIAS_CALCULATE_STDDEV++// Buffer length for MPU9250 slave reads+#define GPIO_INTA_MPU6050_IO CONFIG_MPU_PIN_INT+#define SENSORS_MPU6050_BUFF_LEN 14+#define SENSORS_MAG_BUFF_LEN 8+#define SENSORS_BARO_BUFF_S_P_LEN MS5611_D1D2_SIZE+#define SENSORS_BARO_BUFF_T_LEN MS5611_D1D2_SIZE+#define SENSORS_BARO_BUFF_LEN (SENSORS_BARO_BUFF_S_P_LEN + SENSORS_BARO_BUFF_T_LEN)++#define GYRO_NBR_OF_AXES 3+#define GYRO_MIN_BIAS_TIMEOUT_MS M2T(1 * 1000)+// Number of samples used in variance calculation. Changing this effects the threshold+#define SENSORS_NBR_OF_BIAS_SAMPLES 1024+// Variance threshold to take zero bias for gyro+#define GYRO_VARIANCE_BASE 5000+#define GYRO_VARIANCE_THRESHOLD_X (GYRO_VARIANCE_BASE)+#define GYRO_VARIANCE_THRESHOLD_Y (GYRO_VARIANCE_BASE)+#define GYRO_VARIANCE_THRESHOLD_Z (GYRO_VARIANCE_BASE)+#define ESP_INTR_FLAG_DEFAULT 0++#define PITCH_CALIB (CONFIG_PITCH_CALIB*1.0/100)+#define ROLL_CALIB (CONFIG_ROLL_CALIB*1.0/100)++typedef struct {+ Axis3f bias;+ Axis3f variance;+ Axis3f mean;+ bool isBiasValueFound;+ bool isBufferFilled;+ Axis3i16 *bufHead;+ Axis3i16 buffer[SENSORS_NBR_OF_BIAS_SAMPLES];+} BiasObj;++static xQueueHandle accelerometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(accelerometerDataQueue, 1, sizeof(Axis3f));+static xQueueHandle gyroDataQueue;+STATIC_MEM_QUEUE_ALLOC(gyroDataQueue, 1, sizeof(Axis3f));+static xQueueHandle magnetometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(magnetometerDataQueue, 1, sizeof(Axis3f));+static xQueueHandle barometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(barometerDataQueue, 1, sizeof(baro_t));++static xSemaphoreHandle sensorsDataReady;+static xSemaphoreHandle dataReady;++static bool isInit = false;+static sensorData_t sensorData;+static volatile uint64_t imuIntTimestamp;++static Axis3i16 gyroRaw;+static Axis3i16 accelRaw;+static BiasObj gyroBiasRunning;+static Axis3f gyroBias;+#if defined(SENSORS_GYRO_BIAS_CALCULATE_STDDEV) && defined(GYRO_BIAS_LIGHT_WEIGHT)+static Axis3f gyroBiasStdDev;+#endif+static bool gyroBiasFound = false;+static float accScaleSum = 0;+static float accScale = 1;++// Low Pass filtering+#define GYRO_LPF_CUTOFF_FREQ 80+#define ACCEL_LPF_CUTOFF_FREQ 30+static lpf2pData accLpf[3];+static lpf2pData gyroLpf[3];+static void applyAxis3fLpf(lpf2pData *data, Axis3f *in);++static bool isBarometerPresent = false;+static bool isMagnetometerPresent = false;+#ifdef SENSORS_ENABLE_RANGE_VL53L1X+static bool isVl53l1xPresent = false;+#endif+#ifdef SENSORS_ENABLE_RANGE_VL53L0X+static bool isVl53l0xPresent = false;+#endif+#ifdef SENSORS_ENABLE_FLOW_PMW3901+static bool isPmw3901Present = false;+#endif+static bool isMpu6050TestPassed = false;+#ifdef SENSORS_ENABLE_MAG_HM5883L+static bool isHmc5883lTestPassed = false;+#endif+#ifdef SENSORS_ENABLE_PRESSURE_MS5611+static bool isMs5611TestPassed = false;+#endif++// Pre-calculated values for accelerometer alignment+float cosPitch;+float sinPitch;+float cosRoll;+float sinRoll;++// This buffer needs to hold data from all sensors+static uint8_t buffer[SENSORS_MPU6050_BUFF_LEN + SENSORS_MAG_BUFF_LEN + SENSORS_BARO_BUFF_LEN] = {0};++static void processAccGyroMeasurements(const uint8_t *buffer);+static void processMagnetometerMeasurements(const uint8_t *buffer);+static void processBarometerMeasurements(const uint8_t *buffer);+static void sensorsSetupSlaveRead(void);++#ifdef GYRO_GYRO_BIAS_LIGHT_WEIGHT+static bool processGyroBiasNoBuffer(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut);+#else+static bool processGyroBias(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut);+#endif+static bool processAccScale(int16_t ax, int16_t ay, int16_t az);+static void sensorsBiasObjInit(BiasObj *bias);+static void sensorsCalculateVarianceAndMean(BiasObj *bias, Axis3f *varOut, Axis3f *meanOut);+static void sensorsCalculateBiasMean(BiasObj *bias, Axis3i32 *meanOut);+static void sensorsAddBiasValue(BiasObj *bias, int16_t x, int16_t y, int16_t z);+static bool sensorsFindBiasValue(BiasObj *bias);+static void sensorsAccAlignToGravity(Axis3f *in, Axis3f *out);++STATIC_MEM_TASK_ALLOC(sensorsTask, SENSORS_TASK_STACKSIZE);+bool sensorsMpu6050Hmc5883lMs5611ReadGyro(Axis3f *gyro)+{+ return (pdTRUE == xQueueReceive(gyroDataQueue, gyro, 0));+}++bool sensorsMpu6050Hmc5883lMs5611ReadAcc(Axis3f *acc)+{+ return (pdTRUE == xQueueReceive(accelerometerDataQueue, acc, 0));+}++bool sensorsMpu6050Hmc5883lMs5611ReadMag(Axis3f *mag)+{+ return (pdTRUE == xQueueReceive(magnetometerDataQueue, mag, 0));+}++bool sensorsMpu6050Hmc5883lMs5611ReadBaro(baro_t *baro)+{+ return (pdTRUE == xQueueReceive(barometerDataQueue, baro, 0));+}++void sensorsMpu6050Hmc5883lMs5611Acquire(sensorData_t *sensors, const uint32_t tick)+{+ sensorsReadGyro(&sensors->gyro);+ sensorsReadAcc(&sensors->acc);+ sensorsReadMag(&sensors->mag);+ sensorsReadBaro(&sensors->baro);+ sensors->interruptTimestamp = sensorData.interruptTimestamp;+}++bool sensorsMpu6050Hmc5883lMs5611AreCalibrated()+{+ return gyroBiasFound;+}++static void sensorsTask(void *param)+{+ //TODO:+ systemWaitStart();+ vTaskDelay(M2T(200));+ DEBUG_PRINTD("xTaskCreate sensorsTask IN");+ sensorsSetupSlaveRead(); //+ DEBUG_PRINTD("xTaskCreate sensorsTask SetupSlave done");++ while (1) {++ /* mpu6050 interrupt trigger: data is ready to be read */+ if (pdTRUE == xSemaphoreTake(sensorsDataReady, portMAX_DELAY)) {+ sensorData.interruptTimestamp = imuIntTimestamp;++ /* sensors step 1-read data from I2C */+ uint8_t dataLen = (uint8_t)(SENSORS_MPU6050_BUFF_LEN ++ (isMagnetometerPresent ? SENSORS_MAG_BUFF_LEN : 0) ++ (isBarometerPresent ? SENSORS_BARO_BUFF_LEN : 0));+ i2cdevReadReg8(I2C0_DEV, MPU6050_ADDRESS_AD0_LOW, MPU6050_RA_ACCEL_XOUT_H, dataLen, buffer);++ /* sensors step 2-process the respective data */+ processAccGyroMeasurements(&(buffer[0]));++ if (isMagnetometerPresent) {+ processMagnetometerMeasurements(&(buffer[SENSORS_MPU6050_BUFF_LEN]));+ }++ if (isBarometerPresent) {+ processBarometerMeasurements(&(buffer[isMagnetometerPresent ? SENSORS_MPU6050_BUFF_LEN + SENSORS_MAG_BUFF_LEN : SENSORS_MPU6050_BUFF_LEN]));+ }++ /* sensors step 3- queue sensors data on the output queues */+ xQueueOverwrite(accelerometerDataQueue, &sensorData.acc);+ xQueueOverwrite(gyroDataQueue, &sensorData.gyro);++ if (isMagnetometerPresent) {+ xQueueOverwrite(magnetometerDataQueue, &sensorData.mag);+ }++ if (isBarometerPresent) {+ xQueueOverwrite(barometerDataQueue, &sensorData.baro);+ }++ /* sensors step 4- Unlock stabilizer task */+ xSemaphoreGive(dataReady);+#ifdef DEBUG_EP2+ DEBUG_PRINT_LOCAL("ax = %f, ay = %f, az = %f, gx = %f, gy = %f, gz = %f , hx = %f , hy = %f, hz =%f \n", sensorData.acc.x, sensorData.acc.y, sensorData.acc.z, sensorData.gyro.x, sensorData.gyro.y, sensorData.gyro.z, sensorData.mag.x, sensorData.mag.y, sensorData.mag.z);+#endif+ }+ }+}++void sensorsMpu6050Hmc5883lMs5611WaitDataReady(void)+{+ xSemaphoreTake(dataReady, portMAX_DELAY);+}++void processBarometerMeasurements(const uint8_t *buffer)+{+ //TODO: replace it to MS5611+ DEBUG_PRINTW("processBarometerMeasurements NEED TODO");+// static uint32_t rawPressure = 0;+// static int16_t rawTemp = 0;++// Check if there is a new pressure update++// Check if there is a new temp update++// sensorData.baro.pressure = (float) rawPressure / LPS25H_LSB_PER_MBAR;+// sensorData.baro.temperature = LPS25H_TEMP_OFFSET + ((float) rawTemp / LPS25H_LSB_PER_CELSIUS);+// sensorData.baro.asl = lps25hPressureToAltitude(&sensorData.baro.pressure);+}++void processMagnetometerMeasurements(const uint8_t *buffer)+{+ //TODO: replace it to hmc5883l+ if (buffer[7] & (1 << HMC5883L_STATUS_READY_BIT)) {+ int16_t headingx = (((int16_t)buffer[2]) << 8) | buffer[1]; //hmc5883 different from+ int16_t headingz = (((int16_t)buffer[4]) << 8) | buffer[3];+ int16_t headingy = (((int16_t)buffer[6]) << 8) | buffer[5];++ sensorData.mag.x = (float)headingx / MAG_GAUSS_PER_LSB; //to gauss+ sensorData.mag.y = (float)headingy / MAG_GAUSS_PER_LSB;+ sensorData.mag.z = (float)headingz / MAG_GAUSS_PER_LSB;+ DEBUG_PRINTI("hmc5883l DATA ready");+ } else {++ DEBUG_PRINTW("hmc5883l DATA not ready");+ }+}++void processAccGyroMeasurements(const uint8_t *buffer)+{+ /* Note the ordering to correct the rotated 90º IMU coordinate system */++ Axis3f accScaled;++#ifdef CONFIG_TARGET_ESPLANE_V1+ /* sensors step 2.1 read from buffer */+ /*+ accelRaw.x = (((int16_t)buffer[0]) << 8) | buffer[1];+ accelRaw.y = (((int16_t)buffer[2]) << 8) | buffer[3];+ accelRaw.z = (((int16_t)buffer[4]) << 8) | buffer[5];+ gyroRaw.x = (((int16_t)buffer[8]) << 8) | buffer[9];+ gyroRaw.y = (((int16_t)buffer[10]) << 8) | buffer[11];+ gyroRaw.z = (((int16_t)buffer[12]) << 8) | buffer[13];+ */+ accelRaw.y = (((int16_t)buffer[0]) << 8) | buffer[1];+ accelRaw.x = (((int16_t)buffer[2]) << 8) | buffer[3];+ accelRaw.z = (((int16_t)buffer[4]) << 8) | buffer[5];+ gyroRaw.y = (((int16_t)buffer[8]) << 8) | buffer[9];+ gyroRaw.x = (((int16_t)buffer[10]) << 8) | buffer[11];+ gyroRaw.z = (((int16_t)buffer[12]) << 8) | buffer[13];+#else+ /* sensors step 2.1 read from buffer */+ accelRaw.y = (((int16_t)buffer[0]) << 8) | buffer[1];+ accelRaw.x = (((int16_t)buffer[2]) << 8) | buffer[3];+ accelRaw.z = (((int16_t)buffer[4]) << 8) | buffer[5];+ gyroRaw.y = (((int16_t)buffer[8]) << 8) | buffer[9];+ gyroRaw.x = (((int16_t)buffer[10]) << 8) | buffer[11];+ gyroRaw.z = (((int16_t)buffer[12]) << 8) | buffer[13];+#endif++#ifdef GYRO_BIAS_LIGHT_WEIGHT+ gyroBiasFound = processGyroBiasNoBuffer(gyroRaw.x, gyroRaw.y, gyroRaw.z, &gyroBias);+#else+ /* sensors step 2.2 Calculates the gyro bias first when the variance is below threshold */+ gyroBiasFound = processGyroBias(gyroRaw.x, gyroRaw.y, gyroRaw.z, &gyroBias);+#endif++ /*sensors step 2.3 Calculates the acc scale when platform is steady */+ if (gyroBiasFound) {+ processAccScale(accelRaw.x, accelRaw.y, accelRaw.z);+ }++ /* sensors step 2.4 convert digtal value to physical angle */+#ifdef CONFIG_TARGET_ESPLANE_V1+ //sensorData.gyro.x = (gyroRaw.x - gyroBias.x) * SENSORS_DEG_PER_LSB_CFG;+ sensorData.gyro.x = -(gyroRaw.x - gyroBias.x) * SENSORS_DEG_PER_LSB_CFG;+#else+ sensorData.gyro.x = -(gyroRaw.x - gyroBias.x) * SENSORS_DEG_PER_LSB_CFG;+#endif++ sensorData.gyro.y = (gyroRaw.y - gyroBias.y) * SENSORS_DEG_PER_LSB_CFG;+ sensorData.gyro.z = (gyroRaw.z - gyroBias.z) * SENSORS_DEG_PER_LSB_CFG;+ /* sensors step 2.5 low pass filter */+ applyAxis3fLpf((lpf2pData *)(&gyroLpf), &sensorData.gyro);++#ifdef CONFIG_TARGET_ESPLANE_V1+ //accScaled.x = (accelRaw.x) * SENSORS_G_PER_LSB_CFG / accScale;+ accScaled.x = -(accelRaw.x) * SENSORS_G_PER_LSB_CFG / accScale;+#else+ accScaled.x = -(accelRaw.x) * SENSORS_G_PER_LSB_CFG / accScale;+#endif++ accScaled.y = (accelRaw.y) * SENSORS_G_PER_LSB_CFG / accScale;+ accScaled.z = (accelRaw.z) * SENSORS_G_PER_LSB_CFG / accScale;++ /* sensors step 2.6 Compensate for a miss-aligned accelerometer. */+ sensorsAccAlignToGravity(&accScaled, &sensorData.acc);+ applyAxis3fLpf((lpf2pData *)(&accLpf), &sensorData.acc);+}+static void sensorsDeviceInit(void)+{+ isMagnetometerPresent = false;+ isBarometerPresent = false;++ // Wait for sensors to startup+ while (xTaskGetTickCount() < 2000){+ vTaskDelay(M2T(50));+ };++ i2cdevInit(I2C0_DEV);+ mpu6050Init(I2C0_DEV);++ if (mpu6050TestConnection() == true) {+ DEBUG_PRINTI("MPU6050 I2C connection [OK].\n");+ } else {+ DEBUG_PRINTE("MPU6050 I2C connection [FAIL].\n");+ // Please check your hardware !+ assert(0);+ }++ mpu6050Reset();+ vTaskDelay(M2T(50));+ // Activate mpu6050+ mpu6050SetSleepEnabled(false);+ // Delay until registers are reset+ vTaskDelay(M2T(100));+ // Set x-axis gyro as clock source+ mpu6050SetClockSource(MPU6050_CLOCK_PLL_XGYRO);+ // Delay until clock is set and stable+ vTaskDelay(M2T(200));+ // Enable temp sensor+ mpu6050SetTempSensorEnabled(true);+ // Disable interrupts+ mpu6050SetIntEnabled(false);+ // Connect the MAG and BARO to the main I2C bus+ mpu6050SetI2CBypassEnabled(true);+ // Set gyro full scale range+ mpu6050SetFullScaleGyroRange(SENSORS_GYRO_FS_CFG);+ // Set accelerometer full scale range+ mpu6050SetFullScaleAccelRange(SENSORS_ACCEL_FS_CFG);++ // Set digital low-pass bandwidth for gyro and acc+ // board ESP32_S2_DRONE_V1_2 has more vibrations, bandwidth should be lower+#ifdef SENSORS_MPU6050_DLPF_256HZ+ // 256Hz digital low-pass filter only works with little vibrations+ // Set output rate (15): 8000 / (1 + 7) = 1000Hz+ mpu6050SetRate(7);+ // Set digital low-pass bandwidth+ mpu6050SetDLPFMode(MPU6050_DLPF_BW_256);+#elif defined(CONFIG_TARGET_ESP32_S2_DRONE_V1_2)+ // To low DLPF bandwidth might cause instability and decrease agility+ // but it works well for handling vibrations and unbalanced propellers+ // Set output rate (1): 1000 / (1 + 0) = 1000Hz+ mpu6050SetRate(0);+ mpu6050SetDLPFMode(MPU6050_DLPF_BW_42);+ // Init second order filer for accelerometer+ for (uint8_t i = 0; i < 3; i++) {+ lpf2pInit(&gyroLpf[i], 1000, GYRO_LPF_CUTOFF_FREQ);+ lpf2pInit(&accLpf[i], 1000, ACCEL_LPF_CUTOFF_FREQ);+ }+#else+ mpu6050SetRate(0);+ mpu6050SetDLPFMode(MPU6050_DLPF_BW_98);+ // Init second order filer for accelerometer+ for (uint8_t i = 0; i < 3; i++) {+ lpf2pInit(&gyroLpf[i], 1000, GYRO_LPF_CUTOFF_FREQ);+ lpf2pInit(&accLpf[i], 1000, ACCEL_LPF_CUTOFF_FREQ);+ }+#endif++#ifdef SENSORS_ENABLE_MAG_HM5883L+ hmc5883lInit(I2C0_DEV);++ if (hmc5883lTestConnection() == true) {+ isMagnetometerPresent = true;+ hmc5883lSetMode(HMC5883L_MODE_CONTINUOUS); // 16bit 100Hz+ DEBUG_PRINTI("hmc5883l I2C connection [OK].\n");+ } else {+ DEBUG_PRINTW("hmc5883l I2C connection [FAIL].\n");+ }++#endif+#ifdef SENSORS_ENABLE_PRESSURE_MS5611+ ms5611Init(I2C0_DEV);++ if (false) {+ isBarometerPresent = true;+ DEBUG_PRINTI("MS5611 I2C connection [OK].\n");+ } else {+ //TODO: Should sensor test fail hard if no connection+ DEBUG_PRINTW("MS5611 I2C connection [FAIL].\n");+ }++#endif++#ifdef SENSORS_ENABLE_RANGE_VL53L1X+ zRanger2Init();++ if (zRanger2Test() == true) {+ isVl53l1xPresent = true;+ DEBUG_PRINTI("VL53L1X I2C connection [OK].\n");+ } else {+ //TODO: Should sensor test fail hard if no connection+ DEBUG_PRINTW("VL53L1X I2C connection [FAIL].\n");+ }++#endif++#ifdef SENSORS_ENABLE_RANGE_VL53L0X+ zRangerInit();++ if (zRangerTest() == true) {+ isVl53l0xPresent = true;+ DEBUG_PRINTI("VL53L0X I2C connection [OK].\n");+ } else {+ //TODO: Should sensor test fail hard if no connection+ DEBUG_PRINTW("VL53L0X I2C connection [FAIL].\n");+ }++#endif++#ifdef SENSORS_ENABLE_FLOW_PMW3901+ flowdeck2Init();++ if (flowdeck2Test() == true) {+ isPmw3901Present = true;+ setCommandermode(POSHOLD_MODE);+ DEBUG_PRINTI("PMW3901 SPI connection [OK].\n");+ } else {+ //TODO: Should sensor test fail hard if no connection+ DEBUG_PRINTW("PMW3901 SPI connection [FAIL].\n");+ }+#endif++ DEBUG_PRINTI("sensors init done");+ /*+ *get calib angle from NVS+ */+ // cosPitch = cosf(configblockGetCalibPitch() * (float)M_PI / 180);+ // sinPitch = sinf(configblockGetCalibPitch() * (float)M_PI / 180);+ // cosRoll = cosf(configblockGetCalibRoll() * (float)M_PI / 180);+ // sinRoll = sinf(configblockGetCalibRoll() * (float)M_PI / 180);+ cosPitch = cosf(PITCH_CALIB * (float)M_PI / 180);+ sinPitch = sinf(PITCH_CALIB * (float)M_PI / 180);+ cosRoll = cosf(ROLL_CALIB * (float)M_PI / 180);+ sinRoll = sinf(ROLL_CALIB * (float)M_PI / 180);+ DEBUG_PRINTI("pitch_calib = %f,roll_calib = %f",PITCH_CALIB,ROLL_CALIB);+}++static void sensorsSetupSlaveRead(void)+{+ // Now begin to set up the slaves+#ifdef SENSORS_MPU6050_DLPF_256HZ+ // As noted in registersheet 4.4: "Data should be sampled at or above sample rate;+ // SMPLRT_DIV is only used for 1kHz internal sampling." Slowest update rate is then 500Hz.+ mpu6050SetSlave4MasterDelay(15); // read slaves at 500Hz = (8000Hz / (1 + 15))+#else+ mpu6050SetSlave4MasterDelay(9); // read slaves at 100Hz = (500Hz / (1 + 4))+#endif++ mpu6050SetI2CBypassEnabled(false);+ mpu6050SetWaitForExternalSensorEnabled(true); // the slave data isn't so important for the state estimation+ mpu6050SetInterruptMode(0); // active high+ mpu6050SetInterruptDrive(0); // push pull+ mpu6050SetInterruptLatch(0); // latched until clear+ mpu6050SetInterruptLatchClear(1); // cleared on any register read+ mpu6050SetSlaveReadWriteTransitionEnabled(false); // Send a stop at the end of a slave read+ mpu6050SetMasterClockSpeed(13); // Set i2c speed to 400kHz++#ifdef SENSORS_ENABLE_MAG_HM5883L++ if (isMagnetometerPresent) {+ // Set registers for mpu6050 master to read from+ mpu6050SetSlaveAddress(0, 0x80 | HMC5883L_ADDRESS); // set the magnetometer to Slave 0, enable read+ mpu6050SetSlaveRegister(0, HMC5883L_RA_MODE); // read the magnetometer heading register+ mpu6050SetSlaveDataLength(0, SENSORS_MAG_BUFF_LEN); // hmc5883l:model,x,z,y,status ak8963:read 8 bytes (ST1, x, y, z heading, ST2 (overflow check))+ mpu6050SetSlaveDelayEnabled(0, true);+ mpu6050SetSlaveEnabled(0, true);+ DEBUG_PRINTD("mpu6050SetSlaveAddress HMC5883L done \n");+ }++#endif++#ifdef SENSORS_ENABLE_PRESSURE_MS5611++ if (isBarometerPresent) {+ // Configure the LPS25H as a slave and enable read+ // Setting up two reads works for LPS25H fifo avg filter as well as the+ // auto inc wraps back to LPS25H_PRESS_OUT_L after LPS25H_PRESS_OUT_H is read.+ mpu6050SetSlaveAddress(1, 0x80 | MS5611_ADDR_CSB_LOW);+ mpu6050SetSlaveRegister(1, MS5611_D1);+ mpu6050SetSlaveDataLength(1, MS5611_D1D2_SIZE);+ mpu6050SetSlaveDelayEnabled(1, true);+ mpu6050SetSlaveEnabled(1, true);++ mpu6050SetSlaveAddress(2, 0x80 | MS5611_ADDR_CSB_LOW); //temperature+ mpu6050SetSlaveRegister(2, MS5611_D2);+ mpu6050SetSlaveDataLength(2, MS5611_D1D2_SIZE);+ mpu6050SetSlaveDelayEnabled(2, true);+ mpu6050SetSlaveEnabled(2, true);+ DEBUG_PRINTD("mpu6050SetSlaveAddress MS5611 done \n");+ }++#endif++ // Enable sensors after configuration+ mpu6050SetI2CMasterModeEnabled(true);++ mpu6050SetIntDataReadyEnabled(true);++ DEBUG_PRINTD("sensorsSetupSlaveRead done \n");+}++static void sensorsTaskInit(void)+{+ accelerometerDataQueue = STATIC_MEM_QUEUE_CREATE(accelerometerDataQueue);+ gyroDataQueue = STATIC_MEM_QUEUE_CREATE(gyroDataQueue);+ magnetometerDataQueue = STATIC_MEM_QUEUE_CREATE(magnetometerDataQueue);+ barometerDataQueue = STATIC_MEM_QUEUE_CREATE(barometerDataQueue);++ STATIC_MEM_TASK_CREATE(sensorsTask, sensorsTask, SENSORS_TASK_NAME, NULL, SENSORS_TASK_PRI);+ DEBUG_PRINTD("xTaskCreate sensorsTask \n");+}++static void IRAM_ATTR sensors_inta_isr_handler(void *arg)+{+ portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;+ imuIntTimestamp = usecTimestamp(); //This function returns the number of microseconds since esp_timer was initialized+ xSemaphoreGiveFromISR(sensorsDataReady, &xHigherPriorityTaskWoken);++ if (xHigherPriorityTaskWoken) {+ portYIELD_FROM_ISR();+ }+}++static void sensorsInterruptInit(void)+{++ DEBUG_PRINTD("sensorsInterruptInit \n");+ gpio_config_t io_conf = {+ //interrupt of rising edge+#if ESP_IDF_VERSION_MAJOR > 4+ .intr_type = GPIO_INTR_POSEDGE,+#else+ .intr_type = GPIO_PIN_INTR_POSEDGE,+#endif+ //bit mask of the pins+ .pin_bit_mask = (1ULL << GPIO_INTA_MPU6050_IO),+ //set as input mode+ .mode = GPIO_MODE_INPUT,+ //disable pull-down mode+ .pull_down_en = 0,+ //enable pull-up mode+ .pull_up_en = 1,+ };+ sensorsDataReady = xSemaphoreCreateBinary();+ dataReady = xSemaphoreCreateBinary();+ gpio_config(&io_conf);+ //install gpio isr service+ //portDISABLE_INTERRUPTS();+ gpio_set_intr_type(GPIO_INTA_MPU6050_IO, GPIO_INTR_POSEDGE);+ gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT);+ //hook isr handler for specific gpio pin+ gpio_isr_handler_add(GPIO_INTA_MPU6050_IO, sensors_inta_isr_handler, (void *)GPIO_INTA_MPU6050_IO);+ //portENABLE_INTERRUPTS();+ DEBUG_PRINTD("sensorsInterruptInit done \n");++ // FSYNC "shall not be floating, must be set high or low by the MCU"++}++void sensorsMpu6050Hmc5883lMs5611Init(void)+{+ if (isInit) {+ return;+ }++ sensorsBiasObjInit(&gyroBiasRunning);+ sensorsDeviceInit();+ sensorsInterruptInit();+ sensorsTaskInit();+ isInit = true;+}++bool sensorsMpu6050Hmc5883lMs5611Test(void)+{++ bool testStatus = true;++ if (!isInit) {+ DEBUG_PRINTE("Error while initializing sensor task\r\n");+ testStatus = false;+ }++ // Try for 3 seconds so the quad has stabilized enough to pass the test+ for (int i = 0; i < 300; i++) {+ if (mpu6050SelfTest() == true) {+ isMpu6050TestPassed = true;+ break;+ } else {+ vTaskDelay(M2T(10));+ }+ }++ testStatus &= isMpu6050TestPassed;++#ifdef SENSORS_ENABLE_MAG_HM5883L+ testStatus &= isMagnetometerPresent;++ if (testStatus) {+ isHmc5883lTestPassed = hmc5883lSelfTest();+ testStatus &= isHmc5883lTestPassed;+ }++#endif++#ifdef SENSORS_ENABLE_PRESSURE_MS5611+ testStatus &= isBarometerPresent;++ if (testStatus) {+ isMs5611TestPassed = ms5611SelfTest();++ testStatus &= isMs5611TestPassed;+ }++#endif++ return testStatus;++}++/**+ * Calculates accelerometer scale out of SENSORS_ACC_SCALE_SAMPLES samples. Should be called when+ * platform is stable.+ */+static bool processAccScale(int16_t ax, int16_t ay, int16_t az)+{+ static bool accBiasFound = false;+ static uint32_t accScaleSumCount = 0;++ if (!accBiasFound) {+ accScaleSum += sqrtf(powf(ax * SENSORS_G_PER_LSB_CFG, 2) + powf(ay * SENSORS_G_PER_LSB_CFG, 2) + powf(az * SENSORS_G_PER_LSB_CFG, 2));+ accScaleSumCount++;++ if (accScaleSumCount == SENSORS_ACC_SCALE_SAMPLES) {+ accScale = accScaleSum / SENSORS_ACC_SCALE_SAMPLES;+ accBiasFound = true;+ }+ }++ return accBiasFound;+}++#ifdef GYRO_BIAS_LIGHT_WEIGHT+/**+ * Calculates the bias out of the first SENSORS_BIAS_SAMPLES gathered. Requires no buffer+ * but needs platform to be stable during startup.+ */+static bool processGyroBiasNoBuffer(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut)+{+ static uint32_t gyroBiasSampleCount = 0;+ static bool gyroBiasNoBuffFound = false;+ static Axis3i64 gyroBiasSampleSum;+ static Axis3i64 gyroBiasSampleSumSquares;++ if (!gyroBiasNoBuffFound) {+ // If the gyro has not yet been calibrated:+ // Add the current sample to the running mean and variance+ gyroBiasSampleSum.x += gx;+ gyroBiasSampleSum.y += gy;+ gyroBiasSampleSum.z += gz;+#ifdef SENSORS_GYRO_BIAS_CALCULATE_STDDEV+ gyroBiasSampleSumSquares.x += gx * gx;+ gyroBiasSampleSumSquares.y += gy * gy;+ gyroBiasSampleSumSquares.z += gz * gz;+#endif+ gyroBiasSampleCount += 1;++ // If we then have enough samples, calculate the mean and standard deviation+ if (gyroBiasSampleCount == SENSORS_BIAS_SAMPLES) {+ gyroBiasOut->x = (float)(gyroBiasSampleSum.x) / SENSORS_BIAS_SAMPLES;+ gyroBiasOut->y = (float)(gyroBiasSampleSum.y) / SENSORS_BIAS_SAMPLES;+ gyroBiasOut->z = (float)(gyroBiasSampleSum.z) / SENSORS_BIAS_SAMPLES;++#ifdef SENSORS_GYRO_BIAS_CALCULATE_STDDEV+ gyroBiasStdDev.x = sqrtf((float)(gyroBiasSampleSumSquares.x) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->x * gyroBiasOut->x));+ gyroBiasStdDev.y = sqrtf((float)(gyroBiasSampleSumSquares.y) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->y * gyroBiasOut->y));+ gyroBiasStdDev.z = sqrtf((float)(gyroBiasSampleSumSquares.z) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->z * gyroBiasOut->z));+#endif+ gyroBiasNoBuffFound = true;+ }+ }++ return gyroBiasNoBuffFound;+}+#else+/**+ * Calculates the bias first when the gyro variance is below threshold. Requires a buffer+ * but calibrates platform first when it is stable.+ */+static bool processGyroBias(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut)+{+ sensorsAddBiasValue(&gyroBiasRunning, gx, gy, gz);++ if (!gyroBiasRunning.isBiasValueFound) {+ sensorsFindBiasValue(&gyroBiasRunning);++ if (gyroBiasRunning.isBiasValueFound) {+ //TODO:+ soundSetEffect(SND_CALIB);+ ledseqRun(&seq_calibrated);+ DEBUG_PRINTI("isBiasValueFound!");+ }+ }++ gyroBiasOut->x = gyroBiasRunning.bias.x;+ gyroBiasOut->y = gyroBiasRunning.bias.y;+ gyroBiasOut->z = gyroBiasRunning.bias.z;++ return gyroBiasRunning.isBiasValueFound;+}+#endif++static void sensorsBiasObjInit(BiasObj *bias)+{+ bias->isBufferFilled = false;+ bias->bufHead = bias->buffer;+}++/**+ * Calculates the variance and mean for the bias buffer.+ */+static void sensorsCalculateVarianceAndMean(BiasObj *bias, Axis3f *varOut, Axis3f *meanOut)+{+ uint32_t i;+ int64_t sum[GYRO_NBR_OF_AXES] = {0};+ int64_t sumSq[GYRO_NBR_OF_AXES] = {0};++ for (i = 0; i < SENSORS_NBR_OF_BIAS_SAMPLES; i++) {+ sum[0] += bias->buffer[i].x;+ sum[1] += bias->buffer[i].y;+ sum[2] += bias->buffer[i].z;+ sumSq[0] += bias->buffer[i].x * bias->buffer[i].x;+ sumSq[1] += bias->buffer[i].y * bias->buffer[i].y;+ sumSq[2] += bias->buffer[i].z * bias->buffer[i].z;+ }++ varOut->x = (sumSq[0] - ((int64_t)sum[0] * sum[0]) / SENSORS_NBR_OF_BIAS_SAMPLES);+ varOut->y = (sumSq[1] - ((int64_t)sum[1] * sum[1]) / SENSORS_NBR_OF_BIAS_SAMPLES);+ varOut->z = (sumSq[2] - ((int64_t)sum[2] * sum[2]) / SENSORS_NBR_OF_BIAS_SAMPLES);++ meanOut->x = (float)sum[0] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->y = (float)sum[1] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->z = (float)sum[2] / SENSORS_NBR_OF_BIAS_SAMPLES;+}++/**+ * Calculates the mean for the bias buffer.+ */+static void __attribute__((used)) sensorsCalculateBiasMean(BiasObj *bias, Axis3i32 *meanOut)+{+ uint32_t i;+ int32_t sum[GYRO_NBR_OF_AXES] = {0};++ for (i = 0; i < SENSORS_NBR_OF_BIAS_SAMPLES; i++) {+ sum[0] += bias->buffer[i].x;+ sum[1] += bias->buffer[i].y;+ sum[2] += bias->buffer[i].z;+ }++ meanOut->x = sum[0] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->y = sum[1] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->z = sum[2] / SENSORS_NBR_OF_BIAS_SAMPLES;+}++/**+ * Adds a new value to the variance buffer and if it is full+ * replaces the oldest one. Thus a circular buffer.+ */+static void sensorsAddBiasValue(BiasObj *bias, int16_t x, int16_t y, int16_t z)+{+ bias->bufHead->x = x;+ bias->bufHead->y = y;+ bias->bufHead->z = z;+ bias->bufHead++;++ if (bias->bufHead >= &bias->buffer[SENSORS_NBR_OF_BIAS_SAMPLES]) {+ bias->bufHead = bias->buffer;+ bias->isBufferFilled = true;+ }+}++/**+ * Checks if the variances is below the predefined thresholds.+ * The bias value should have been added before calling this.+ * @param bias The bias object+ */+static bool sensorsFindBiasValue(BiasObj *bias)+{+ static int32_t varianceSampleTime;+ bool foundBias = false;++ if (bias->isBufferFilled) {+ sensorsCalculateVarianceAndMean(bias, &bias->variance, &bias->mean);++ if (bias->variance.x < GYRO_VARIANCE_THRESHOLD_X &&+ bias->variance.y < GYRO_VARIANCE_THRESHOLD_Y &&+ bias->variance.z < GYRO_VARIANCE_THRESHOLD_Z &&+ (varianceSampleTime + GYRO_MIN_BIAS_TIMEOUT_MS < xTaskGetTickCount())) {+ varianceSampleTime = xTaskGetTickCount();+ bias->bias.x = bias->mean.x;+ bias->bias.y = bias->mean.y;+ bias->bias.z = bias->mean.z;+ foundBias = true;+ bias->isBiasValueFound = true;+ }+ }++ return foundBias;+}++bool sensorsMpu6050Hmc5883lMs5611ManufacturingTest(void)+{+ bool testStatus = false;+ Axis3i16 g;+ Axis3i16 a;+ Axis3f acc; // Accelerometer axis data in mG+ float pitch, roll;+ uint32_t startTick = xTaskGetTickCount();++ testStatus = mpu6050SelfTest();++ if (testStatus) {+ sensorsBiasObjInit(&gyroBiasRunning);++ while (xTaskGetTickCount() - startTick < SENSORS_VARIANCE_MAN_TEST_TIMEOUT) {+ mpu6050GetMotion6(&a.y, &a.x, &a.z, &g.y, &g.x, &g.z);++ if (processGyroBias(g.x, g.y, g.z, &gyroBias)) {+ gyroBiasFound = true;+ DEBUG_PRINTI("Gyro variance test [OK]\n");+ break;+ }+ }++ if (gyroBiasFound) {+ acc.x = (a.x) * SENSORS_G_PER_LSB_CFG;+ acc.y = (a.y) * SENSORS_G_PER_LSB_CFG;+ acc.z = (a.z) * SENSORS_G_PER_LSB_CFG;++ // Calculate pitch and roll based on accelerometer. Board must be level+ pitch = tanf(-acc.x / (sqrtf(acc.y * acc.y + acc.z * acc.z))) * 180 / (float)M_PI;+ roll = tanf(acc.y / acc.z) * 180 / (float)M_PI;++ if ((fabsf(roll) < SENSORS_MAN_TEST_LEVEL_MAX) && (fabsf(pitch) < SENSORS_MAN_TEST_LEVEL_MAX)) {+ DEBUG_PRINTI("Acc level test [OK]\n");+ testStatus = true;+ } else {+ DEBUG_PRINTE("Acc level test Roll:%0.2f, Pitch:%0.2f [FAIL]\n", (double)roll, (double)pitch);+ testStatus = false;+ }+ } else {+ DEBUG_PRINTE("Gyro variance test [FAIL]\n");+ testStatus = false;+ }+ }++ return testStatus;+}++/**+ * Compensate for a miss-aligned accelerometer. It uses the trim+ * data gathered from the UI and written in the config-block to+ * rotate the accelerometer to be aligned with gravity.+ */+static void sensorsAccAlignToGravity(Axis3f *in, Axis3f *out)+{+ Axis3f rx;+ Axis3f ry;++ // Rotate around x-axis+ rx.x = in->x;+ rx.y = in->y * cosRoll - in->z * sinRoll;+ rx.z = in->y * sinRoll + in->z * cosRoll;++ // Rotate around y-axis+ ry.x = rx.x * cosPitch - rx.z * sinPitch;+ ry.y = rx.y;+ ry.z = -rx.x * sinPitch + rx.z * cosPitch;++ out->x = ry.x;+ out->y = ry.y;+ out->z = ry.z;+}++/** set different low pass filters in different environment+ *+ *+ */+void sensorsMpu6050Hmc5883lMs5611SetAccMode(accModes accMode)+{+ switch (accMode)+ {+ case ACC_MODE_PROPTEST:+ mpu6050SetRate(7);+ mpu6050SetDLPFMode(MPU6050_DLPF_BW_256);+ for (uint8_t i = 0; i < 3; i++)+ {+ lpf2pInit(&accLpf[i], 1000, 250);+ }+ break;+ case ACC_MODE_FLIGHT:+ default:+ mpu6050SetRate(0);+#ifdef CONFIG_TARGET_ESP32_S2_DRONE_V1_2+ mpu6050SetDLPFMode(MPU6050_DLPF_BW_42);+ for (uint8_t i = 0; i < 3; i++) {+ lpf2pInit(&accLpf[i], 1000, ACCEL_LPF_CUTOFF_FREQ);+ }+#else+ mpu6050SetDLPFMode(MPU6050_DLPF_BW_98);+ for (uint8_t i = 0; i < 3; i++) {+ lpf2pInit(&accLpf[i], 1000, ACCEL_LPF_CUTOFF_FREQ);+ }+#endif+ break;+ }+}++static void applyAxis3fLpf(lpf2pData *data, Axis3f *in)+{+ for (uint8_t i = 0; i < 3; i++) {+ in->axis[i] = lpf2pApply(&data[i], in->axis[i]);+ }+}++#ifdef GYRO_ADD_RAW_AND_VARIANCE_LOG_VALUES+LOG_GROUP_START(gyro)+LOG_ADD(LOG_INT16, xRaw, &gyroRaw.x)+LOG_ADD(LOG_INT16, yRaw, &gyroRaw.y)+LOG_ADD(LOG_INT16, zRaw, &gyroRaw.z)+LOG_ADD(LOG_FLOAT, xVariance, &gyroBiasRunning.variance.x)+LOG_ADD(LOG_FLOAT, yVariance, &gyroBiasRunning.variance.y)+LOG_ADD(LOG_FLOAT, zVariance, &gyroBiasRunning.variance.z)+LOG_GROUP_STOP(gyro)+#endif++//TODO:+PARAM_GROUP_START(imu_sensors)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, HMC5883L, &isMagnetometerPresent)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, MS5611, &isBarometerPresent) // TODO: Rename MS5611 to LPS25H. Client needs to be updated at the same time.+PARAM_GROUP_STOP(imu_sensors)++PARAM_GROUP_START(imu_tests)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, mpu6050, &isMpu6050TestPassed)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, HMC5883L, &isMagnetometerPresent)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, pmw3901, &isPmw3901Present)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, MS5611, &isBarometerPresent) // TODO: Rename MS5611 to LPS25H. Client needs to be updated at the same time.+PARAM_GROUP_STOP(imu_tests)diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_mpu9250_lps25h.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_mpu9250_lps25h.cnew file mode 100644index 0000000..7293bea--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/sensors_mpu9250_lps25h.c@@ -0,0 +1,934 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2018 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * Implements HAL for sensors MPU9250 and LPS25H+ *+ * 2016.06.15: Initial version by Mike Hamer, http://mikehamer.info+ */++#include "sensors_mpu9250_lps25h.h"++#include <math.h>+#include <stm32f4xx.h>++#include "lps25h.h"+#include "mpu6500.h"+#include "ak8963.h"++#include "FreeRTOS.h"+#include "semphr.h"+#include "task.h"++#include "system.h"+#include "configblock.h"+#include "param.h"+#include "log.h"+#include "debug.h"+#include "imu.h"+#include "nvicconf.h"+#include "ledseq.h"+#include "sound.h"+#include "filter.h"+#include "static_mem.h"++/**+ * Enable 250Hz digital LPF mode. However does not work with+ * multiple slave reading through MPU9250 (MAG and BARO), only single for some reason.+ */+//#define SENSORS_MPU6500_DLPF_256HZ++#define SENSORS_ENABLE_PRESSURE_LPS25H+//#define GYRO_ADD_RAW_AND_VARIANCE_LOG_VALUES++#define SENSORS_ENABLE_MAG_AK8963+#define MAG_GAUSS_PER_LSB 666.7f++#define SENSORS_GYRO_FS_CFG MPU6500_GYRO_FS_2000+#define SENSORS_DEG_PER_LSB_CFG MPU6500_DEG_PER_LSB_2000++#define SENSORS_ACCEL_FS_CFG MPU6500_ACCEL_FS_16+#define SENSORS_G_PER_LSB_CFG MPU6500_G_PER_LSB_16++#define SENSORS_VARIANCE_MAN_TEST_TIMEOUT M2T(2000) // Timeout in ms+#define SENSORS_MAN_TEST_LEVEL_MAX 5.0f // Max degrees off++#define SENSORS_BIAS_SAMPLES 1000+#define SENSORS_ACC_SCALE_SAMPLES 200+#define SENSORS_GYRO_BIAS_CALCULATE_STDDEV++// Buffer length for MPU9250 slave reads+#define SENSORS_MPU6500_BUFF_LEN 14+#define SENSORS_MAG_BUFF_LEN 8+#define SENSORS_BARO_BUFF_S_P_LEN 4+#define SENSORS_BARO_BUFF_T_LEN 2+#define SENSORS_BARO_BUFF_LEN (SENSORS_BARO_BUFF_S_P_LEN + SENSORS_BARO_BUFF_T_LEN)++#define GYRO_NBR_OF_AXES 3+#define GYRO_MIN_BIAS_TIMEOUT_MS M2T(1*1000)+// Number of samples used in variance calculation. Changing this effects the threshold+#define SENSORS_NBR_OF_BIAS_SAMPLES 1024+// Variance threshold to take zero bias for gyro+#define GYRO_VARIANCE_BASE 5000+#define GYRO_VARIANCE_THRESHOLD_X (GYRO_VARIANCE_BASE)+#define GYRO_VARIANCE_THRESHOLD_Y (GYRO_VARIANCE_BASE)+#define GYRO_VARIANCE_THRESHOLD_Z (GYRO_VARIANCE_BASE)++typedef struct+{+ Axis3f bias;+ Axis3f variance;+ Axis3f mean;+ bool isBiasValueFound;+ bool isBufferFilled;+ Axis3i16* bufHead;+ Axis3i16 buffer[SENSORS_NBR_OF_BIAS_SAMPLES];+} BiasObj;++static xQueueHandle accelerometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(accelerometerDataQueue, 1, sizeof(Axis3f));+static xQueueHandle gyroDataQueue;+STATIC_MEM_QUEUE_ALLOC(gyroDataQueue, 1, sizeof(Axis3f));+static xQueueHandle magnetometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(magnetometerDataQueue, 1, sizeof(Axis3f));+static xQueueHandle barometerDataQueue;+STATIC_MEM_QUEUE_ALLOC(barometerDataQueue, 1, sizeof(baro_t));++static xSemaphoreHandle sensorsDataReady;+static StaticSemaphore_t sensorsDataReadyBuffer;+static xSemaphoreHandle dataReady;+static StaticSemaphore_t dataReadyBuffer;++static bool isInit = false;+static sensorData_t sensorData;+static volatile uint64_t imuIntTimestamp;++static Axis3i16 gyroRaw;+static Axis3i16 accelRaw;+NO_DMA_CCM_SAFE_ZERO_INIT static BiasObj gyroBiasRunning;+static Axis3f gyroBias;+#if defined(SENSORS_GYRO_BIAS_CALCULATE_STDDEV) && defined (GYRO_BIAS_LIGHT_WEIGHT)+static Axis3f gyroBiasStdDev;+#endif+static bool gyroBiasFound = false;+static float accScaleSum = 0;+static float accScale = 1;++// Low Pass filtering+#define GYRO_LPF_CUTOFF_FREQ 80+#define ACCEL_LPF_CUTOFF_FREQ 30+static lpf2pData accLpf[3];+static lpf2pData gyroLpf[3];+static void applyAxis3fLpf(lpf2pData *data, Axis3f* in);++static bool isBarometerPresent = false;+static bool isMagnetometerPresent = false;++static bool isMpu6500TestPassed = false;+static bool isAK8963TestPassed = false;+static bool isLPS25HTestPassed = false;++// Pre-calculated values for accelerometer alignment+static float cosPitch;+static float sinPitch;+static float cosRoll;+static float sinRoll;++// This buffer needs to hold data from all sensors+static uint8_t buffer[SENSORS_MPU6500_BUFF_LEN + SENSORS_MAG_BUFF_LEN + SENSORS_BARO_BUFF_LEN] = {0};++static void processAccGyroMeasurements(const uint8_t *buffer);+static void processMagnetometerMeasurements(const uint8_t *buffer);+static void processBarometerMeasurements(const uint8_t *buffer);+static void sensorsSetupSlaveRead(void);++#ifdef GYRO_GYRO_BIAS_LIGHT_WEIGHT+static bool processGyroBiasNoBuffer(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut);+#else+static bool processGyroBias(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut);+#endif+static bool processAccScale(int16_t ax, int16_t ay, int16_t az);+static void sensorsBiasObjInit(BiasObj* bias);+static void sensorsCalculateVarianceAndMean(BiasObj* bias, Axis3f* varOut, Axis3f* meanOut);+static void sensorsCalculateBiasMean(BiasObj* bias, Axis3i32* meanOut);+static void sensorsAddBiasValue(BiasObj* bias, int16_t x, int16_t y, int16_t z);+static bool sensorsFindBiasValue(BiasObj* bias);+static void sensorsAccAlignToGravity(Axis3f* in, Axis3f* out);++STATIC_MEM_TASK_ALLOC(sensorsTask, SENSORS_TASK_STACKSIZE);++bool sensorsMpu9250Lps25hReadGyro(Axis3f *gyro)+{+ return (pdTRUE == xQueueReceive(gyroDataQueue, gyro, 0));+}++bool sensorsMpu9250Lps25hReadAcc(Axis3f *acc)+{+ return (pdTRUE == xQueueReceive(accelerometerDataQueue, acc, 0));+}++bool sensorsMpu9250Lps25hReadMag(Axis3f *mag)+{+ return (pdTRUE == xQueueReceive(magnetometerDataQueue, mag, 0));+}++bool sensorsMpu9250Lps25hReadBaro(baro_t *baro)+{+ return (pdTRUE == xQueueReceive(barometerDataQueue, baro, 0));+}++void sensorsMpu9250Lps25hAcquire(sensorData_t *sensors, const uint32_t tick)+{+ sensorsReadGyro(&sensors->gyro);+ sensorsReadAcc(&sensors->acc);+ sensorsReadMag(&sensors->mag);+ sensorsReadBaro(&sensors->baro);+ sensors->interruptTimestamp = sensorData.interruptTimestamp;+}++bool sensorsMpu9250Lps25hAreCalibrated() {+ return gyroBiasFound;+}++static void sensorsTask(void *param)+{+ systemWaitStart();++ sensorsSetupSlaveRead();++ while (1)+ {+ if (pdTRUE == xSemaphoreTake(sensorsDataReady, portMAX_DELAY))+ {+ sensorData.interruptTimestamp = imuIntTimestamp;+ // data is ready to be read+ uint8_t dataLen = (uint8_t) (SENSORS_MPU6500_BUFF_LEN ++ (isMagnetometerPresent ? SENSORS_MAG_BUFF_LEN : 0) ++ (isBarometerPresent ? SENSORS_BARO_BUFF_LEN : 0));++ i2cdevReadReg8(I2C3_DEV, MPU6500_ADDRESS_AD0_HIGH, MPU6500_RA_ACCEL_XOUT_H, dataLen, buffer);+ // these functions process the respective data and queue it on the output queues+ processAccGyroMeasurements(&(buffer[0]));+ if (isMagnetometerPresent)+ {+ processMagnetometerMeasurements(&(buffer[SENSORS_MPU6500_BUFF_LEN]));+ }+ if (isBarometerPresent)+ {+ processBarometerMeasurements(&(buffer[isMagnetometerPresent ?+ SENSORS_MPU6500_BUFF_LEN + SENSORS_MAG_BUFF_LEN : SENSORS_MPU6500_BUFF_LEN]));+ }++ xQueueOverwrite(accelerometerDataQueue, &sensorData.acc);+ xQueueOverwrite(gyroDataQueue, &sensorData.gyro);+ if (isMagnetometerPresent)+ {+ xQueueOverwrite(magnetometerDataQueue, &sensorData.mag);+ }+ if (isBarometerPresent)+ {+ xQueueOverwrite(barometerDataQueue, &sensorData.baro);+ }++ // Unlock stabilizer task+ xSemaphoreGive(dataReady);+ }+ }+}++void sensorsMpu9250Lps25hWaitDataReady(void)+{+ xSemaphoreTake(dataReady, portMAX_DELAY);+}++void processBarometerMeasurements(const uint8_t *buffer)+{+ static uint32_t rawPressure = 0;+ static int16_t rawTemp = 0;++ // Check if there is a new pressure update+ if (buffer[0] & 0x02) {+ rawPressure = ((uint32_t) buffer[3] << 16) | ((uint32_t) buffer[2] << 8) | buffer[1];+ }+ // Check if there is a new temp update+ if (buffer[0] & 0x01) {+ rawTemp = ((int16_t) buffer[5] << 8) | buffer[4];+ }++ sensorData.baro.pressure = (float) rawPressure / LPS25H_LSB_PER_MBAR;+ sensorData.baro.temperature = LPS25H_TEMP_OFFSET + ((float) rawTemp / LPS25H_LSB_PER_CELSIUS);+ sensorData.baro.asl = lps25hPressureToAltitude(&sensorData.baro.pressure);+}++void processMagnetometerMeasurements(const uint8_t *buffer)+{+ if (buffer[0] & (1 << AK8963_ST1_DRDY_BIT)) {+ int16_t headingx = (((int16_t) buffer[2]) << 8) | buffer[1];+ int16_t headingy = (((int16_t) buffer[4]) << 8) | buffer[3];+ int16_t headingz = (((int16_t) buffer[6]) << 8) | buffer[5];++ sensorData.mag.x = (float)headingx / MAG_GAUSS_PER_LSB;+ sensorData.mag.y = (float)headingy / MAG_GAUSS_PER_LSB;+ sensorData.mag.z = (float)headingz / MAG_GAUSS_PER_LSB;+ }+}++void processAccGyroMeasurements(const uint8_t *buffer)+{+ Axis3f accScaled;+ // Note the ordering to correct the rotated 90º IMU coordinate system+ accelRaw.y = (((int16_t) buffer[0]) << 8) | buffer[1];+ accelRaw.x = (((int16_t) buffer[2]) << 8) | buffer[3];+ accelRaw.z = (((int16_t) buffer[4]) << 8) | buffer[5];+ gyroRaw.y = (((int16_t) buffer[8]) << 8) | buffer[9];+ gyroRaw.x = (((int16_t) buffer[10]) << 8) | buffer[11];+ gyroRaw.z = (((int16_t) buffer[12]) << 8) | buffer[13];+++#ifdef GYRO_BIAS_LIGHT_WEIGHT+ gyroBiasFound = processGyroBiasNoBuffer(gyroRaw.x, gyroRaw.y, gyroRaw.z, &gyroBias);+#else+ gyroBiasFound = processGyroBias(gyroRaw.x, gyroRaw.y, gyroRaw.z, &gyroBias);+#endif+ if (gyroBiasFound)+ {+ processAccScale(accelRaw.x, accelRaw.y, accelRaw.z);+ }++ sensorData.gyro.x = -(gyroRaw.x - gyroBias.x) * SENSORS_DEG_PER_LSB_CFG;+ sensorData.gyro.y = (gyroRaw.y - gyroBias.y) * SENSORS_DEG_PER_LSB_CFG;+ sensorData.gyro.z = (gyroRaw.z - gyroBias.z) * SENSORS_DEG_PER_LSB_CFG;+ applyAxis3fLpf((lpf2pData*)(&gyroLpf), &sensorData.gyro);++ accScaled.x = -(accelRaw.x) * SENSORS_G_PER_LSB_CFG / accScale;+ accScaled.y = (accelRaw.y) * SENSORS_G_PER_LSB_CFG / accScale;+ accScaled.z = (accelRaw.z) * SENSORS_G_PER_LSB_CFG / accScale;+ sensorsAccAlignToGravity(&accScaled, &sensorData.acc);+ applyAxis3fLpf((lpf2pData*)(&accLpf), &sensorData.acc);+}++static void sensorsDeviceInit(void)+{+ isMagnetometerPresent = false;+ isBarometerPresent = false;++ // Wait for sensors to startup+ while (xTaskGetTickCount() < 1000);++ i2cdevInit(I2C3_DEV);+ mpu6500Init(I2C3_DEV);+ if (mpu6500TestConnection() == true)+ {+ DEBUG_PRINT("MPU9250 I2C connection [OK].\n");+ }+ else+ {+ DEBUG_PRINT("MPU9250 I2C connection [FAIL].\n");+ }++ mpu6500Reset();+ vTaskDelay(M2T(50));+ // Activate MPU6500+ mpu6500SetSleepEnabled(false);+ // Delay until registers are reset+ vTaskDelay(M2T(100));+ // Set x-axis gyro as clock source+ mpu6500SetClockSource(MPU6500_CLOCK_PLL_XGYRO);+ // Delay until clock is set and stable+ vTaskDelay(M2T(200));+ // Enable temp sensor+ mpu6500SetTempSensorEnabled(true);+ // Disable interrupts+ mpu6500SetIntEnabled(false);+ // Connect the MAG and BARO to the main I2C bus+ mpu6500SetI2CBypassEnabled(true);+ // Set gyro full scale range+ mpu6500SetFullScaleGyroRange(SENSORS_GYRO_FS_CFG);+ // Set accelerometer full scale range+ mpu6500SetFullScaleAccelRange(SENSORS_ACCEL_FS_CFG);+ // Set accelerometer digital low-pass bandwidth+ mpu6500SetAccelDLPF(MPU6500_ACCEL_DLPF_BW_41);++#if SENSORS_MPU6500_DLPF_256HZ+ // 256Hz digital low-pass filter only works with little vibrations+ // Set output rate (15): 8000 / (1 + 7) = 1000Hz+ mpu6500SetRate(7);+ // Set digital low-pass bandwidth+ mpu6500SetDLPFMode(MPU6500_DLPF_BW_256);+#else+ // To low DLPF bandwidth might cause instability and decrease agility+ // but it works well for handling vibrations and unbalanced propellers+ // Set output rate (1): 1000 / (1 + 0) = 1000Hz+ mpu6500SetRate(0);+ // Set digital low-pass bandwidth for gyro+ mpu6500SetDLPFMode(MPU6500_DLPF_BW_98);+ // Init second order filer for accelerometer+ for (uint8_t i = 0; i < 3; i++)+ {+ lpf2pInit(&gyroLpf[i], 1000, GYRO_LPF_CUTOFF_FREQ);+ lpf2pInit(&accLpf[i], 1000, ACCEL_LPF_CUTOFF_FREQ);+ }+#endif+++#ifdef SENSORS_ENABLE_MAG_AK8963+ ak8963Init(I2C3_DEV);+ if (ak8963TestConnection() == true)+ {+ isMagnetometerPresent = true;+ ak8963SetMode(AK8963_MODE_16BIT | AK8963_MODE_CONT2); // 16bit 100Hz+ DEBUG_PRINT("AK8963 I2C connection [OK].\n");+ }+ else+ {+ DEBUG_PRINT("AK8963 I2C connection [FAIL].\n");+ }+#endif++#ifdef SENSORS_ENABLE_PRESSURE_LPS25H+ lps25hInit(I2C3_DEV);+ if (lps25hTestConnection() == true)+ {+ lps25hSetEnabled(true);+ isBarometerPresent = true;+ DEBUG_PRINT("LPS25H I2C connection [OK].\n");+ }+ else+ {+ //TODO: Should sensor test fail hard if no connection+ DEBUG_PRINT("LPS25H I2C connection [FAIL].\n");+ }+#endif++ cosPitch = cosf(configblockGetCalibPitch() * (float) M_PI/180);+ sinPitch = sinf(configblockGetCalibPitch() * (float) M_PI/180);+ cosRoll = cosf(configblockGetCalibRoll() * (float) M_PI/180);+ sinRoll = sinf(configblockGetCalibRoll() * (float) M_PI/180);+}+++static void sensorsSetupSlaveRead(void)+{+ // Now begin to set up the slaves+#ifdef SENSORS_MPU6500_DLPF_256HZ+ // As noted in registersheet 4.4: "Data should be sampled at or above sample rate;+ // SMPLRT_DIV is only used for 1kHz internal sampling." Slowest update rate is then 500Hz.+ mpu6500SetSlave4MasterDelay(15); // read slaves at 500Hz = (8000Hz / (1 + 15))+#else+ mpu6500SetSlave4MasterDelay(9); // read slaves at 100Hz = (500Hz / (1 + 4))+#endif++ mpu6500SetI2CBypassEnabled(false);+ mpu6500SetWaitForExternalSensorEnabled(true); // the slave data isn't so important for the state estimation+ mpu6500SetInterruptMode(0); // active high+ mpu6500SetInterruptDrive(0); // push pull+ mpu6500SetInterruptLatch(0); // latched until clear+ mpu6500SetInterruptLatchClear(1); // cleared on any register read+ mpu6500SetSlaveReadWriteTransitionEnabled(false); // Send a stop at the end of a slave read+ mpu6500SetMasterClockSpeed(13); // Set i2c speed to 400kHz++#ifdef SENSORS_ENABLE_MAG_AK8963+ if (isMagnetometerPresent)+ {+ // Set registers for MPU6500 master to read from+ mpu6500SetSlaveAddress(0, 0x80 | AK8963_ADDRESS_00); // set the magnetometer to Slave 0, enable read+ mpu6500SetSlaveRegister(0, AK8963_RA_ST1); // read the magnetometer heading register+ mpu6500SetSlaveDataLength(0, SENSORS_MAG_BUFF_LEN); // read 8 bytes (ST1, x, y, z heading, ST2 (overflow check))+ mpu6500SetSlaveDelayEnabled(0, true);+ mpu6500SetSlaveEnabled(0, true);+ }+#endif++#ifdef SENSORS_ENABLE_PRESSURE_LPS25H+ if (isBarometerPresent)+ {+ // Configure the LPS25H as a slave and enable read+ // Setting up two reads works for LPS25H fifo avg filter as well as the+ // auto inc wraps back to LPS25H_PRESS_OUT_L after LPS25H_PRESS_OUT_H is read.+ mpu6500SetSlaveAddress(1, 0x80 | LPS25H_I2C_ADDR);+ mpu6500SetSlaveRegister(1, LPS25H_STATUS_REG | LPS25H_ADDR_AUTO_INC);+ mpu6500SetSlaveDataLength(1, SENSORS_BARO_BUFF_S_P_LEN);+ mpu6500SetSlaveDelayEnabled(1, true);+ mpu6500SetSlaveEnabled(1, true);++ mpu6500SetSlaveAddress(2, 0x80 | LPS25H_I2C_ADDR);+ mpu6500SetSlaveRegister(2, LPS25H_TEMP_OUT_L | LPS25H_ADDR_AUTO_INC);+ mpu6500SetSlaveDataLength(2, SENSORS_BARO_BUFF_T_LEN);+ mpu6500SetSlaveDelayEnabled(2, true);+ mpu6500SetSlaveEnabled(2, true);+ }+#endif++ // Enable sensors after configuration+ mpu6500SetI2CMasterModeEnabled(true);++ mpu6500SetIntDataReadyEnabled(true);+}++static void sensorsTaskInit(void)+{+ accelerometerDataQueue = STATIC_MEM_QUEUE_CREATE(accelerometerDataQueue);+ gyroDataQueue = STATIC_MEM_QUEUE_CREATE(gyroDataQueue);+ magnetometerDataQueue = STATIC_MEM_QUEUE_CREATE(magnetometerDataQueue);+ barometerDataQueue = STATIC_MEM_QUEUE_CREATE(barometerDataQueue);++ STATIC_MEM_TASK_CREATE(sensorsTask, sensorsTask, SENSORS_TASK_NAME, NULL, SENSORS_TASK_PRI);+}++static void sensorsInterruptInit(void)+{+ GPIO_InitTypeDef GPIO_InitStructure;+ EXTI_InitTypeDef EXTI_InitStructure;++ sensorsDataReady = xSemaphoreCreateBinaryStatic(&sensorsDataReadyBuffer);+ dataReady = xSemaphoreCreateBinaryStatic(&dataReadyBuffer);++ // FSYNC "shall not be floating, must be set high or low by the MCU"+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;+ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;+ GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;+ GPIO_Init(GPIOC, &GPIO_InitStructure);+ GPIO_ResetBits(GPIOC, GPIO_Pin_14);++ // Enable the MPU6500 interrupt on PC13+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;+ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;+ GPIO_Init(GPIOC, &GPIO_InitStructure);++ SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC, EXTI_PinSource13);++ EXTI_InitStructure.EXTI_Line = EXTI_Line13;+ EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;+ EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;+ EXTI_InitStructure.EXTI_LineCmd = ENABLE;+ portDISABLE_INTERRUPTS();+ EXTI_Init(&EXTI_InitStructure);+ EXTI_ClearITPendingBit(EXTI_Line13);+ portENABLE_INTERRUPTS();+}++void sensorsMpu9250Lps25hInit(void)+{+ if (isInit)+ {+ return;+ }++ sensorsBiasObjInit(&gyroBiasRunning);+ sensorsDeviceInit();+ sensorsInterruptInit();+ sensorsTaskInit();++ isInit = true;+}++bool sensorsMpu9250Lps25hTest(void)+{+ bool testStatus = true;++ if (!isInit)+ {+ DEBUG_PRINT("Error while initializing sensor task\r\n");+ testStatus = false;+ }++ // Try for 3 seconds so the quad has stabilized enough to pass the test+ for (int i = 0; i < 300; i++)+ {+ if(mpu6500SelfTest() == true)+ {+ isMpu6500TestPassed = true;+ break;+ }+ else+ {+ vTaskDelay(M2T(10));+ }+ }+ testStatus &= isMpu6500TestPassed;++#ifdef SENSORS_ENABLE_MAG_AK8963+ testStatus &= isMagnetometerPresent;+ if (testStatus)+ {+ isAK8963TestPassed = ak8963SelfTest();+ testStatus = isAK8963TestPassed;+ }+#endif++#ifdef SENSORS_ENABLE_PRESSURE_LPS25H+ testStatus &= isBarometerPresent;+ if (testStatus)+ {+ isLPS25HTestPassed = lps25hSelfTest();+ testStatus = isLPS25HTestPassed;+ }+#endif++ return testStatus;+}++/**+ * Calculates accelerometer scale out of SENSORS_ACC_SCALE_SAMPLES samples. Should be called when+ * platform is stable.+ */+static bool processAccScale(int16_t ax, int16_t ay, int16_t az)+{+ static bool accBiasFound = false;+ static uint32_t accScaleSumCount = 0;++ if (!accBiasFound)+ {+ accScaleSum += sqrtf(powf(ax * SENSORS_G_PER_LSB_CFG, 2) + powf(ay * SENSORS_G_PER_LSB_CFG, 2) + powf(az * SENSORS_G_PER_LSB_CFG, 2));+ accScaleSumCount++;++ if (accScaleSumCount == SENSORS_ACC_SCALE_SAMPLES)+ {+ accScale = accScaleSum / SENSORS_ACC_SCALE_SAMPLES;+ accBiasFound = true;+ }+ }++ return accBiasFound;+}++#ifdef GYRO_BIAS_LIGHT_WEIGHT+/**+ * Calculates the bias out of the first SENSORS_BIAS_SAMPLES gathered. Requires no buffer+ * but needs platform to be stable during startup.+ */+static bool processGyroBiasNoBuffer(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut)+{+ static uint32_t gyroBiasSampleCount = 0;+ static bool gyroBiasNoBuffFound = false;+ static Axis3i64 gyroBiasSampleSum;+ static Axis3i64 gyroBiasSampleSumSquares;++ if (!gyroBiasNoBuffFound)+ {+ // If the gyro has not yet been calibrated:+ // Add the current sample to the running mean and variance+ gyroBiasSampleSum.x += gx;+ gyroBiasSampleSum.y += gy;+ gyroBiasSampleSum.z += gz;+#ifdef SENSORS_GYRO_BIAS_CALCULATE_STDDEV+ gyroBiasSampleSumSquares.x += gx * gx;+ gyroBiasSampleSumSquares.y += gy * gy;+ gyroBiasSampleSumSquares.z += gz * gz;+#endif+ gyroBiasSampleCount += 1;++ // If we then have enough samples, calculate the mean and standard deviation+ if (gyroBiasSampleCount == SENSORS_BIAS_SAMPLES)+ {+ gyroBiasOut->x = (float)(gyroBiasSampleSum.x) / SENSORS_BIAS_SAMPLES;+ gyroBiasOut->y = (float)(gyroBiasSampleSum.y) / SENSORS_BIAS_SAMPLES;+ gyroBiasOut->z = (float)(gyroBiasSampleSum.z) / SENSORS_BIAS_SAMPLES;++#ifdef SENSORS_GYRO_BIAS_CALCULATE_STDDEV+ gyroBiasStdDev.x = sqrtf((float)(gyroBiasSampleSumSquares.x) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->x * gyroBiasOut->x));+ gyroBiasStdDev.y = sqrtf((float)(gyroBiasSampleSumSquares.y) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->y * gyroBiasOut->y));+ gyroBiasStdDev.z = sqrtf((float)(gyroBiasSampleSumSquares.z) / SENSORS_BIAS_SAMPLES - (gyroBiasOut->z * gyroBiasOut->z));+#endif+ gyroBiasNoBuffFound = true;+ }+ }++ return gyroBiasNoBuffFound;+}+#else+/**+ * Calculates the bias first when the gyro variance is below threshold. Requires a buffer+ * but calibrates platform first when it is stable.+ */+static bool processGyroBias(int16_t gx, int16_t gy, int16_t gz, Axis3f *gyroBiasOut)+{+ sensorsAddBiasValue(&gyroBiasRunning, gx, gy, gz);++ if (!gyroBiasRunning.isBiasValueFound)+ {+ sensorsFindBiasValue(&gyroBiasRunning);+ if (gyroBiasRunning.isBiasValueFound)+ {+ soundSetEffect(SND_CALIB);+ ledseqRun(&seq_calibrated);+ }+ }++ gyroBiasOut->x = gyroBiasRunning.bias.x;+ gyroBiasOut->y = gyroBiasRunning.bias.y;+ gyroBiasOut->z = gyroBiasRunning.bias.z;++ return gyroBiasRunning.isBiasValueFound;+}+#endif++static void sensorsBiasObjInit(BiasObj* bias)+{+ bias->isBufferFilled = false;+ bias->bufHead = bias->buffer;+}++/**+ * Calculates the variance and mean for the bias buffer.+ */+static void sensorsCalculateVarianceAndMean(BiasObj* bias, Axis3f* varOut, Axis3f* meanOut)+{+ uint32_t i;+ int64_t sum[GYRO_NBR_OF_AXES] = {0};+ int64_t sumSq[GYRO_NBR_OF_AXES] = {0};++ for (i = 0; i < SENSORS_NBR_OF_BIAS_SAMPLES; i++)+ {+ sum[0] += bias->buffer[i].x;+ sum[1] += bias->buffer[i].y;+ sum[2] += bias->buffer[i].z;+ sumSq[0] += bias->buffer[i].x * bias->buffer[i].x;+ sumSq[1] += bias->buffer[i].y * bias->buffer[i].y;+ sumSq[2] += bias->buffer[i].z * bias->buffer[i].z;+ }++ varOut->x = (sumSq[0] - ((int64_t)sum[0] * sum[0]) / SENSORS_NBR_OF_BIAS_SAMPLES);+ varOut->y = (sumSq[1] - ((int64_t)sum[1] * sum[1]) / SENSORS_NBR_OF_BIAS_SAMPLES);+ varOut->z = (sumSq[2] - ((int64_t)sum[2] * sum[2]) / SENSORS_NBR_OF_BIAS_SAMPLES);++ meanOut->x = (float)sum[0] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->y = (float)sum[1] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->z = (float)sum[2] / SENSORS_NBR_OF_BIAS_SAMPLES;+}++/**+ * Calculates the mean for the bias buffer.+ */+static void __attribute__((used)) sensorsCalculateBiasMean(BiasObj* bias, Axis3i32* meanOut)+{+ uint32_t i;+ int32_t sum[GYRO_NBR_OF_AXES] = {0};++ for (i = 0; i < SENSORS_NBR_OF_BIAS_SAMPLES; i++)+ {+ sum[0] += bias->buffer[i].x;+ sum[1] += bias->buffer[i].y;+ sum[2] += bias->buffer[i].z;+ }++ meanOut->x = sum[0] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->y = sum[1] / SENSORS_NBR_OF_BIAS_SAMPLES;+ meanOut->z = sum[2] / SENSORS_NBR_OF_BIAS_SAMPLES;+}++/**+ * Adds a new value to the variance buffer and if it is full+ * replaces the oldest one. Thus a circular buffer.+ */+static void sensorsAddBiasValue(BiasObj* bias, int16_t x, int16_t y, int16_t z)+{+ bias->bufHead->x = x;+ bias->bufHead->y = y;+ bias->bufHead->z = z;+ bias->bufHead++;++ if (bias->bufHead >= &bias->buffer[SENSORS_NBR_OF_BIAS_SAMPLES])+ {+ bias->bufHead = bias->buffer;+ bias->isBufferFilled = true;+ }+}++/**+ * Checks if the variances is below the predefined thresholds.+ * The bias value should have been added before calling this.+ * @param bias The bias object+ */+static bool sensorsFindBiasValue(BiasObj* bias)+{+ static int32_t varianceSampleTime;+ bool foundBias = false;++ if (bias->isBufferFilled)+ {+ sensorsCalculateVarianceAndMean(bias, &bias->variance, &bias->mean);++ if (bias->variance.x < GYRO_VARIANCE_THRESHOLD_X &&+ bias->variance.y < GYRO_VARIANCE_THRESHOLD_Y &&+ bias->variance.z < GYRO_VARIANCE_THRESHOLD_Z &&+ (varianceSampleTime + GYRO_MIN_BIAS_TIMEOUT_MS < xTaskGetTickCount()))+ {+ varianceSampleTime = xTaskGetTickCount();+ bias->bias.x = bias->mean.x;+ bias->bias.y = bias->mean.y;+ bias->bias.z = bias->mean.z;+ foundBias = true;+ bias->isBiasValueFound = true;+ }+ }++ return foundBias;+}++bool sensorsMpu9250Lps25hManufacturingTest(void)+{+ bool testStatus = false;+ Axis3i16 g;+ Axis3i16 a;+ Axis3f acc; // Accelerometer axis data in mG+ float pitch, roll;+ uint32_t startTick = xTaskGetTickCount();++ testStatus = mpu6500SelfTest();++ if (testStatus)+ {+ sensorsBiasObjInit(&gyroBiasRunning);+ while (xTaskGetTickCount() - startTick < SENSORS_VARIANCE_MAN_TEST_TIMEOUT)+ {+ mpu6500GetMotion6(&a.y, &a.x, &a.z, &g.y, &g.x, &g.z);++ if (processGyroBias(g.x, g.y, g.z, &gyroBias))+ {+ gyroBiasFound = true;+ DEBUG_PRINT("Gyro variance test [OK]\n");+ break;+ }+ }++ if (gyroBiasFound)+ {+ acc.x = -(a.x) * SENSORS_G_PER_LSB_CFG;+ acc.y = (a.y) * SENSORS_G_PER_LSB_CFG;+ acc.z = (a.z) * SENSORS_G_PER_LSB_CFG;++ // Calculate pitch and roll based on accelerometer. Board must be level+ pitch = tanf(-acc.x/(sqrtf(acc.y*acc.y + acc.z*acc.z))) * 180/(float) M_PI;+ roll = tanf(acc.y/acc.z) * 180/(float) M_PI;++ if ((fabsf(roll) < SENSORS_MAN_TEST_LEVEL_MAX) && (fabsf(pitch) < SENSORS_MAN_TEST_LEVEL_MAX))+ {+ DEBUG_PRINT("Acc level test [OK]\n");+ testStatus = true;+ }+ else+ {+ DEBUG_PRINT("Acc level test Roll:%0.2f, Pitch:%0.2f [FAIL]\n", (double)roll, (double)pitch);+ testStatus = false;+ }+ }+ else+ {+ DEBUG_PRINT("Gyro variance test [FAIL]\n");+ testStatus = false;+ }+ }++ return testStatus;+}++void __attribute__((used)) EXTI13_Callback(void)+{+ portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;+ imuIntTimestamp = usecTimestamp();+ xSemaphoreGiveFromISR(sensorsDataReady, &xHigherPriorityTaskWoken);++ if (xHigherPriorityTaskWoken)+ {+ portYIELD();+ }+}++/**+ * Compensate for a miss-aligned accelerometer. It uses the trim+ * data gathered from the UI and written in the config-block to+ * rotate the accelerometer to be aligned with gravity.+ */+static void sensorsAccAlignToGravity(Axis3f* in, Axis3f* out)+{+ Axis3f rx;+ Axis3f ry;++ // Rotate around x-axis+ rx.x = in->x;+ rx.y = in->y * cosRoll - in->z * sinRoll;+ rx.z = in->y * sinRoll + in->z * cosRoll;++ // Rotate around y-axis+ ry.x = rx.x * cosPitch - rx.z * sinPitch;+ ry.y = rx.y;+ ry.z = -rx.x * sinPitch + rx.z * cosPitch;++ out->x = ry.x;+ out->y = ry.y;+ out->z = ry.z;+}++void sensorsMpu9250Lps25hSetAccMode(accModes accMode)+{+ switch (accMode)+ {+ case ACC_MODE_PROPTEST:+ mpu6500SetAccelDLPF(MPU6500_ACCEL_DLPF_BW_460);+ for (uint8_t i = 0; i < 3; i++)+ {+ lpf2pInit(&accLpf[i], 1000, 500);+ }+ break;+ case ACC_MODE_FLIGHT:+ default:+ mpu6500SetAccelDLPF(MPU6500_ACCEL_DLPF_BW_41);+ for (uint8_t i = 0; i < 3; i++)+ {+ lpf2pInit(&accLpf[i], 1000, ACCEL_LPF_CUTOFF_FREQ);+ }+ break;+ }+}++static void applyAxis3fLpf(lpf2pData *data, Axis3f* in)+{+ for (uint8_t i = 0; i < 3; i++) {+ in->axis[i] = lpf2pApply(&data[i], in->axis[i]);+ }+}++#ifdef GYRO_ADD_RAW_AND_VARIANCE_LOG_VALUES+LOG_GROUP_START(gyro)+LOG_ADD(LOG_INT16, xRaw, &gyroRaw.x)+LOG_ADD(LOG_INT16, yRaw, &gyroRaw.y)+LOG_ADD(LOG_INT16, zRaw, &gyroRaw.z)+LOG_ADD(LOG_FLOAT, xVariance, &gyroBiasRunning.variance.x)+LOG_ADD(LOG_FLOAT, yVariance, &gyroBiasRunning.variance.y)+LOG_ADD(LOG_FLOAT, zVariance, &gyroBiasRunning.variance.z)+LOG_GROUP_STOP(gyro)+#endif++PARAM_GROUP_START(imu_sensors)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, HMC5883L, &isMagnetometerPresent)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, MS5611, &isBarometerPresent) // TODO: Rename MS5611 to LPS25H. Client needs to be updated at the same time.+PARAM_GROUP_STOP(imu_sensors)++PARAM_GROUP_START(imu_tests)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, MPU6500, &isMpu6500TestPassed)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, HMC5883L, &isAK8963TestPassed)+PARAM_ADD(PARAM_UINT8 | PARAM_RONLY, MS5611, &isLPS25HTestPassed) // TODO: Rename MS5611 to LPS25H. Client needs to be updated at the same time.+PARAM_GROUP_STOP(imu_tests)diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/storage.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/storage.cnew file mode 100644index 0000000..8f0800d--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/storage.c@@ -0,0 +1,194 @@+/**+ * ,---------, ____ _ __+ * | ,-^-, | / __ )(_) /_______________ _____ ___+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2019 - 2020 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * storage.c: Key/Buffer persistant storage+ *+ */++#include "storage.h"++#include "kve/kve.h"++#include "FreeRTOS.h"+#include "semphr.h"++#include "i2cdev.h"+#include "eeprom.h"++#define TRACE_MEMORY_ACCESS 0++#if !TRACE_MEMORY_ACCESS+#define DEBUG_MODULE "STORAGE"+#endif+#include "debug.h"++// Memory organization++// Low level memory access++// ToDo: Shall we handle partition elsewhere?+#define KVE_PARTITION_START (1024)+#define KVE_PARTITION_LENGTH (7*1024)++static SemaphoreHandle_t storageMutex;++static size_t readEeprom(size_t address, void* data, size_t length)+{+ if (length == 0) {+ return 0;+ }++ bool success = eepromReadBuffer(data, KVE_PARTITION_START + address, length);++#if TRACE_MEMORY_ACCESS+ DEBUG_PRINT("R %s @%04x l%d: ", success?" OK ":"FAIL", address, length);++ for (int i=0; i < length; i++) {+ DEBUG_PRINT("%02x ", ((char*)data)[i]);+ }++ DEBUG_PRINT("\n");+#endif++ if (success) {+ return length;+ } else {+ return 0;+ }+}++static size_t writeEeprom(size_t address, const void* data, size_t length)+{+ if (length == 0) {+ return 0;+ }++ bool success = eepromWriteBuffer(data, KVE_PARTITION_START + address, length);++#if TRACE_MEMORY_ACCESS+ DEBUG_PRINT("W %s @%04x: ", success?" OK ":"FAIL", address);++ for (int i=0; i < length; i++) {+ DEBUG_PRINT("%02x ", ((char*)data)[i]);+ }++ DEBUG_PRINT("\n");+#endif++ if (success) {+ return length;+ } else {+ return 0;+ }+}++static void flushEeprom(void)+{+ // NOP for now, lets fix the EEPROM write first!+}++static kveMemory_t kve = {+ .memorySize = KVE_PARTITION_LENGTH,+ .read = readEeprom,+ .write = writeEeprom,+ .flush = flushEeprom,+};++// Public API++static bool isInit = false;++void storageInit()+{+ storageMutex = xSemaphoreCreateMutex();++ isInit = true;+}++bool storageTest()+{+ bool pass = kveCheck(&kve);++ DEBUG_PRINT("Storage check %s.\n", pass?"[OK]":"[FAIL]");++ if (!pass) {+ DEBUG_PRINT("Reformating storage ...\n");++ kveFormat(&kve);++ pass = kveCheck(&kve);+ DEBUG_PRINT("Storage check %s.\n", pass?"[OK]":"[FAIL]");++ if (pass == false) {+ DEBUG_PRINT("Error: Cannot format storage!\n");+ }+ }++ return pass;+}++bool storageStore(char* key, const void* buffer, size_t length)+{+ if (!isInit) {+ return false;+ }++ xSemaphoreTake(storageMutex, portMAX_DELAY);++ bool result = kveStore(&kve, key, buffer, length);++ xSemaphoreGive(storageMutex);++ return result;+}++size_t storageFetch(char *key, void* buffer, size_t length)+{+ if (!isInit) {+ return 0;+ }++ xSemaphoreTake(storageMutex, portMAX_DELAY);++ size_t result = kveFetch(&kve, key, buffer, length);++ xSemaphoreGive(storageMutex);++ return result;+}++bool storageDelete(char* key)+{+ if (!isInit) {+ return false;+ }++ xSemaphoreTake(storageMutex, portMAX_DELAY);++ bool result = kveDelete(&kve, key);++ xSemaphoreGive(storageMutex);++ return result;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/syslink.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/syslink.cnew file mode 100644index 0000000..1bd4926--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/syslink.c@@ -0,0 +1,189 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2012 BitCraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * syslink.c: Communication between NRF51 and STM32+ */+#define DEBUG_MODULE "SL"++#include <stdbool.h>+#include <string.h>+#include <stdint.h>++#include "FreeRTOS.h"+#include "task.h"+#include "queue.h"+#include "semphr.h"++#include "config.h"+#include "debug.h"+#include "syslink.h"+#include "radiolink.h"+#include "uart_syslink.h"+#include "configblock.h"+#include "pm.h"+#include "ow.h"+#include "static_mem.h"++#ifdef UART2_LINK_COMM+#include "uart2.h"+#endif++static bool isInit = false;+static uint8_t sendBuffer[SYSLINK_MTU + 6];++static void syslinkRouteIncommingPacket(SyslinkPacket *slp);++static xSemaphoreHandle syslinkAccess;++STATIC_MEM_TASK_ALLOC_STACK_NO_DMA_CCM_SAFE(syslinkTask, SYSLINK_TASK_STACKSIZE);++/* Syslink task, handles communication between nrf and stm and dispatch messages+ */+static void syslinkTask(void *param)+{+ SyslinkPacket slp;+ while(1)+ {+ uartslkGetPacketBlocking(&slp);+ syslinkRouteIncommingPacket(&slp);+ }+}++#ifdef UART2_LINK_COMM++STATIC_MEM_TASK_ALLOC(uart2Task, UART2_TASK_STACKSIZE);++static void uart2Task(void *param)+{+ SyslinkPacket slp;+ while(1)+ {+ uart2GetPacketBlocking(&slp);+ syslinkRouteIncommingPacket(&slp);+ }+}++#endif++static void syslinkRouteIncommingPacket(SyslinkPacket *slp)+{+ uint8_t groupType;++ groupType = slp->type & SYSLINK_GROUP_MASK;++ switch (groupType)+ {+ case SYSLINK_RADIO_GROUP:+ radiolinkSyslinkDispatch(slp);+ break;+ case SYSLINK_PM_GROUP:+ pmSyslinkUpdate(slp);+ break;+ case SYSLINK_OW_GROUP:+ owSyslinkRecieve(slp);+ break;+ default:+ DEBUG_PRINT("Unknown packet:%X.\n", slp->type);+ break;+ }+}++/*+ * Public functions+ */++void syslinkInit()+{+ if(isInit) {+ return;+ }++ vSemaphoreCreateBinary(syslinkAccess);++ STATIC_MEM_TASK_CREATE(syslinkTask, syslinkTask, SYSLINK_TASK_NAME, NULL, SYSLINK_TASK_PRI);++ #ifdef UART2_LINK_COMM+ uart2Init(512000);+ STATIC_MEM_TASK_CREATE(uart2Task, uart2Task, UART2_TASK_NAME, NULL, UART2_TASK_PRI);+ #endif++ isInit = true;+}++bool syslinkTest()+{+ return isInit;+}++int syslinkSendPacket(SyslinkPacket *slp)+{+ int i = 0;+ int dataSize;+ uint8_t cksum[2] = {0};++ xSemaphoreTake(syslinkAccess, portMAX_DELAY);++ ASSERT(slp->length <= SYSLINK_MTU);++ sendBuffer[0] = SYSLINK_START_BYTE1;+ sendBuffer[1] = SYSLINK_START_BYTE2;+ sendBuffer[2] = slp->type;+ sendBuffer[3] = slp->length;++ memcpy(&sendBuffer[4], slp->data, slp->length);+ dataSize = slp->length + 6;+ // Calculate checksum delux+ for (i = 2; i < dataSize - 2; i++)+ {+ cksum[0] += sendBuffer[i];+ cksum[1] += cksum[0];+ }+ sendBuffer[dataSize-2] = cksum[0];+ sendBuffer[dataSize-1] = cksum[1];++ #ifdef UART2_LINK_COMM+ uint8_t groupType;+ groupType = slp->type & SYSLINK_GROUP_MASK;+ switch (groupType)+ {+ case SYSLINK_RADIO_GROUP:+ uart2SendDataDmaBlocking(dataSize, sendBuffer);+ break;+ case SYSLINK_PM_GROUP:+ uartslkSendDataDmaBlocking(dataSize, sendBuffer);+ break;+ case SYSLINK_OW_GROUP:+ uartslkSendDataDmaBlocking(dataSize, sendBuffer);+ break;+ default:+ DEBUG_PRINT("Unknown packet:%X.\n", slp->type);+ break;+ }+ #else+ uartslkSendDataDmaBlocking(dataSize, sendBuffer);+ #endif++ xSemaphoreGive(syslinkAccess);++ return 0;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/usb.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/usb.cnew file mode 100644index 0000000..4750b32--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/usb.c@@ -0,0 +1,411 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * uart.c - uart CRTP link and raw access functions+ */+#include <string.h>++/*ST includes */+#include "stm32fxxx.h"++/*FreeRtos includes*/+#include "FreeRTOS.h"+#include "task.h"+#include "semphr.h"+#include "queue.h"+#include "queuemonitor.h"++#include "config.h"+#include "usblink.h"+#include "radiolink.h"+#include "usb.h"++#include "usbd_usr.h"+#include "usb_conf.h"+#include "usbd_desc.h"+#include "usb_dcd.h"++#include "crtp.h"+#include "static_mem.h"+++NO_DMA_CCM_SAFE_ZERO_INIT __ALIGN_BEGIN USB_OTG_CORE_HANDLE USB_OTG_dev __ALIGN_END ;++static bool isInit = false;+static bool doingTransfer = false;++// This should probably be reduced to a CRTP packet size+static xQueueHandle usbDataRx;+STATIC_MEM_QUEUE_ALLOC(usbDataRx, 5, sizeof(USBPacket)); /* Buffer USB packets (max 64 bytes) */+static xQueueHandle usbDataTx;+STATIC_MEM_QUEUE_ALLOC(usbDataTx, 1, sizeof(USBPacket)); /* Buffer USB packets (max 64 bytes) */++/* Endpoints */+#define IN_EP 0x81 /* EP1 for data IN */+#define OUT_EP 0x01 /* EP1 for data OUT */++#define DEVICE_DESCRIPTOR 0x01+#define CONFIGURATION_DESCRIPTOR 0x02+#define STRING_DESCRIPTOR 0x03+#define INTERFACE_DESCRIPTOR 0x04+#define ENDPOINT_DESCRIPTOR 0x05++__ALIGN_BEGIN uint8_t usbd_cf_CfgDesc[57] __ALIGN_END = {+ /***** Configuration descriptor ******/+ 9, //bLength+ CONFIGURATION_DESCRIPTOR, //bDescriptorType+ 32,0x00, //wTotalLength+ 1, //bNumInterfaces+ 1, //bConfigurationValue+ 0, //iConfiguration+ 0x80, //bmAttribute (Bus powered, no remote wakeup)+ 50, //bMaxPower (100mA, shall be enough)+ /***** Interface 0 descriptor: Crazyradio EPs ******/+ 9, //bLength+ INTERFACE_DESCRIPTOR, //bDescriptorType+ 0, //bInterfaceNumber+ 0, //bAlternateSetting+ 2, //bNumEndpoint (one in, one out)+ 0xFF, //bInterfaceClass (VENDOR=0xFF)+ 0xFF, //bInterfaceSubClass (VENDOR=0xFF)+ 0, //bInterfaceProtocol (None)+ 0, //iInterface+ /***** Endpoint 1 IN descriptor ******/+ 7, //bLength+ ENDPOINT_DESCRIPTOR, //bDescriptorType+ 0x81, //bEndpointAddess (EP1 IN)+ 0x02, //bmAttributes (Bulk endpoint)+ 0x40, 0x00, //wMaxPacketSize (64 bytes)+ 6, //bInterval (irrelevant for bulk endpoint)+ /***** Endpoint 1 OUT descriptor ******/+ 7, //bLength+ ENDPOINT_DESCRIPTOR, //bDescriptorType+ 0x01, //bEndpointAddess (EP1 OUT)+ 0x02, //bmAttributes (Bulk endpoint)+ 0x40, 0x00, //wMaxPacketSize (64 bytes)+ 6, //bInterval (irrelevant for bulk endpoint)+};++static uint8_t usbd_cf_Init (void *pdev, uint8_t cfgidx);+static uint8_t usbd_cf_DeInit (void *pdev, uint8_t cfgidx);+static uint8_t usbd_cf_DataIn (void *pdev, uint8_t epnum);+static uint8_t usbd_cf_DataOut (void *pdev, uint8_t epnum);+static uint8_t *usbd_cf_GetCfgDesc (uint8_t speed, uint16_t *length);+static uint8_t usbd_cf_SOF (void *pdev);+static uint8_t usbd_cf_Setup (void *pdev , USB_SETUP_REQ *req);++static USBPacket inPacket;+static USBPacket outPacket;++/* CDC interface class callbacks structure */+USBD_Class_cb_TypeDef cf_usb_cb =+{+ usbd_cf_Init,+ usbd_cf_DeInit,+ usbd_cf_Setup,+ NULL,+ NULL,+ usbd_cf_DataIn,+ usbd_cf_DataOut,+ usbd_cf_SOF,+ NULL,+ NULL,+ usbd_cf_GetCfgDesc,+};++USBD_Usr_cb_TypeDef USR_cb =+{+ USBD_USR_Init,+ USBD_USR_DeviceReset,+ USBD_USR_DeviceConfigured,+ USBD_USR_DeviceSuspended,+ USBD_USR_DeviceResumed,+ USBD_USR_DeviceConnected,+ USBD_USR_DeviceDisconnected,+};++int command = 0xFF;++static void resetUSB(void) {+ portBASE_TYPE xTaskWokenByReceive = pdFALSE;++ crtpSetLink(radiolinkGetLink());++ if (isInit == true) {+ // Empty queue+ while (xQueueReceiveFromISR(usbDataTx, &outPacket, &xTaskWokenByReceive) == pdTRUE)+ ;+ }++ USB_OTG_FlushTxFifo(&USB_OTG_dev, IN_EP);+}++static uint8_t usbd_cf_Setup(void *pdev , USB_SETUP_REQ *req)+{+ command = req->wIndex;+ if (command == 0x01) {+ crtpSetLink(usblinkGetLink());+ } else {+ crtpSetLink(radiolinkGetLink());+ }++ return USBD_OK;+}++static uint8_t usbd_cf_Init (void *pdev,+ uint8_t cfgidx)+{+ /* Open EP IN */+ DCD_EP_Open(pdev,+ IN_EP,+ USB_RX_TX_PACKET_SIZE,+ USB_OTG_EP_BULK);++ /* Open EP OUT */+ DCD_EP_Open(pdev,+ OUT_EP,+ USB_RX_TX_PACKET_SIZE,+ USB_OTG_EP_BULK);++ /* Prepare Out endpoint to receive next packet */+ DCD_EP_PrepareRx(pdev,+ OUT_EP,+ (uint8_t*)(inPacket.data),+ USB_RX_TX_PACKET_SIZE);++ return USBD_OK;+}++/**+ * @brief usbd_cdc_Init+ * DeInitialize the CDC layer+ * @param pdev: device instance+ * @param cfgidx: Configuration index+ * @retval status+ */+static uint8_t usbd_cf_DeInit (void *pdev,+ uint8_t cfgidx)+{+ /* Open EP IN */+ DCD_EP_Close(pdev, IN_EP);++ /* Open EP OUT */+ DCD_EP_Close(pdev, OUT_EP);++ return USBD_OK;+}++/**+ * @brief usbd_audio_DataIn+ * Data sent on non-control IN endpoint+ * @param pdev: device instance+ * @param epnum: endpoint number+ * @retval status+ */+static uint8_t usbd_cf_DataIn (void *pdev, uint8_t epnum)+{+ portBASE_TYPE xTaskWokenByReceive = pdFALSE;++ doingTransfer = false;++ if (xQueueReceiveFromISR(usbDataTx, &outPacket, &xTaskWokenByReceive) == pdTRUE)+ {+ doingTransfer = true;+ DCD_EP_Tx (pdev,+ IN_EP,+ (uint8_t*)outPacket.data,+ outPacket.size);+ }++ portYIELD_FROM_ISR(xTaskWokenByReceive);++ return USBD_OK;+}++static uint8_t usbd_cf_SOF (void *pdev)+{+ portBASE_TYPE xTaskWokenByReceive = pdFALSE;++ if (!doingTransfer) {+ if (xQueueReceiveFromISR(usbDataTx, &outPacket, &xTaskWokenByReceive) == pdTRUE)+ {+ doingTransfer = true;+ DCD_EP_Tx (pdev,+ IN_EP,+ (uint8_t*)outPacket.data,+ outPacket.size);+ }+ }++ portYIELD_FROM_ISR(xTaskWokenByReceive);++ return USBD_OK;+}++/**+ * @brief usbd_cf_DataOut+ * Data received on non-control Out endpoint+ * @param pdev: device instance+ * @param epnum: endpoint number+ * @retval status+ */+static uint8_t usbd_cf_DataOut (void *pdev, uint8_t epnum)+{+ portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;++ /* Get the received data buffer and update the counter */+ inPacket.size = ((USB_OTG_CORE_HANDLE*)pdev)->dev.out_ep[epnum].xfer_count;++ xQueueSendFromISR(usbDataRx, &inPacket, &xHigherPriorityTaskWoken);++ /* Prepare Out endpoint to receive next packet */+ DCD_EP_PrepareRx(pdev,+ OUT_EP,+ (uint8_t*)(inPacket.data),+ USB_RX_TX_PACKET_SIZE);++ return USBD_OK;+}++/**+ * @brief USBD_cdc_GetCfgDesc+ * Return configuration descriptor+ * @param speed : current device speed+ * @param length : pointer data length+ * @retval pointer to descriptor buffer+ */+static uint8_t *usbd_cf_GetCfgDesc (uint8_t speed, uint16_t *length)+{+ *length = sizeof (usbd_cf_CfgDesc);+ return usbd_cf_CfgDesc;+}++/**+* @brief USBD_USR_Init+* Displays the message on LCD for host lib initialization+* @param None+* @retval None+*/+void USBD_USR_Init(void)+{+}++/**+* @brief USBD_USR_DeviceReset+* @param speed : device speed+* @retval None+*/+void USBD_USR_DeviceReset(uint8_t speed)+{+ resetUSB();+}+++/**+* @brief USBD_USR_DeviceConfigured+* @param None+* @retval Staus+*/+void USBD_USR_DeviceConfigured(void)+{+}++/**+* @brief USBD_USR_DeviceSuspended+* @param None+* @retval None+*/+void USBD_USR_DeviceSuspended(void)+{+ /* USB communication suspended (probably USB unplugged). Switch back to radiolink */+ resetUSB();+}+++/**+* @brief USBD_USR_DeviceResumed+* @param None+* @retval None+*/+void USBD_USR_DeviceResumed(void)+{+}+++/**+* @brief USBD_USR_DeviceConnected+* @param None+* @retval Staus+*/+void USBD_USR_DeviceConnected(void)+{+}+++/**+* @brief USBD_USR_DeviceDisonnected+* @param None+* @retval Staus+*/+void USBD_USR_DeviceDisconnected(void)+{+ resetUSB();+}++void usbInit(void)+{+ USBD_Init(&USB_OTG_dev,+ USB_OTG_FS_CORE_ID,+ &USR_desc,+ &cf_usb_cb,+ &USR_cb);++ usbDataRx = STATIC_MEM_QUEUE_CREATE(usbDataRx);+ DEBUG_QUEUE_MONITOR_REGISTER(usbDataRx);+ usbDataTx = STATIC_MEM_QUEUE_CREATE(usbDataTx);+ DEBUG_QUEUE_MONITOR_REGISTER(usbDataTx);++ isInit = true;+}++bool usbTest(void)+{+ return isInit;+}++bool usbGetDataBlocking(USBPacket *in)+{+ while (xQueueReceive(usbDataRx, in, portMAX_DELAY) != pdTRUE)+ ; // Don't return until we get some data on the USB+ return true;+}++static USBPacket outStage;++bool usbSendData(uint32_t size, uint8_t* data)+{+ outStage.size = size;+ memcpy(outStage.data, data, size);+ // Dont' block when sending+ return (xQueueSend(usbDataTx, &outStage, M2T(100)) == pdTRUE);+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/usb_bsp.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/usb_bsp.cnew file mode 100644index 0000000..43c43ea--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/usb_bsp.c@@ -0,0 +1,328 @@+/**+ ******************************************************************************+ * @file usb_bsp.c+ * @author MCD Application Team+ * @version V1.1.0+ * @date 19-March-2012+ * @brief This file is responsible to offer board support package and is+ * configurable by user.+ ******************************************************************************+ * @attention+ *+ * <h2><center>© COPYRIGHT 2012 STMicroelectronics</center></h2>+ *+ * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");+ * You may not use this file except in compliance with the License.+ * You may obtain a copy of the License at:+ *+ * http://www.st.com/software_license_agreement_liberty_v2+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ ******************************************************************************+ */++/* Includes ------------------------------------------------------------------*/+#include "usb_bsp.h"+#include "usbd_conf.h"++#include "stm32fxxx.h"++#include "config.h"+#include "nvicconf.h"+++/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY+* @{+*/++/** @defgroup USB_BSP+* @brief This file is responsible to offer board support package+* @{+*/++/** @defgroup USB_BSP_Private_Defines+* @{+*/+/**+* @}+*/+++/** @defgroup USB_BSP_Private_TypesDefinitions+* @{+*/+/**+* @}+*/++++++/** @defgroup USB_BSP_Private_Macros+* @{+*/+/**+* @}+*/++/** @defgroup USBH_BSP_Private_Variables+* @{+*/++/**+* @}+*/++/** @defgroup USBH_BSP_Private_FunctionPrototypes+* @{+*/+/**+* @}+*/++/** @defgroup USB_BSP_Private_Functions+* @{+*/+++/**+* @brief USB_OTG_BSP_Init+* Initilizes BSP configurations+* @param None+* @retval None+*/++void USB_OTG_BSP_Init(USB_OTG_CORE_HANDLE *pdev)+{+#ifdef USE_STM3210C_EVAL++ RCC_OTGFSCLKConfig(RCC_OTGFSCLKSource_PLLVCO_Div3);+ RCC_AHBPeriphClockCmd(RCC_AHBPeriph_OTG_FS, ENABLE) ;++#else // USE_STM322xG_EVAL+ GPIO_InitTypeDef GPIO_InitStructure;+ #ifdef USE_USB_OTG_FS+ RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOA , ENABLE);++ /* Configure SOF ID DM DP Pins */+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 |+ GPIO_Pin_11 |+ GPIO_Pin_12;++ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;+ GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;+ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;+ GPIO_Init(GPIOA, &GPIO_InitStructure);++ // AF10++ GPIO_PinAFConfig(GPIOA,GPIO_PinSource8,GPIO_AF_OTG1_FS) ;+ GPIO_PinAFConfig(GPIOA,GPIO_PinSource11,GPIO_AF_OTG1_FS) ;+ GPIO_PinAFConfig(GPIOA,GPIO_PinSource12,GPIO_AF_OTG1_FS) ;++ /* Configure VBUS Pin */+ /*GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;+ GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;+ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;+ GPIO_Init(GPIOA, &GPIO_InitStructure); */++ /* Configure ID pin */+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;+ GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;+ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ;+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;+ GPIO_Init(GPIOA, &GPIO_InitStructure);+ GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_OTG1_FS) ;++ RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);+ RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_OTG_FS, ENABLE) ;+ #else // USE_USB_OTG_HS++ #ifdef USE_ULPI_PHY // ULPI+ RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOB |+ RCC_AHB1Periph_GPIOC | RCC_AHB1Periph_GPIOH |+ RCC_AHB1Periph_GPIOI, ENABLE);+++ GPIO_PinAFConfig(GPIOA,GPIO_PinSource3, GPIO_AF_OTG2_HS) ; // D0+ GPIO_PinAFConfig(GPIOA,GPIO_PinSource5, GPIO_AF_OTG2_HS) ; // CLK+ GPIO_PinAFConfig(GPIOB,GPIO_PinSource0, GPIO_AF_OTG2_HS) ; // D1+ GPIO_PinAFConfig(GPIOB,GPIO_PinSource1, GPIO_AF_OTG2_HS) ; // D2+ GPIO_PinAFConfig(GPIOB,GPIO_PinSource5, GPIO_AF_OTG2_HS) ; // D7+ GPIO_PinAFConfig(GPIOB,GPIO_PinSource10,GPIO_AF_OTG2_HS) ; // D3+ GPIO_PinAFConfig(GPIOB,GPIO_PinSource11,GPIO_AF_OTG2_HS) ; // D4+ GPIO_PinAFConfig(GPIOB,GPIO_PinSource12,GPIO_AF_OTG2_HS) ; // D5+ GPIO_PinAFConfig(GPIOB,GPIO_PinSource13,GPIO_AF_OTG2_HS) ; // D6+ GPIO_PinAFConfig(GPIOH,GPIO_PinSource4, GPIO_AF_OTG2_HS) ; // NXT+ GPIO_PinAFConfig(GPIOI,GPIO_PinSource11,GPIO_AF_OTG2_HS) ; // DIR+ GPIO_PinAFConfig(GPIOC,GPIO_PinSource0, GPIO_AF_OTG2_HS) ; // STP++ // CLK+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 ;+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;+ GPIO_Init(GPIOA, &GPIO_InitStructure);++ // D0+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3 ;+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;+ GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;+ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;+ GPIO_Init(GPIOA, &GPIO_InitStructure);++++ // D1 D2 D3 D4 D5 D6 D7+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 |+ GPIO_Pin_5 | GPIO_Pin_10 |+ GPIO_Pin_11| GPIO_Pin_12 |+ GPIO_Pin_13 ;++ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;+ GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;+ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;+ GPIO_Init(GPIOB, &GPIO_InitStructure);+++ // STP+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 ;+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;+ GPIO_Init(GPIOC, &GPIO_InitStructure);++ //NXT+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;+ GPIO_Init(GPIOH, &GPIO_InitStructure);+++ //DIR+ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 ;+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;+ GPIO_Init(GPIOI, &GPIO_InitStructure);+++ RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_OTG_HS |+ RCC_AHB1Periph_OTG_HS_ULPI, ENABLE) ;++ #else++ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB , ENABLE);++ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 |+ GPIO_Pin_14 |+ GPIO_Pin_15;++ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;+ GPIO_Init(GPIOB, &GPIO_InitStructure);++ GPIO_PinAFConfig(GPIOB,GPIO_PinSource12, GPIO_AF_OTG2_FS) ;+ GPIO_PinAFConfig(GPIOB,GPIO_PinSource14,GPIO_AF_OTG2_FS) ;+ GPIO_PinAFConfig(GPIOB,GPIO_PinSource15,GPIO_AF_OTG2_FS) ;++ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;+ GPIO_Init(GPIOB, &GPIO_InitStructure);+++ RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_OTG_HS, ENABLE) ;++ #endif+ #endif //USB_OTG_HS+#endif //USE_STM322xG_EVAL+}+/**+* @brief USB_OTG_BSP_EnableInterrupt+* Enabele USB Global interrupt+* @param None+* @retval None+*/+void USB_OTG_BSP_EnableInterrupt(USB_OTG_CORE_HANDLE *pdev)+{+ NVIC_InitTypeDef NVIC_InitStructure;++ NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);+#ifdef USE_USB_OTG_HS+ NVIC_InitStructure.NVIC_IRQChannel = OTG_HS_IRQn;+#else+ NVIC_InitStructure.NVIC_IRQChannel = OTG_FS_IRQn;+#endif+ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_MID_PRI;+ NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;+ NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;+ NVIC_Init(&NVIC_InitStructure);+#ifdef USB_OTG_HS_DEDICATED_EP1_ENABLED+ NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);+ NVIC_InitStructure.NVIC_IRQChannel = OTG_HS_EP1_OUT_IRQn;+ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_MID_PRI;+ NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;+ NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;+ NVIC_Init(&NVIC_InitStructure);++ NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);+ NVIC_InitStructure.NVIC_IRQChannel = OTG_HS_EP1_IN_IRQn;+ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_MID_PRI;+ NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;+ NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;+ NVIC_Init(&NVIC_InitStructure);+#endif+}+/**+* @brief USB_OTG_BSP_uDelay+* This function provides delay time in micro sec+* @param usec : Value of delay required in micro sec+* @retval None+*/+void USB_OTG_BSP_uDelay (const uint32_t usec)+{+ uint32_t count = 0;+ const uint32_t utime = (120 * usec / 7);+ do+ {+ if ( ++count > utime )+ {+ return ;+ }+ }+ while (1);+}+++/**+* @brief USB_OTG_BSP_mDelay+* This function provides delay time in milli sec+* @param msec : Value of delay required in milli sec+* @retval None+*/+void USB_OTG_BSP_mDelay (const uint32_t msec)+{+ USB_OTG_BSP_uDelay(msec * 1000);+}+/**+* @}+*/++/**+* @}+*/++/**+* @}+*/++/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/usbd_desc.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/usbd_desc.cnew file mode 100644index 0000000..105df08--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/usbd_desc.c@@ -0,0 +1,333 @@+/**+ ******************************************************************************+ * @file usbd_desc.c+ * @author MCD Application Team+ * @version V1.1.0+ * @date 19-March-2012+ * @brief This file provides the USBD descriptors and string formating method.+ ******************************************************************************+ * @attention+ *+ * <h2><center>© COPYRIGHT 2012 STMicroelectronics</center></h2>+ *+ * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");+ * You may not use this file except in compliance with the License.+ * You may obtain a copy of the License at:+ *+ * http://www.st.com/software_license_agreement_liberty_v2+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ ******************************************************************************+ */++/* Includes ------------------------------------------------------------------*/+#include "usbd_core.h"+#include "usbd_desc.h"+#include "usbd_req.h"+#include "usbd_conf.h"+#include "usb_regs.h"++#include "config.h"++/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY+ * @{+ */+++/** @defgroup USBD_DESC+ * @brief USBD descriptors module+ * @{+ */++/** @defgroup USBD_DESC_Private_TypesDefinitions+ * @{+ */+/**+ * @}+ */+++/** @defgroup USBD_DESC_Private_Defines+ * @{+ */+#define USBD_VID 0x0483++#define USBD_PID 0x5740++/** @defgroup USB_String_Descriptors+ * @{+ */+#define USBD_LANGID_STRING 0x409+#define USBD_MANUFACTURER_STRING "Bitcraze AB"++#define USBD_PRODUCT_HS_STRING "STM32 Virtual ComPort in HS mode"+#define USBD_SERIALNUMBER_HS_STRING "00000000050B"++#define USBD_PRODUCT_FS_STRING "Crazyflie 2.0"+#define USBD_SERIALNUMBER_FS_STRING "00000000050C"++#define USBD_CONFIGURATION_HS_STRING "VCP Config"+#define USBD_INTERFACE_HS_STRING "VCP Interface"++#define USBD_CONFIGURATION_FS_STRING "VCP Config"+#define USBD_INTERFACE_FS_STRING "Raw CRTP interface"+/**+ * @}+ */+++/** @defgroup USBD_DESC_Private_Macros+ * @{+ */+/**+ * @}+ */+++/** @defgroup USBD_DESC_Private_Variables+ * @{+ */++USBD_DEVICE USR_desc =+{+ USBD_USR_DeviceDescriptor,+ USBD_USR_LangIDStrDescriptor,+ USBD_USR_ManufacturerStrDescriptor,+ USBD_USR_ProductStrDescriptor,+ USBD_USR_SerialStrDescriptor,+ USBD_USR_ConfigStrDescriptor,+ USBD_USR_InterfaceStrDescriptor,++};++#ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED+ #if defined ( __ICCARM__ ) /*!< IAR Compiler */+ #pragma data_alignment=4+ #endif+#endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */+/* USB Standard Device Descriptor */+__ALIGN_BEGIN uint8_t USBD_DeviceDesc[USB_SIZ_DEVICE_DESC] __ALIGN_END =+ {+ 0x12, /*bLength */+ USB_DEVICE_DESCRIPTOR_TYPE, /*bDescriptorType*/+ 0x00, /*bcdUSB */+ 0x02,+ 0x00, /*bDeviceClass*/+ 0x00, /*bDeviceSubClass*/+ 0x00, /*bDeviceProtocol*/+ USB_OTG_MAX_EP0_SIZE, /*bMaxPacketSize*/+ LOBYTE(USBD_VID), /*idVendor*/+ HIBYTE(USBD_VID), /*idVendor*/+ LOBYTE(USBD_PID), /*idVendor*/+ HIBYTE(USBD_PID), /*idVendor*/+ 0x00, /*bcdDevice rel. 2.00*/+ 0x02,+ USBD_IDX_MFC_STR, /*Index of manufacturer string*/+ USBD_IDX_PRODUCT_STR, /*Index of product string*/+ USBD_IDX_SERIAL_STR, /*Index of serial number string*/+ USBD_CFG_MAX_NUM /*bNumConfigurations*/+ } ; /* USB_DeviceDescriptor */++#ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED+ #if defined ( __ICCARM__ ) /*!< IAR Compiler */+ #pragma data_alignment=4+ #endif+#endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */+/* USB Standard Device Descriptor */+__ALIGN_BEGIN uint8_t USBD_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END =+{+ USB_LEN_DEV_QUALIFIER_DESC,+ USB_DESC_TYPE_DEVICE_QUALIFIER,+ 0x00,+ 0x02,+ 0x00,+ 0x00,+ 0x00,+ 0x40,+ 0x01,+ 0x00,+};++#ifdef USB_OTG_HS_INTERNAL_DMA_ENABLED+ #if defined ( __ICCARM__ ) /*!< IAR Compiler */+ #pragma data_alignment=4+ #endif+#endif /* USB_OTG_HS_INTERNAL_DMA_ENABLED */+/* USB Standard Device Descriptor */+__ALIGN_BEGIN uint8_t USBD_LangIDDesc[USB_SIZ_STRING_LANGID] __ALIGN_END =+{+ USB_SIZ_STRING_LANGID,+ USB_DESC_TYPE_STRING,+ LOBYTE(USBD_LANGID_STRING),+ HIBYTE(USBD_LANGID_STRING),+};+/**+ * @}+ */+++/** @defgroup USBD_DESC_Private_FunctionPrototypes+ * @{+ */+/**+ * @}+ */+++/** @defgroup USBD_DESC_Private_Functions+ * @{+ */++/**+* @brief USBD_USR_DeviceDescriptor+* return the device descriptor+* @param speed : current device speed+* @param length : pointer to data length variable+* @retval pointer to descriptor buffer+*/+uint8_t * USBD_USR_DeviceDescriptor( uint8_t speed , uint16_t *length)+{+ *length = sizeof(USBD_DeviceDesc);+ return USBD_DeviceDesc;+}++/**+* @brief USBD_USR_LangIDStrDescriptor+* return the LangID string descriptor+* @param speed : current device speed+* @param length : pointer to data length variable+* @retval pointer to descriptor buffer+*/+uint8_t * USBD_USR_LangIDStrDescriptor( uint8_t speed , uint16_t *length)+{+ *length = sizeof(USBD_LangIDDesc);+ return USBD_LangIDDesc;+}+++/**+* @brief USBD_USR_ProductStrDescriptor+* return the product string descriptor+* @param speed : current device speed+* @param length : pointer to data length variable+* @retval pointer to descriptor buffer+*/+uint8_t * USBD_USR_ProductStrDescriptor( uint8_t speed , uint16_t *length)+{+++ if(speed == 0)+ {+ USBD_GetString ((uint8_t *)USBD_PRODUCT_HS_STRING, USBD_StrDesc, length);+ }+ else+ {+ USBD_GetString ((uint8_t *)USBD_PRODUCT_FS_STRING, USBD_StrDesc, length);+ }+ return USBD_StrDesc;+}++/**+* @brief USBD_USR_ManufacturerStrDescriptor+* return the manufacturer string descriptor+* @param speed : current device speed+* @param length : pointer to data length variable+* @retval pointer to descriptor buffer+*/+uint8_t * USBD_USR_ManufacturerStrDescriptor( uint8_t speed , uint16_t *length)+{+ USBD_GetString ((uint8_t *)USBD_MANUFACTURER_STRING, USBD_StrDesc, length);+ return USBD_StrDesc;+}++static const char bin2hex[] = {'0', '1', '2', '3', '4', '5', '6', '7',+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};++/**+* @brief USBD_USR_SerialStrDescriptor+* return the serial number string descriptor+* @param speed : current device speed+* @param length : pointer to data length variable+* @retval pointer to descriptor buffer+*/+uint8_t * USBD_USR_SerialStrDescriptor( uint8_t speed , uint16_t *length)+{+ char serial_nr[25];+ char *chip_id = (char*)MCU_ID_ADDRESS;+ int i;++ serial_nr[24] = 0;++ for (i=0; i<12; i++)+ {+ serial_nr[0+(i*2)] = bin2hex[(chip_id[i]>>4)&0x0F];+ serial_nr[1+(i*2)] = bin2hex[chip_id[i]&0x0F];+ }++ USBD_GetString ((uint8_t *)serial_nr, USBD_StrDesc, length);++ return USBD_StrDesc;+}++/**+* @brief USBD_USR_ConfigStrDescriptor+* return the configuration string descriptor+* @param speed : current device speed+* @param length : pointer to data length variable+* @retval pointer to descriptor buffer+*/+uint8_t * USBD_USR_ConfigStrDescriptor( uint8_t speed , uint16_t *length)+{+ if(speed == USB_OTG_SPEED_HIGH)+ {+ USBD_GetString ((uint8_t *)USBD_CONFIGURATION_HS_STRING, USBD_StrDesc, length);+ }+ else+ {+ USBD_GetString ((uint8_t *)USBD_CONFIGURATION_FS_STRING, USBD_StrDesc, length);+ }+ return USBD_StrDesc;+}+++/**+* @brief USBD_USR_InterfaceStrDescriptor+* return the interface string descriptor+* @param speed : current device speed+* @param length : pointer to data length variable+* @retval pointer to descriptor buffer+*/+uint8_t * USBD_USR_InterfaceStrDescriptor( uint8_t speed , uint16_t *length)+{+ if(speed == 0)+ {+ USBD_GetString ((uint8_t *)USBD_INTERFACE_HS_STRING, USBD_StrDesc, length);+ }+ else+ {+ USBD_GetString ((uint8_t *)USBD_INTERFACE_FS_STRING, USBD_StrDesc, length);+ }+ return USBD_StrDesc;+}++/**+ * @}+ */+++/**+ * @}+ */+++/**+ * @}+ */++/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/+diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/usblink.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/usblink.cnew file mode 100644index 0000000..ff018ff--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/usblink.c@@ -0,0 +1,148 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2012 BitCraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * syslink.c: nRF24L01 implementation of the CRTP link+ */++#include <stdbool.h>+#include <string.h>++#include "config.h"+#include "usblink.h"+#include "crtp.h"+#include "configblock.h"+#include "ledseq.h"+#include "pm.h"++#include "FreeRTOS.h"+#include "task.h"+#include "queue.h"+#include "queuemonitor.h"+#include "semphr.h"+#include "static_mem.h"++#include "usb.h"++static bool isInit = false;+static xQueueHandle crtpPacketDelivery;+STATIC_MEM_QUEUE_ALLOC(crtpPacketDelivery, 16, sizeof(CRTPPacket));+static uint8_t sendBuffer[64];++static int usblinkSendPacket(CRTPPacket *p);+static int usblinkSetEnable(bool enable);+static int usblinkReceiveCRTPPacket(CRTPPacket *p);++STATIC_MEM_TASK_ALLOC(usblinkTask, USBLINK_TASK_STACKSIZE);++static struct crtpLinkOperations usblinkOp =+{+ .setEnable = usblinkSetEnable,+ .sendPacket = usblinkSendPacket,+ .receivePacket = usblinkReceiveCRTPPacket,+};++/* Radio task handles the CRTP packet transfers as well as the radio link+ * specific communications (eg. Scann and ID ports, communication error handling+ * and so much other cool things that I don't have time for it ...)+ */+static USBPacket usbIn;+static CRTPPacket p;+static void usblinkTask(void *param)+{+ while(1)+ {+ // Fetch a USB packet off the queue+ usbGetDataBlocking(&usbIn);+ p.size = usbIn.size - 1;+ memcpy(&p.raw, usbIn.data, usbIn.size);+ // This queuing will copy a CRTP packet size from usbIn+ ASSERT(xQueueSend(crtpPacketDelivery, &p, 0) == pdTRUE);+ }++}++static int usblinkReceiveCRTPPacket(CRTPPacket *p)+{+ if (xQueueReceive(crtpPacketDelivery, p, M2T(100)) == pdTRUE)+ {+ ledseqRun(&seq_linkUp);+ return 0;+ }++ return -1;+}++static int usblinkSendPacket(CRTPPacket *p)+{+ int dataSize;++ ASSERT(p->size < SYSLINK_MTU);++ sendBuffer[0] = p->header;++ if (p->size <= CRTP_MAX_DATA_SIZE)+ {+ memcpy(&sendBuffer[1], p->data, p->size);+ }+ dataSize = p->size + 1;+++ ledseqRun(&seq_linkDown);++ return usbSendData(dataSize, sendBuffer);+}++static int usblinkSetEnable(bool enable)+{+ return 0;+}++/*+ * Public functions+ */++void usblinkInit()+{+ if(isInit)+ return;++ // Initialize the USB peripheral+ usbInit();++ crtpPacketDelivery = STATIC_MEM_QUEUE_CREATE(crtpPacketDelivery);+ DEBUG_QUEUE_MONITOR_REGISTER(crtpPacketDelivery);++ STATIC_MEM_TASK_CREATE(usblinkTask, usblinkTask, USBLINK_TASK_NAME, NULL, USBLINK_TASK_PRI);++ isInit = true;+}++bool usblinkTest()+{+ return isInit;+}++struct crtpLinkOperations * usblinkGetLink()+{+ return &usblinkOp;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/usec_time.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/usec_time.cnew file mode 100644index 0000000..05f2d76--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/usec_time.c@@ -0,0 +1,41 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2011-2013 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * usec_time.c - microsecond-resolution timer and timestamps.+ */++#include "usec_time.h"+#include "esp_timer.h"+void initUsecTimer(void)+{++}++uint64_t usecTimestamp(void)+{+ return (uint64_t)esp_timer_get_time();+}++diff --git a/Firmware/esp-drone/components/core/crazyflie/hal/src/wifilink.c b/Firmware/esp-drone/components/core/crazyflie/hal/src/wifilink.cnew file mode 100644index 0000000..a03747d--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/hal/src/wifilink.c@@ -0,0 +1,189 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2012 BitCraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * wifilink.c: ESP32 Wi-Fi implementation of the CRTP link+ */++#include <stdbool.h>+#include <string.h>++#include "config.h"+#include "wifilink.h"+#include "wifi_esp32.h"+#include "crtp.h"+#include "configblock.h"+#include "ledseq.h"+#include "pm_esplane.h"+#include "FreeRTOS.h"+#include "task.h"+#include "queue.h"+#include "queuemonitor.h"+#include "semphr.h"+#include "stm32_legacy.h"++#define DEBUG_MODULE "WIFILINK"+#include "debug_cf.h"+#include "static_mem.h"++#define WIFI_ACTIVITY_TIMEOUT_MS (1000)++static bool isInit = false;+static xQueueHandle crtpPacketDelivery;+STATIC_MEM_QUEUE_ALLOC(crtpPacketDelivery, 16, sizeof(CRTPPacket));+static uint8_t sendBuffer[64];++static UDPPacket wifiIn;+static CRTPPacket p;+static uint32_t lastPacketTick;++static int wifilinkSendPacket(CRTPPacket *p);+static int wifilinkSetEnable(bool enable);+static int wifilinkReceiveCRTPPacket(CRTPPacket *p);++STATIC_MEM_TASK_ALLOC(wifilinkTask, USBLINK_TASK_STACKSIZE);++static bool wifilinkIsConnected(void)+{+ return (xTaskGetTickCount() - lastPacketTick) < M2T(WIFI_ACTIVITY_TIMEOUT_MS);+}++static struct crtpLinkOperations wifilinkOp = {+ .setEnable = wifilinkSetEnable,+ .sendPacket = wifilinkSendPacket,+ .receivePacket = wifilinkReceiveCRTPPacket,+ .isConnected = wifilinkIsConnected,+};++#ifdef CONFIG_ENABLE_LEGACY_APP+static bool detectOldVersionApp(UDPPacket *in)+{++ if ((in->data)[0] != 0x00 && in->size == 11) { //12-1+ if ((in->data)[0] == 0x80 && (in->data)[9] == 0x00 && (in->data)[10] == 0x00 && (in->data)[11] == 0x00) {+ return true;+ }+ }++ return false;+}+#endif++static void wifilinkTask(void *param)+{+ while (1) {+ /* command step - receive 03 Fetch a wifi packet off the queue */+ wifiGetDataBlocking(&wifiIn);+ lastPacketTick = xTaskGetTickCount();+#ifdef CONFIG_ENABLE_LEGACY_APP+ float rch, pch, ych;+ uint16_t tch;+ if (detectOldVersionApp(&wifiIn)) {+ rch = (1.0) * (float)(((((uint16_t)wifiIn.data[1] << 8) + (uint16_t)wifiIn.data[2]) - 296) * 15.0 / 150.0); //-15~+15+ pch = (-1.0) * (float)(((((uint16_t)wifiIn.data[3] << 8) + (uint16_t)wifiIn.data[4]) - 296) * 15.0 / 150.0); //-15~+15+ tch = (((uint16_t)wifiIn.data[5] << 8) + (uint16_t)wifiIn.data[6]) * 59000.0 / 600.0;+ ych = (float)(((((uint16_t)wifiIn.data[7] << 8) + (uint16_t)wifiIn.data[8]) - 296) * 15.0 / 150.0); //-15~+15+ p.size = wifiIn.size + 1 ; //add cksum size+ p.header = CRTP_HEADER(CRTP_PORT_SETPOINT, 0x00); //head redefine++ memcpy(&p.data[0], &rch, 4);+ memcpy(&p.data[4], &pch, 4);+ memcpy(&p.data[8], &ych, 4);+ memcpy(&p.data[12], &tch, 2);+ } else+#endif+ {+ /* command step - receive 04 copy CRTP part from packet, the size not contain head */+ p.size = wifiIn.size - 1;+ memcpy(&p.raw, wifiIn.data, wifiIn.size);+ }++ /* command step - receive 05 send to crtpPacketDelivery queue */+ xQueueSend(crtpPacketDelivery, &p, 0) ;+ }++}++static int wifilinkReceiveCRTPPacket(CRTPPacket *p)+{+ if (xQueueReceive(crtpPacketDelivery, p, M2T(100)) == pdTRUE) {+ ledseqRun(&seq_linkUp);+ return 0;+ }++ return -1;+}++static int wifilinkSendPacket(CRTPPacket *p)+{+ int dataSize;++ ASSERT(p->size < SYSLINK_MTU);++ sendBuffer[0] = p->header;++ if (p->size <= CRTP_MAX_DATA_SIZE) {+ memcpy(&sendBuffer[1], p->data, p->size);+ }++ dataSize = p->size + 1;+++ /*ledseqRun(&seq_linkDown);*/++ return wifiSendData(dataSize, sendBuffer);+}++static int wifilinkSetEnable(bool enable)+{+ return 0;+}++/*+ * Public functions+ */++void wifilinkInit()+{+ if (isInit) {+ return;+ }+++ crtpPacketDelivery = STATIC_MEM_QUEUE_CREATE(crtpPacketDelivery);+ DEBUG_QUEUE_MONITOR_REGISTER(crtpPacketDelivery);++ STATIC_MEM_TASK_CREATE(wifilinkTask, wifilinkTask,WIFILINK_TASK_NAME,NULL, WIFILINK_TASK_PRI);++ isInit = true;+}++bool wifilinkTest()+{+ return isInit;+}++struct crtpLinkOperations *wifilinkGetLink()+{+ return &wifilinkOp;+}