mirror of
https://github.com/okalachev/flix.git
synced 2026-08-16 00:38:56 +00:00
Compare commits
34
Commits
8917849711
...
pos-draft
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
142cb9af01 | ||
|
|
74b082957e | ||
|
|
4582942919 | ||
|
|
df14a5678f | ||
|
|
81721abf91 | ||
|
|
1276d220a6 | ||
|
|
79c7e282cb | ||
|
|
f031cf3046 | ||
|
|
60f389a289 | ||
|
|
5c24ce113d | ||
|
|
b58c2e7c7a | ||
|
|
2137730a8d | ||
|
|
309d2d2e29 | ||
|
|
0c91ccfab5 | ||
|
|
26d53d4ce1 | ||
|
|
0366b24ff3 | ||
|
|
3de4e9ab9a | ||
|
|
f1e024b19a | ||
|
|
d9be26c5be | ||
|
|
f8a4cbfee1 | ||
|
|
658040e652 | ||
|
|
70459df8dd | ||
|
|
61213bb8a1 | ||
|
|
d48b71fb1a | ||
|
|
0439407d76 | ||
|
|
c2005a2ca2 | ||
|
|
6a804862da | ||
|
|
590bfe10b0 | ||
|
|
70af1a1c09 | ||
|
|
9e9dafbdfb | ||
|
|
86a4418813 | ||
|
|
7c53e88963 | ||
|
|
28f015569b | ||
|
|
83d1c5c68a |
@@ -27,6 +27,8 @@ jobs:
|
||||
run: make BOARD=esp32:esp32:esp32c3
|
||||
- name: Build firmware for ESP32-S3
|
||||
run: make BOARD=esp32:esp32:esp32s3
|
||||
- name: Build espnow-proxy
|
||||
run: arduino-cli compile --fqbn esp32:esp32:esp32 tools/espnow-proxy
|
||||
- name: Check c_cpp_properties.json
|
||||
run: tools/check_c_cpp_properties.py
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
BOARD = esp32:esp32:d1_mini32:DebugLevel=error
|
||||
BOARD = esp32:esp32:d1_mini32
|
||||
PORT := $(strip $(wildcard /dev/serial/by-id/usb-Silicon_Labs_CP21* /dev/serial/by-id/usb-1a86_USB_Single_Serial_* /dev/cu.usbserial-* /dev/cu.usbmodem*))
|
||||
|
||||
export ARDUINO_NETWORK_CONNECTION_TIMEOUT := 1h
|
||||
|
||||
build: .core .libs
|
||||
arduino-cli compile --fqbn $(BOARD) flix
|
||||
arduino-cli compile --fqbn $(BOARD) --build-property "build.core_debug_level=1" flix
|
||||
|
||||
upload: build
|
||||
arduino-cli upload --fqbn $(BOARD) -p "$(PORT)" flix
|
||||
|
||||
+27
-7
@@ -25,7 +25,7 @@ You can build and upload the firmware using either **Arduino IDE** (easier for b
|
||||
* `FlixPeriph`, the latest version.
|
||||
* `MAVLink`, version 2.0.25.
|
||||
5. Open the `flix/flix.ino` sketch from downloaded firmware sources in Arduino IDE.
|
||||
6. Connect your ESP32 board to the computer and choose correct board type in Arduino IDE (*WEMOS D1 MINI ESP32* for ESP32 Mini) and the port.
|
||||
6. Connect your ESP32 board to the computer and choose correct board type in Arduino IDE (*WEMOS D1 MINI ESP32* for ESP32 Mini, *ESP32S3 Dev Module* for ESP32-S3 Super Mini) and the port.
|
||||
7. Set *Tools* ⇒ *Core Debug Level* to *Error* to see the errors in the serial console. Set *Tools* ⇒ *USB CDC on Boot* to *Enabled* for ESP32-S3/ESP32-C3 boards.
|
||||
8. [Build and upload](https://docs.arduino.cc/software/ide-v2/tutorials/getting-started/ide-v2-uploading-a-sketch) the firmware using Arduino IDE.
|
||||
|
||||
@@ -61,7 +61,7 @@ You can build and upload the firmware using either **Arduino IDE** (easier for b
|
||||
For ESP32-S3/ESP32-C3 boards, set the appropriate [FQBN](https://docs.arduino.cc/arduino-cli/FAQ/#whats-the-fqbn-string) using `BOARD` parameter:
|
||||
|
||||
```bash
|
||||
make BOARD=esp32:esp32:esp32s3:DebugLevel=error,FlashSize=4M,CDCOnBoot=cdc upload
|
||||
make BOARD=esp32:esp32:esp32s3:FlashSize=4M,CDCOnBoot=cdc upload
|
||||
```
|
||||
|
||||
See other available Make commands in [Makefile](../Makefile).
|
||||
@@ -76,8 +76,25 @@ See other available Make commands in [Makefile](../Makefile).
|
||||
In case if using different IMU model than MPU9250, change `imu` variable declaration in the `imu.ino`:
|
||||
|
||||
```cpp
|
||||
ICM20948 imu(SPI); // For ICM-20948
|
||||
MPU6050 imu(Wire); // For MPU-6050
|
||||
ICM20948 imu(SPI); // For ICM-20948 via SPI
|
||||
// or
|
||||
MPU6050 imu(Wire); // For MPU-6050 via I2C
|
||||
```
|
||||
|
||||
If using non-default SPI pins, pass SCK, MISO, and MOSI pin numbers to `SPI.begin` call and SS pin to `imu` constructor like that:
|
||||
|
||||
```cpp
|
||||
ICM20948(SPI, <SS>);
|
||||
// ...
|
||||
SPI.begin(<SCK>, <MISO>, <MOSI>);
|
||||
imu.begin();
|
||||
```
|
||||
|
||||
If using non-default I2C pins, pass SDA and SCL pin numbers to `Wire.setPins` call like that:
|
||||
|
||||
```cpp
|
||||
Wire.begin(<SDA>, <SCL>);
|
||||
imu.begin();
|
||||
```
|
||||
|
||||
### Connect using QGroundControl
|
||||
@@ -105,7 +122,7 @@ To access the console using serial port:
|
||||
To access the console using QGroundControl:
|
||||
|
||||
1. Connect to the drone using QGroundControl app.
|
||||
2. Go to the QGroundControl menu ⇒ *Vehicle Setup* ⇒ *Analyze Tools* ⇒ *MAVLink Console*.
|
||||
2. Go to the QGroundControl menu ⇒ *Analyze Tools* ⇒ *MAVLink Console*.
|
||||
|
||||
<img src="img/cli.png" width="400">
|
||||
|
||||
@@ -333,7 +350,7 @@ To setup ESP-NOW communication:
|
||||
|
||||
1. Flash the second ESP32 board with ESP-NOW proxy sketch: [`tools/espnow-proxy/espnow-proxy.ino`](../tools/espnow-proxy/espnow-proxy.ino). Use Arduino IDE or command line: `make upload_proxy`.
|
||||
|
||||
2. Open Serial Monitor or use `make monitor` command. The ESP32 will print its MAC address and generated encryption key, for example:
|
||||
2. Open Serial Monitor in Arduino IDE or use `make monitor` command. The ESP32 will print its MAC address and generated encryption key, for example:
|
||||
|
||||
```
|
||||
espnow 7a:c8:e3:eb:bf:e9 &PiuSysxP9+$L&5E
|
||||
@@ -352,7 +369,10 @@ To setup ESP-NOW communication:
|
||||
* Type: Serial.
|
||||
* Serial Port: choose the port of the proxy ESP32 board, e. g. `/dev/cu.usbserial-0001`.
|
||||
* Baud Rate: 115200.
|
||||
5. Click *Save*. QGroundControl should connect to the drone using ESP-NOW and begin showing the telemetry.
|
||||
5. Click *Save*, click *Connect*. QGroundControl should connect to the drone using ESP-NOW and begin showing the telemetry.
|
||||
|
||||
> [!TIP]
|
||||
> Make sure Arduino IDE is not running when using ESP-NOW proxy board, as it may block it.
|
||||
|
||||
## Flight log
|
||||
|
||||
|
||||
+24
-5
@@ -6,10 +6,10 @@
|
||||
#include "pid.h"
|
||||
#include "vector.h"
|
||||
#include "util.h"
|
||||
#include "lpf.h"
|
||||
#include "filter.h"
|
||||
|
||||
extern const int MOTOR_REAR_LEFT, MOTOR_REAR_RIGHT, MOTOR_FRONT_RIGHT, MOTOR_FRONT_LEFT;
|
||||
extern const int RAW, ACRO, STAB, AUTO;
|
||||
extern const int RAW, ACRO, STAB, AUTO, POS;
|
||||
extern const int W_AP, W_STA, W_ESPNOW;
|
||||
extern float t, dt, loopRate;
|
||||
extern uint16_t channels[16];
|
||||
@@ -50,8 +50,14 @@ const char* motd =
|
||||
"sta <ssid> <password> - configure Wi-Fi client mode\n"
|
||||
"espnow <mac> [<key>] - configure ESP-NOW peer\n"
|
||||
"mot - show motor output\n"
|
||||
"log [dump] - print log header [and data]\n"
|
||||
"mfr/mfl/mrr/mrl [<thrust>] - test motor (remove props)\n"
|
||||
"log [dump] - print log header [and data]\n"
|
||||
"log - show log info\n"
|
||||
"log header - show log header\n"
|
||||
"log reset - reset log\n"
|
||||
"log <name> <rate> - setup log topic rate\n"
|
||||
"l <str> - show log values starting with str\n"
|
||||
"l expose <name> - expose log value to telemetry\n"
|
||||
"sys - show system info\n"
|
||||
"reset - reset drone's state\n"
|
||||
"reboot - reboot the drone\n";
|
||||
@@ -128,6 +134,8 @@ void doCommand(String str, bool echo = false) {
|
||||
mode = ACRO;
|
||||
} else if (command == "auto") {
|
||||
mode = AUTO;
|
||||
} else if (command == "pos") {
|
||||
mode = POS;
|
||||
} else if (command == "rc") {
|
||||
print("channels: ");
|
||||
for (int i = 0; i < 16; i++) {
|
||||
@@ -153,9 +161,18 @@ void doCommand(String str, bool echo = false) {
|
||||
} else if (command == "mot") {
|
||||
print("front-right %g front-left %g rear-right %g rear-left %g\n",
|
||||
motors[MOTOR_FRONT_RIGHT], motors[MOTOR_FRONT_LEFT], motors[MOTOR_REAR_RIGHT], motors[MOTOR_REAR_LEFT]);
|
||||
} else if (command == "log") {
|
||||
} else if (command == "log" && arg0 == "") {
|
||||
printLogInfo();
|
||||
} else if (command == "log" && arg1 != "") {
|
||||
configLogThrottle(arg0.c_str(), arg1.toFloat());
|
||||
} else if (command == "log" && arg0 == "header") {
|
||||
printLogHeader();
|
||||
if (arg0 == "dump") printLogData();
|
||||
} else if (command == "log" && arg0 == "reset") {
|
||||
resetLog();
|
||||
} else if (command == "l" && arg0 == "expose" && arg1 != "") {
|
||||
exposeLogValue(arg1.c_str());
|
||||
} else if (command == "l") {
|
||||
printLogValues(arg0.c_str());
|
||||
} else if (command == "cr") {
|
||||
calibrateRC();
|
||||
} else if (command == "ca") {
|
||||
@@ -174,6 +191,8 @@ void doCommand(String str, bool echo = false) {
|
||||
print("Temperature: %.1f °C\n", temperatureRead());
|
||||
print("Total RAM: %d KB\n", ESP.getHeapSize() / 1024);
|
||||
print("Free heap: %d KB\n", ESP.getFreeHeap() / 1024);
|
||||
print("PSRAM: %d KB\n", ESP.getPsramSize() / 1024);
|
||||
print("Free PSRAM: %d KB\n", ESP.getFreePsram() / 1024);
|
||||
print("Firmware: " __DATE__ " " __TIME__ "\n");
|
||||
// Print tasks table
|
||||
print("Num Task MinSt Prio Core CPU%%\n");
|
||||
|
||||
+15
-3
@@ -6,7 +6,7 @@
|
||||
#include "vector.h"
|
||||
#include "quaternion.h"
|
||||
#include "pid.h"
|
||||
#include "lpf.h"
|
||||
#include "filter.h"
|
||||
#include "util.h"
|
||||
|
||||
#define PITCHRATE_P 0.05
|
||||
@@ -34,7 +34,7 @@
|
||||
#define TILT_MAX radians(30)
|
||||
#define RATES_D_LPF_ALPHA 0.2 // cutoff frequency ~ 40 Hz
|
||||
|
||||
const int RAW = 0, ACRO = 1, STAB = 2, AUTO = 3; // flight modes
|
||||
const int RAW = 0, ACRO = 1, STAB = 2, AUTO = 3, POS = 4;
|
||||
int mode = STAB;
|
||||
bool armed = false;
|
||||
|
||||
@@ -56,6 +56,7 @@ int flightModes[] = {STAB, STAB, STAB}; // map for rc mode switch
|
||||
|
||||
extern const int MOTOR_REAR_LEFT, MOTOR_REAR_RIGHT, MOTOR_FRONT_RIGHT, MOTOR_FRONT_LEFT;
|
||||
extern float controlRoll, controlPitch, controlThrottle, controlYaw, controlMode;
|
||||
extern Vector position, positionTarget;
|
||||
|
||||
void control() {
|
||||
interpretControls();
|
||||
@@ -79,7 +80,18 @@ void interpretControls() {
|
||||
|
||||
thrustTarget = controlThrottle;
|
||||
|
||||
if (mode == STAB) {
|
||||
if (mode == POS) {
|
||||
if (controlRoll != 0 || controlPitch != 0) {
|
||||
positionTarget.x = NAN;
|
||||
positionTarget.y = NAN;
|
||||
} else if (invalid(positionTarget.x) || invalid(positionTarget.y)) {
|
||||
// reset position target
|
||||
positionTarget.x = position.x;
|
||||
positionTarget.y = position.y;
|
||||
}
|
||||
}
|
||||
|
||||
if (mode == STAB || (mode == POS && invalid(positionTarget.x))) {
|
||||
float yawTarget = attitudeTarget.getYaw();
|
||||
if (!armed || invalid(yawTarget) || controlYaw != 0) yawTarget = attitude.getYaw(); // reset yaw target
|
||||
attitudeTarget = Quaternion::fromEuler(Vector(controlRoll * tiltMax, controlPitch * tiltMax, yawTarget));
|
||||
|
||||
+9
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
#include "quaternion.h"
|
||||
#include "vector.h"
|
||||
#include "lpf.h"
|
||||
#include "filter.h"
|
||||
#include "util.h"
|
||||
|
||||
Vector rates; // estimated angular rates, rad/s
|
||||
@@ -15,16 +15,24 @@ bool landed;
|
||||
float accWeight = 0.003;
|
||||
float levelWeight = 0.0002;
|
||||
LowPassFilter<Vector> ratesFilter(0.2); // cutoff frequency ~ 40 Hz
|
||||
NotchFilter<Vector> ratesNotch(382, 0);
|
||||
|
||||
void setupEstimate() {
|
||||
print("Setup estimation\n");
|
||||
ratesNotch.reset();
|
||||
}
|
||||
|
||||
void estimate() {
|
||||
applyGyro();
|
||||
applyAcc();
|
||||
applyLevel();
|
||||
estimatePosition();
|
||||
}
|
||||
|
||||
void applyGyro() {
|
||||
// filter gyro to get angular rates
|
||||
rates = ratesFilter.update(gyro);
|
||||
rates = ratesNotch.update(rates);
|
||||
|
||||
// apply rates to attitude
|
||||
attitude = Quaternion::rotate(attitude, Quaternion::fromRotationVector(rates * dt));
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// Copyright (c) 2023 Oleg Kalachev <okalachev@gmail.com>
|
||||
// Repository: https://github.com/okalachev/flix
|
||||
|
||||
// Low pass and notch filters
|
||||
|
||||
#pragma once
|
||||
|
||||
template <typename T> // Using template to make the filter usable for scalar and vector values
|
||||
class LowPassFilter {
|
||||
public:
|
||||
float alpha; // smoothing constant, 1 means filter disabled
|
||||
T output;
|
||||
|
||||
LowPassFilter(float alpha): alpha(alpha) {};
|
||||
|
||||
T update(const T input) {
|
||||
if (!init) {
|
||||
init = true;
|
||||
return output = input;
|
||||
}
|
||||
return output += alpha * (input - output);
|
||||
}
|
||||
|
||||
void setCutOffFrequency(float cutOffFreq, float dt) {
|
||||
alpha = 1 - exp(-2 * PI * cutOffFreq * dt);
|
||||
}
|
||||
|
||||
void reset() {
|
||||
init = false;
|
||||
}
|
||||
|
||||
private:
|
||||
bool init = false;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class NotchFilter {
|
||||
public:
|
||||
float frequency;
|
||||
float bandwidth;
|
||||
T output;
|
||||
|
||||
NotchFilter(float frequency, float bandwidth): frequency(frequency), bandwidth(bandwidth) {
|
||||
reset();
|
||||
};
|
||||
|
||||
T update(const T input) {
|
||||
if (frequency <= 0 || bandwidth <= 0) return input;
|
||||
|
||||
if (!init) {
|
||||
init = true;
|
||||
x1 = x2 = input;
|
||||
y1 = y2 = input;
|
||||
return output = input;
|
||||
}
|
||||
|
||||
output = b0 * input + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
|
||||
|
||||
x2 = x1;
|
||||
x1 = input;
|
||||
y2 = y1;
|
||||
y1 = output;
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
const float dt = 0.001f;
|
||||
float f = frequency;
|
||||
float bw = bandwidth;
|
||||
if (f < 0) f = 0;
|
||||
if (bw < 1e-6f) bw = 1e-6f;
|
||||
|
||||
float q = f / bw;
|
||||
if (q < 1e-3f) q = 1e-3f;
|
||||
|
||||
const float w0 = 2.0f * PI * f * dt;
|
||||
const float c = cos(w0);
|
||||
const float s = sin(w0);
|
||||
const float alpha = s / (2.0f * q);
|
||||
|
||||
const float a0 = 1.0f + alpha;
|
||||
const float invA0 = 1.0f / a0;
|
||||
|
||||
b0 = 1.0f * invA0;
|
||||
b1 = -2.0f * c * invA0;
|
||||
b2 = 1.0f * invA0;
|
||||
a1 = -2.0f * c * invA0;
|
||||
a2 = (1.0f - alpha) * invA0;
|
||||
|
||||
init = false;
|
||||
}
|
||||
|
||||
private:
|
||||
float b0, b1, b2, a1, a2;
|
||||
T x1, x2, y1, y2;
|
||||
bool init = false;
|
||||
};
|
||||
+3
-1
@@ -26,6 +26,8 @@ void setup() {
|
||||
setupWiFi();
|
||||
setupIMU();
|
||||
setupRC();
|
||||
setupEstimate();
|
||||
setupLog();
|
||||
setLED(false);
|
||||
print("Initializing complete\n");
|
||||
}
|
||||
@@ -40,6 +42,6 @@ void loop() {
|
||||
handleInput();
|
||||
processMavlink();
|
||||
readVoltage();
|
||||
logData();
|
||||
loopLog();
|
||||
syncParameters();
|
||||
}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
#include <SPI.h>
|
||||
#include <FlixPeriph.h>
|
||||
#include "vector.h"
|
||||
#include "lpf.h"
|
||||
#include "filter.h"
|
||||
#include "util.h"
|
||||
|
||||
MPU9250 imu(SPI);
|
||||
|
||||
+241
-41
@@ -1,77 +1,277 @@
|
||||
// Copyright (c) 2023 Oleg Kalachev <okalachev@gmail.com>
|
||||
// Repository: https://github.com/okalachev/flix
|
||||
|
||||
// In-RAM logging
|
||||
// Logging subsystem
|
||||
|
||||
#include "vector.h"
|
||||
#include "util.h"
|
||||
|
||||
#define LOG_RATE 100
|
||||
#define LOG_DURATION 10
|
||||
#define LOG_SIZE LOG_DURATION * LOG_RATE
|
||||
int logMemory = -1; // 0 - RAM, 1 - PSRAM, -1 - disabled
|
||||
float logUsage = 0.5; // fraction of free memory to use for log
|
||||
|
||||
Vector attitudeEuler;
|
||||
Vector attitudeTargetEuler;
|
||||
|
||||
struct LogEntry {
|
||||
struct LogValue {
|
||||
const char *name;
|
||||
float *value;
|
||||
Value value;
|
||||
float lastValue = NAN;
|
||||
bool logged = true; // if false, use only for triggering log update
|
||||
LogValue() : name(nullptr), value() {}; // empty value constructor
|
||||
template <typename T>
|
||||
LogValue(const char *name, T value, bool logged = true) : name(name), value(value), logged(logged) {};
|
||||
};
|
||||
|
||||
LogEntry logEntries[] = {
|
||||
{"t", &t},
|
||||
struct LogTopic {
|
||||
LogValue values[10];
|
||||
int length = 0; // number of logged values
|
||||
float throttle; // max update rate, Hz
|
||||
float lastUpdate = -INFINITY;
|
||||
|
||||
LogTopic(float throttle, LogValue v0, LogValue v1 = {}, LogValue v2 = {}, LogValue v3 = {}, LogValue v4 = {}, LogValue v5 = {}, LogValue v6 = {}, LogValue v7 = {}, LogValue v8 = {}, LogValue v9 = {}) :
|
||||
throttle(throttle), values{v0, v1, v2, v3, v4, v5, v6, v7, v8, v9} {
|
||||
// Count logged values
|
||||
for (auto& v : values) {
|
||||
if (v.name == nullptr) break;
|
||||
if (v.logged) length++;
|
||||
}
|
||||
};
|
||||
|
||||
LogTopic(LogValue v0, LogValue v1 = {}, LogValue v2 = {}, LogValue v3 = {}, LogValue v4 = {}, LogValue v5 = {}, LogValue v6 = {}, LogValue v7 = {}, LogValue v8 = {}, LogValue v9 = {}) :
|
||||
LogTopic(INFINITY, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {};
|
||||
};
|
||||
|
||||
LogTopic logTopics[] = {
|
||||
// time
|
||||
LogTopic({"t", &t}), // must be the first topic
|
||||
LogTopic(1, {"loopRate", &loopRate}),
|
||||
|
||||
// imu
|
||||
LogTopic(
|
||||
{"gyro.x", &gyro.x},
|
||||
{"gyro.y", &gyro.y},
|
||||
{"gyro.z", &gyro.z}),
|
||||
|
||||
LogTopic(50,
|
||||
{"acc.x", &acc.x},
|
||||
{"acc.y", &acc.y},
|
||||
{"acc.z", &acc.z}),
|
||||
|
||||
LogTopic(10,
|
||||
{"gyroBias.x", &gyroBias.x},
|
||||
{"gyroBias.y", &gyroBias.y},
|
||||
{"gyroBias.z", &gyroBias.z}),
|
||||
|
||||
// estimation
|
||||
LogTopic(50,
|
||||
{"rates.x", &rates.x},
|
||||
{"rates.y", &rates.y},
|
||||
{"rates.z", &rates.z},
|
||||
{"attitude.roll", []() { return attitude.getRoll(); }},
|
||||
{"attitude.pitch", []() { return attitude.getPitch(); }},
|
||||
{"attitude.yaw", []() { return attitude.getYaw(); }}),
|
||||
|
||||
LogTopic(50,
|
||||
{"position.x", &position.x},
|
||||
{"position.y", &position.y},
|
||||
{"position.z", &position.z}),
|
||||
|
||||
// rc
|
||||
LogTopic(10,
|
||||
{"controlTime", &controlTime, false}, // trigger value
|
||||
{"controlRoll", &controlRoll},
|
||||
{"controlPitch", &controlPitch},
|
||||
{"controlYaw", &controlYaw},
|
||||
{"controlThrottle", &controlThrottle}),
|
||||
|
||||
// control
|
||||
LogTopic({"armed", &armed}),
|
||||
LogTopic({"mode", &mode}),
|
||||
|
||||
LogTopic(10,
|
||||
{"ratesTarget.x", &ratesTarget.x},
|
||||
{"ratesTarget.y", &ratesTarget.y},
|
||||
{"ratesTarget.z", &ratesTarget.z},
|
||||
{"attitude.x", &attitudeEuler.x},
|
||||
{"attitude.y", &attitudeEuler.y},
|
||||
{"attitude.z", &attitudeEuler.z},
|
||||
{"attitudeTarget.x", &attitudeTargetEuler.x},
|
||||
{"attitudeTarget.y", &attitudeTargetEuler.y},
|
||||
{"attitudeTarget.z", &attitudeTargetEuler.z},
|
||||
{"thrustTarget", &thrustTarget}
|
||||
{"attitudeTarget.roll", []() { return attitudeTarget.getRoll(); }},
|
||||
{"attitudeTarget.pitch", []() { return attitudeTarget.getPitch(); }},
|
||||
{"attitudeTarget.yaw", []() { return attitudeTarget.getYaw(); }},
|
||||
{"thrustTarget", &thrustTarget}),
|
||||
|
||||
// motors
|
||||
LogTopic(
|
||||
{"motors[0]", &motors[0]},
|
||||
{"motors[1]", &motors[1]},
|
||||
{"motors[2]", &motors[2]},
|
||||
{"motors[3]", &motors[3]}),
|
||||
|
||||
// misc
|
||||
LogTopic(5,
|
||||
{"voltage", &voltage},
|
||||
{"temp", &temperatureRead},
|
||||
{"imuTemp", []() { return imu.getTemp(); }}),
|
||||
};
|
||||
|
||||
const int logColumns = sizeof(logEntries) / sizeof(logEntries[0]);
|
||||
float logBuffer[LOG_SIZE][logColumns];
|
||||
void *logBuffer; // buffer for log data
|
||||
size_t logCapacity;
|
||||
size_t logCursor = 0;
|
||||
size_t logLength = 0;
|
||||
LogValue *logExposed = nullptr; // log values exposed to telemetry
|
||||
|
||||
void prepareLogData() {
|
||||
attitudeEuler = attitude.toEuler();
|
||||
attitudeTargetEuler = attitudeTarget.toEuler();
|
||||
void setupLog() {
|
||||
print("Setup log\n");
|
||||
|
||||
free(logBuffer); // when reconfiguring
|
||||
logBuffer = nullptr;
|
||||
logCursor = 0;
|
||||
logLength = 0;
|
||||
|
||||
if (logMemory == 0) {
|
||||
logCapacity = ESP.getFreeHeap() * logUsage;
|
||||
logBuffer = (uint8_t *)calloc(logCapacity, 1);
|
||||
} else if (logMemory == 1) {
|
||||
logCapacity = ESP.getFreePsram() * logUsage;
|
||||
logBuffer = (uint8_t *)heap_caps_calloc(logCapacity, 1, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
|
||||
}
|
||||
}
|
||||
|
||||
void logData() {
|
||||
if (!armed) return;
|
||||
static int logPointer = 0;
|
||||
static Rate period(LOG_RATE);
|
||||
if (!period) return;
|
||||
void loopLog() {
|
||||
if (logBuffer == nullptr || !armed) return;
|
||||
|
||||
prepareLogData();
|
||||
if (!logLength) resetLog(); // reset state on first log write
|
||||
|
||||
for (int i = 0; i < logColumns; i++) {
|
||||
logBuffer[logPointer][i] = *logEntries[i].value;
|
||||
static Rate sync(2);
|
||||
if (sync) {
|
||||
const uint8_t marker[] = {0x1A, 0x91, 0x4F, 0xF6, 0x7F};
|
||||
writeLog(&marker, sizeof(marker)); // write sync marker
|
||||
}
|
||||
|
||||
logPointer++;
|
||||
if (logPointer >= LOG_SIZE) {
|
||||
logPointer = 0;
|
||||
for (uint8_t i = 0; i < sizeof(logTopics) / sizeof(logTopics[0]); i++) {
|
||||
LogTopic& topic = logTopics[i];
|
||||
if (t - topic.lastUpdate < 1 / topic.throttle) continue; // throttle topic
|
||||
if (!isTopicUpdated(i)) continue; // skip if topic was't updated
|
||||
|
||||
topic.lastUpdate = t;
|
||||
writeLog(&i, sizeof(i)); // write topic index
|
||||
|
||||
for (auto& value : topic.values) {
|
||||
if (value.name == nullptr) break;
|
||||
if (!value.logged) continue;
|
||||
value.lastValue = value.value.get();
|
||||
writeLog(&value.lastValue, sizeof(float)); // write value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void resetLog() {
|
||||
for (auto& topic : logTopics) {
|
||||
topic.lastUpdate = -INFINITY;
|
||||
for (auto& value : topic.values) {
|
||||
value.lastValue = NAN;
|
||||
}
|
||||
}
|
||||
logCursor = 0;
|
||||
logLength = 0;
|
||||
}
|
||||
|
||||
void writeLog(const void *data, size_t size) {
|
||||
size_t first = min(size, logCapacity - logCursor);
|
||||
size_t second = size - first;
|
||||
memcpy(logBuffer + logCursor, data, first);
|
||||
logCursor = (logCursor + first) % logCapacity;
|
||||
if (second > 0) {
|
||||
memcpy(logBuffer + logCursor, data + first, second);
|
||||
logCursor = (logCursor + second) % logCapacity;
|
||||
}
|
||||
logLength = min(logLength + size, logCapacity);
|
||||
}
|
||||
|
||||
void readLog(void *data, size_t position, size_t size) {
|
||||
if (logLength == logCapacity) {
|
||||
position = (logCursor + position) % logCapacity;
|
||||
}
|
||||
size_t first = min(size, logCapacity - position);
|
||||
size_t second = size - first;
|
||||
memcpy(data, logBuffer + position, first);
|
||||
if (second > 0) {
|
||||
memcpy(data + first, logBuffer, second);
|
||||
}
|
||||
}
|
||||
|
||||
bool isTopicUpdated(const uint8_t topic) {
|
||||
LogTopic& logTopic = logTopics[topic];
|
||||
bool updated = false;
|
||||
|
||||
for (auto& value : logTopic.values) {
|
||||
if (value.name == nullptr) break;
|
||||
float v = value.value.get();
|
||||
if (!floatEquals(value.lastValue, v)) {
|
||||
value.lastValue = v;
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
void printLogInfo() {
|
||||
if (logMemory == -1) return print("Log: disabled\n");
|
||||
|
||||
print("Memory: %s\n", logMemory == 0 ? "RAM" : "PSRAM");
|
||||
print("Usage: %.f%%\n", logUsage * 100);
|
||||
print("Capacity: %u bytes\n", (unsigned)logCapacity);
|
||||
print("Used: %u bytes\n", (unsigned)logLength);
|
||||
print("Estimated duration: %d seconds\n", estimateLogDuration());
|
||||
}
|
||||
|
||||
int estimateLogDuration() {
|
||||
float bandwidth = 0;
|
||||
for (LogTopic& topic : logTopics) {
|
||||
float rate = isinf(topic.throttle) ? loopRate : topic.throttle;
|
||||
bandwidth += rate * topic.length * sizeof(float);
|
||||
}
|
||||
return logCapacity / bandwidth;
|
||||
}
|
||||
|
||||
void printLogHeader() {
|
||||
for (int i = 0; i < logColumns; i++) {
|
||||
print("%s%s", logEntries[i].name, i < logColumns - 1 ? "," : "\n");
|
||||
int i = 0;
|
||||
for (auto& topic : logTopics) {
|
||||
print("Topic #%d (%g Hz):\n", i++, topic.throttle);
|
||||
for (auto& value : topic.values) {
|
||||
if (value.name == nullptr) break;
|
||||
print(" %s%s\n", value.name, value.logged ?"" : " (not logged)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void printLogData() {
|
||||
for (int i = 0; i < LOG_SIZE; i++) {
|
||||
if (logBuffer[i][0] == 0) continue; // skip empty records
|
||||
for (int j = 0; j < logColumns; j++) {
|
||||
print("%g%s", logBuffer[i][j], j < logColumns - 1 ? "," : "\n");
|
||||
void printLogValues(const char *filter) {
|
||||
for (LogTopic& topic : logTopics) {
|
||||
for (LogValue& value : topic.values) {
|
||||
if (value.name == nullptr) break;
|
||||
if (strncasecmp(value.name, filter, strlen(filter))) continue;
|
||||
print("%s = %g\n", value.name, value.value.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void configLogThrottle(const char *name, float throttle) {
|
||||
for (LogTopic& topic : logTopics) {
|
||||
for (LogValue& value : topic.values) {
|
||||
if (value.name == nullptr) break;
|
||||
if (strcasecmp(value.name, name) != 0) continue;
|
||||
topic.throttle = throttle;
|
||||
print("Log throttle for %s set to %.1f Hz\n", name, throttle);
|
||||
return;
|
||||
}
|
||||
}
|
||||
print("Log value not found: %s\n", name);
|
||||
}
|
||||
|
||||
void exposeLogValue(const char *name) {
|
||||
for (int i = 0; i < sizeof(logTopics) / sizeof(logTopics[0]); i++) {
|
||||
LogTopic& topic = logTopics[i];
|
||||
for (LogValue& value : topic.values) {
|
||||
if (value.name == nullptr) break;
|
||||
if (strcasecmp(value.name, name) != 0) continue;
|
||||
logExposed = &value;
|
||||
print("Log value %s exposed\n", name);
|
||||
return;
|
||||
}
|
||||
}
|
||||
print("Log value not found: %s\n", name);
|
||||
}
|
||||
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
// Copyright (c) 2023 Oleg Kalachev <okalachev@gmail.com>
|
||||
// Repository: https://github.com/okalachev/flix
|
||||
|
||||
// Low pass filter implementation
|
||||
|
||||
#pragma once
|
||||
|
||||
template <typename T> // Using template to make the filter usable for scalar and vector values
|
||||
class LowPassFilter {
|
||||
public:
|
||||
float alpha; // smoothing constant, 1 means filter disabled
|
||||
T output;
|
||||
|
||||
LowPassFilter(float alpha): alpha(alpha) {};
|
||||
|
||||
T update(const T input) {
|
||||
if (!init) {
|
||||
init = true;
|
||||
return output = input;
|
||||
}
|
||||
return output += alpha * (input - output);
|
||||
}
|
||||
|
||||
void setCutOffFrequency(float cutOffFreq, float dt) {
|
||||
alpha = 1 - exp(-2 * PI * cutOffFreq * dt);
|
||||
}
|
||||
|
||||
void reset() {
|
||||
init = false;
|
||||
}
|
||||
|
||||
private:
|
||||
bool init = false;
|
||||
};
|
||||
+64
-13
@@ -16,6 +16,7 @@ Rate telemetryAttitude(20);
|
||||
Rate telemetryRC(10);
|
||||
Rate telemetryMotors(10);
|
||||
Rate telemetryIMU(15);
|
||||
Rate telemetryTopic(10);
|
||||
|
||||
bool mavlinkConnected = false;
|
||||
String mavlinkPrintBuffer;
|
||||
@@ -84,6 +85,12 @@ void sendMavlink() {
|
||||
0, 0, 0, 0);
|
||||
sendMessage(&msg);
|
||||
}
|
||||
|
||||
if (telemetryTopic && logExposed != nullptr) {
|
||||
mavlink_msg_named_value_float_pack(mavlinkSysId, MAV_COMP_ID_AUTOPILOT1, &msg,
|
||||
time, logExposed->name, logExposed->value.get());
|
||||
sendMessage(&msg);
|
||||
}
|
||||
}
|
||||
|
||||
void sendMessage(const void *msg) {
|
||||
@@ -92,6 +99,26 @@ void sendMessage(const void *msg) {
|
||||
sendWiFi(buf, len);
|
||||
}
|
||||
|
||||
static uint8_t mavlinkBatch[ESP_NOW_MAX_DATA_LEN_V2];
|
||||
static int mavlinkBatchSize = 0;
|
||||
|
||||
void batchMessage(const void *msg) {
|
||||
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
|
||||
int len = mavlink_msg_to_send_buffer(buf, (mavlink_message_t *)msg);
|
||||
|
||||
if (mavlinkBatchSize + len > sizeof(mavlinkBatch)) {
|
||||
sendWiFi(mavlinkBatch, mavlinkBatchSize);
|
||||
mavlinkBatchSize = 0;
|
||||
}
|
||||
memcpy(mavlinkBatch + mavlinkBatchSize, buf, len);
|
||||
mavlinkBatchSize += len;
|
||||
}
|
||||
|
||||
void flushBatchMessages() {
|
||||
sendWiFi(mavlinkBatch, mavlinkBatchSize);
|
||||
mavlinkBatchSize = 0;
|
||||
}
|
||||
|
||||
void receiveMavlink() {
|
||||
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
|
||||
int len = receiveWiFi(buf, MAVLINK_MAX_PACKET_LEN);
|
||||
@@ -169,6 +196,13 @@ void handleMavlink(const void *_msg) {
|
||||
sendMessage(&msg);
|
||||
}
|
||||
|
||||
if (msg.msgid == MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE) {
|
||||
mavlink_vision_position_estimate_t m;
|
||||
mavlink_msg_vision_position_estimate_decode(&msg, &m);
|
||||
Vector pos(m.x, m.y, m.z);
|
||||
correctPosition(pos);
|
||||
}
|
||||
|
||||
if (msg.msgid == MAVLINK_MSG_ID_MISSION_REQUEST_LIST) { // handle to make qgc happy
|
||||
mavlink_mission_request_list_t m;
|
||||
mavlink_msg_mission_request_list_decode(&msg, &m);
|
||||
@@ -196,18 +230,24 @@ void handleMavlink(const void *_msg) {
|
||||
mavlink_msg_set_attitude_target_decode(&msg, &m);
|
||||
if (m.target_system && m.target_system != mavlinkSysId) return;
|
||||
|
||||
// copy attitude, rates and thrust targets
|
||||
ratesTarget.x = m.body_roll_rate;
|
||||
ratesTarget.y = -m.body_pitch_rate; // convert to flu
|
||||
ratesTarget.z = -m.body_yaw_rate;
|
||||
if (!(m.type_mask & ATTITUDE_TARGET_TYPEMASK_ATTITUDE_IGNORE)) {
|
||||
// Attitude control
|
||||
attitudeTarget.w = m.q[0];
|
||||
attitudeTarget.x = m.q[1];
|
||||
attitudeTarget.y = -m.q[2];
|
||||
attitudeTarget.z = -m.q[3];
|
||||
thrustTarget = m.thrust;
|
||||
ratesExtra = Vector(0, 0, 0);
|
||||
ratesExtra.x = m.type_mask & ATTITUDE_TARGET_TYPEMASK_BODY_ROLL_RATE_IGNORE ? 0 : m.body_roll_rate;
|
||||
ratesExtra.y = m.type_mask & ATTITUDE_TARGET_TYPEMASK_BODY_PITCH_RATE_IGNORE ? 0 : -m.body_pitch_rate; // convert to flu
|
||||
ratesExtra.z = m.type_mask & ATTITUDE_TARGET_TYPEMASK_BODY_YAW_RATE_IGNORE ? 0 : -m.body_yaw_rate;
|
||||
} else {
|
||||
// Rates control
|
||||
attitudeTarget.invalidate();
|
||||
ratesTarget.x = m.type_mask & ATTITUDE_TARGET_TYPEMASK_BODY_ROLL_RATE_IGNORE ? ratesTarget.x : m.body_roll_rate;
|
||||
ratesTarget.y = m.type_mask & ATTITUDE_TARGET_TYPEMASK_BODY_PITCH_RATE_IGNORE ? ratesTarget.y : -m.body_pitch_rate;
|
||||
ratesTarget.z = m.type_mask & ATTITUDE_TARGET_TYPEMASK_BODY_YAW_RATE_IGNORE ? ratesTarget.z : -m.body_yaw_rate;
|
||||
}
|
||||
|
||||
if (m.type_mask & ATTITUDE_TARGET_TYPEMASK_ATTITUDE_IGNORE) attitudeTarget.invalidate();
|
||||
thrustTarget = valid(m.thrust) ? m.thrust : thrustTarget;
|
||||
armed = m.thrust > 0;
|
||||
}
|
||||
|
||||
@@ -225,18 +265,29 @@ void handleMavlink(const void *_msg) {
|
||||
armed = motors[0] > 0 || motors[1] > 0 || motors[2] > 0 || motors[3] > 0;
|
||||
}
|
||||
|
||||
if (msg.msgid == MAVLINK_MSG_ID_LOG_REQUEST_LIST) {
|
||||
const uint32_t qgcEpoch = 1262304000; // qgc accepts only timestamps after 2010-01-01
|
||||
mavlink_message_t response;
|
||||
mavlink_msg_log_entry_pack(mavlinkSysId, MAV_COMP_ID_AUTOPILOT1, &response,
|
||||
0, 1, 0, qgcEpoch + t * 60, logLength); // put fake unique date to make qgc happy with saving logs
|
||||
sendMessage(&response);
|
||||
}
|
||||
|
||||
if (msg.msgid == MAVLINK_MSG_ID_LOG_REQUEST_DATA) {
|
||||
mavlink_log_request_data_t m;
|
||||
mavlink_msg_log_request_data_decode(&msg, &m);
|
||||
if (m.target_system && m.target_system != mavlinkSysId) return;
|
||||
|
||||
// Send all log records
|
||||
for (int i = 0; i < sizeof(logBuffer) / sizeof(logBuffer[0]); i++) {
|
||||
mavlink_message_t msg;
|
||||
mavlink_msg_log_data_pack(mavlinkSysId, MAV_COMP_ID_AUTOPILOT1, &msg, 0, i,
|
||||
sizeof(logBuffer[0]), (uint8_t *)logBuffer[i]);
|
||||
sendMessage(&msg);
|
||||
for (int i = 0; i < m.count; i += MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN) {
|
||||
int chunkSize = min(MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN, (int)(m.count - i));
|
||||
mavlink_message_t response;
|
||||
uint8_t data[MAVLINK_MSG_LOG_DATA_FIELD_DATA_LEN];
|
||||
readLog(data, m.ofs + i, chunkSize);
|
||||
mavlink_msg_log_data_pack(mavlinkSysId, MAV_COMP_ID_AUTOPILOT1, &response,
|
||||
m.id, m.ofs + i, chunkSize, data);
|
||||
batchMessage(&response);
|
||||
}
|
||||
flushBatchMessages();
|
||||
}
|
||||
|
||||
// Handle commands
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
|
||||
float motors[4]; // normalized motor thrusts in range [0..1]
|
||||
|
||||
int motorPins[4] = {12, 13, 14, 15}; // default pin numbers
|
||||
int motorPins[4] = {-1, -1, -1, -1}; // default pin numbers
|
||||
int pwmFrequency = 78000;
|
||||
int pwmResolution = 10;
|
||||
int pwmStop = 0;
|
||||
|
||||
+28
-1
@@ -5,14 +5,16 @@
|
||||
|
||||
#include <Preferences.h>
|
||||
#include "util.h"
|
||||
#include "pid.h"
|
||||
|
||||
extern int channelZero[16], channelMax[16];
|
||||
extern int rollChannel, pitchChannel, throttleChannel, yawChannel, armedChannel, modeChannel;
|
||||
extern int rcRxPin, voltagePin;
|
||||
extern int wifiMode, wifiLongRange, udpLocalPort, udpRemotePort, espnowChannel;
|
||||
extern float rcLossTimeout, descendTime;
|
||||
extern float rcLossTimeout, descendTime, disarmTilt;
|
||||
extern float voltageScale;
|
||||
extern LowPassFilter<float> voltageFilter;
|
||||
extern PID posX_PID, posY_PID;
|
||||
|
||||
Preferences storage;
|
||||
|
||||
@@ -59,6 +61,12 @@ Parameter parameters[] = {
|
||||
{"CTL_FLT_MODE_0", &flightModes[0]},
|
||||
{"CTL_FLT_MODE_1", &flightModes[1]},
|
||||
{"CTL_FLT_MODE_2", &flightModes[2]},
|
||||
// position
|
||||
{"POS_XY_P", &posX_PID.p, setupPosition},
|
||||
{"POS_XY_I", &posX_PID.i, setupPosition},
|
||||
{"POS_XY_D", &posX_PID.d, setupPosition},
|
||||
{"POS_XY_WU", &posX_PID.windup, setupPosition},
|
||||
{"POS_XY_D_A", &posX_PID.lpf.alpha, setupPosition},
|
||||
// imu
|
||||
{"IMU_ROT_ROLL", &imuRotation.x},
|
||||
{"IMU_ROT_PITCH", &imuRotation.y},
|
||||
@@ -74,6 +82,8 @@ Parameter parameters[] = {
|
||||
{"EST_ACC_WEIGHT", &accWeight},
|
||||
{"EST_LVL_WEIGHT", &levelWeight},
|
||||
{"EST_RATES_LPF_A", &ratesFilter.alpha},
|
||||
{"EST_RATES_NF_F", &ratesNotch.frequency, setupEstimate},
|
||||
{"EST_RATES_NF_BW", &ratesNotch.bandwidth, setupEstimate},
|
||||
// motors
|
||||
{"MOT_PIN_FL", &motorPins[MOTOR_FRONT_LEFT], setupMotors},
|
||||
{"MOT_PIN_FR", &motorPins[MOTOR_FRONT_RIGHT], setupMotors},
|
||||
@@ -121,6 +131,22 @@ Parameter parameters[] = {
|
||||
{"MAV_RATE_RC", &telemetryRC.rate},
|
||||
{"MAV_RATE_MOT", &telemetryMotors.rate},
|
||||
{"MAV_RATE_IMU", &telemetryIMU.rate},
|
||||
{"MAV_RATE_TOPIC", &telemetryTopic.rate},
|
||||
// log
|
||||
{"LOG_MEMORY", &logMemory, setupLog},
|
||||
{"LOG_USAGE", &logUsage, setupLog},
|
||||
{"LOG_RATE_000", &logTopics[0].throttle},
|
||||
{"LOG_RATE_001", &logTopics[1].throttle},
|
||||
{"LOG_RATE_002", &logTopics[2].throttle},
|
||||
{"LOG_RATE_003", &logTopics[3].throttle},
|
||||
{"LOG_RATE_004", &logTopics[4].throttle},
|
||||
{"LOG_RATE_005", &logTopics[5].throttle},
|
||||
{"LOG_RATE_006", &logTopics[6].throttle},
|
||||
{"LOG_RATE_007", &logTopics[7].throttle},
|
||||
{"LOG_RATE_008", &logTopics[8].throttle},
|
||||
{"LOG_RATE_009", &logTopics[9].throttle},
|
||||
{"LOG_RATE_010", &logTopics[10].throttle},
|
||||
{"LOG_RATE_011", &logTopics[11].throttle},
|
||||
// power
|
||||
{"PWR_VOLT_PIN", &voltagePin, setupPower},
|
||||
{"PWR_VOLT_SCALE", &voltageScale},
|
||||
@@ -128,6 +154,7 @@ Parameter parameters[] = {
|
||||
// safety
|
||||
{"SF_RC_LOSS_TIME", &rcLossTimeout},
|
||||
{"SF_DESCEND_TIME", &descendTime},
|
||||
{"SF_DISARM_TILT", &disarmTilt}
|
||||
};
|
||||
|
||||
void setupParameters() {
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "lpf.h"
|
||||
#include "filter.h"
|
||||
|
||||
class PID {
|
||||
public:
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
#include "vector.h"
|
||||
#include "quaternion.h"
|
||||
#include "pid.h"
|
||||
#include "util.h"
|
||||
|
||||
float mass = 0.065;
|
||||
float motorThrust = 0.031 * ONE_G;
|
||||
float positionWeight = 0.9;
|
||||
float velocityWeight = 0.9;
|
||||
|
||||
PID velX_PID(1.0, 0.0, 0.02);
|
||||
PID velY_PID(1.0, 0.0, 0.02);
|
||||
PID velZ_PID(1.0, 0.0, 0.02);
|
||||
|
||||
// PID posX_PID(1.0, 0.0, 0.0);
|
||||
// PID posY_PID(1.0, 0.0, 0.0);
|
||||
// PID posZ_PID(1.0, 0.0, 0.0);
|
||||
|
||||
PID posX_PID(0.1, 0.0, 0.0);
|
||||
PID posY_PID(0.1, 0.0, 0.0);
|
||||
PID posZ_PID(0.1, 0.0, 0.0);
|
||||
|
||||
Vector acceleration;
|
||||
Vector velocity;
|
||||
Vector position;
|
||||
Vector velocityTarget(NAN, NAN, NAN);
|
||||
Vector positionTarget(NAN, NAN, NAN);
|
||||
|
||||
extern Quaternion attitudeTarget;
|
||||
extern float thrustTarget;
|
||||
|
||||
void setupPosition() {
|
||||
// TODO: posY_PID = posX_PID;
|
||||
// posX_PID.copy(posY_PID);
|
||||
posY_PID.p = posX_PID.p;
|
||||
posY_PID.i = posX_PID.i;
|
||||
posY_PID.d = posX_PID.d;
|
||||
}
|
||||
|
||||
void estimatePosition() {
|
||||
acceleration = Quaternion::rotateVector(acceleration, attitude) + Vector(0, 0, -ONE_G);
|
||||
velocity += acceleration * dt;
|
||||
position += velocity * dt;
|
||||
}
|
||||
|
||||
void correctPosition(Vector& pos) {
|
||||
// position += (pos - position) * positionWeight;
|
||||
position = pos;
|
||||
// positionUpdated = true;
|
||||
|
||||
if (invalid(positionTarget.x) || invalid(positionTarget.y)) return;
|
||||
|
||||
attitudeTarget.setPitch(posX_PID.update(positionTarget.x - position.x));
|
||||
attitudeTarget.setRoll(posY_PID.update(positionTarget.y - position.y));
|
||||
}
|
||||
|
||||
void correctVelocity(Vector& vel) {
|
||||
velocity += (vel - velocity) * velocityWeight;
|
||||
}
|
||||
|
||||
void controlVelocity() {
|
||||
Vector accelerationTarget(
|
||||
velX_PID.update(velocityTarget.x - velocity.x),
|
||||
velY_PID.update(velocityTarget.y - velocity.y),
|
||||
velZ_PID.update(velocityTarget.z - velocity.z)
|
||||
);
|
||||
|
||||
Vector thrustVector = (accelerationTarget + Vector(0, 0, ONE_G)) * mass;
|
||||
|
||||
const Vector up(0, 0, 1);
|
||||
|
||||
attitudeTarget = Quaternion::fromBetweenVectors(up, thrustVector);
|
||||
float maxThrust = motorThrust * 4; // 4 motors
|
||||
thrustTarget = thrustVector.norm() / maxThrust;
|
||||
}
|
||||
|
||||
void controlPosition() {
|
||||
if (positionTarget.invalid()) return;
|
||||
|
||||
velocityTarget = Vector(
|
||||
posX_PID.update(positionTarget.x - position.x),
|
||||
posY_PID.update(positionTarget.y - position.y),
|
||||
posZ_PID.update(positionTarget.z - position.z)
|
||||
);
|
||||
|
||||
controlVelocity();
|
||||
}
|
||||
|
||||
void controlPositionSimple() {
|
||||
if (positionTarget.invalid()) return;
|
||||
|
||||
// straight attitude target control
|
||||
attitudeTarget.setPitch(posX_PID.update(positionTarget.x - position.x));
|
||||
attitudeTarget.setRoll(posY_PID.update(positionTarget.y - position.y));
|
||||
}
|
||||
+2
-2
@@ -5,11 +5,11 @@
|
||||
|
||||
#include <soc/soc.h>
|
||||
#include <soc/rtc_cntl_reg.h>
|
||||
#include "lpf.h"
|
||||
#include "filter.h"
|
||||
#include "util.h"
|
||||
|
||||
float voltage = NAN;
|
||||
LowPassFilter<float> voltageFilter(0.2);
|
||||
LowPassFilter<float> voltageFilter(1);
|
||||
int voltagePin = -1;
|
||||
float voltageScale = 2;
|
||||
|
||||
|
||||
+15
-1
@@ -8,10 +8,12 @@ extern float controlRoll, controlPitch, controlThrottle, controlYaw;
|
||||
|
||||
float rcLossTimeout = 1;
|
||||
float descendTime = 10;
|
||||
float disarmTilt = radians(120);
|
||||
|
||||
void failsafe() {
|
||||
rcLossFailsafe();
|
||||
autoFailsafe();
|
||||
tiltFailsafe();
|
||||
}
|
||||
|
||||
// RC loss failsafe
|
||||
@@ -36,7 +38,7 @@ void descend() {
|
||||
// Allow pilot to interrupt automatic flight
|
||||
void autoFailsafe() {
|
||||
static float roll, pitch, yaw, throttle;
|
||||
if (roll != controlRoll || pitch != controlPitch || yaw != controlYaw || abs(throttle - controlThrottle) > 0.05) {
|
||||
if (abs(roll - controlRoll) > 0.05 || abs(pitch - controlPitch) > 0.05 || abs(yaw - controlYaw) > 0.05 || abs(throttle - controlThrottle) > 0.05) {
|
||||
// controls changed and mode switch is not configured
|
||||
if (mode == AUTO && invalid(controlMode)) mode = STAB; // regain control by the pilot
|
||||
}
|
||||
@@ -45,3 +47,15 @@ void autoFailsafe() {
|
||||
yaw = controlYaw;
|
||||
throttle = controlThrottle;
|
||||
}
|
||||
|
||||
// Disarm if tilted too much
|
||||
void tiltFailsafe() {
|
||||
if (!armed) return;
|
||||
if (mode != STAB) return;
|
||||
|
||||
Vector up = Quaternion::rotateVector(Vector(0, 0, 1), attitude);
|
||||
float tilt = acos(up.z);
|
||||
if (disarmTilt && tilt > disarmTilt) {
|
||||
armed = false;
|
||||
}
|
||||
}
|
||||
|
||||
+43
@@ -64,6 +64,49 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
// Simple variant type for logging and parameters
|
||||
struct Value {
|
||||
enum { EMPTY, FLOAT, INT, BOOL, FLOAT_FN, INT_FN, BOOL_FN } type;
|
||||
union {
|
||||
void *pointer;
|
||||
float *_float;
|
||||
int *_int;
|
||||
bool *_bool;
|
||||
float (*floatFn)();
|
||||
int (*intFn)();
|
||||
bool (*boolFn)();
|
||||
};
|
||||
|
||||
Value() : type(EMPTY), pointer(nullptr) {};
|
||||
Value(float *pt) : type(FLOAT), _float(pt) {};
|
||||
Value(int *pt) : type(INT), _int(pt) {};
|
||||
Value(bool *pt) : type(BOOL), _bool(pt) {};
|
||||
Value(float (*fn)()) : type(FLOAT_FN), floatFn(fn) {};
|
||||
Value(int (*fn)()) : type(INT_FN), intFn(fn) {};
|
||||
Value(bool (*fn)()) : type(BOOL_FN), boolFn(fn) {};
|
||||
|
||||
float get() const {
|
||||
switch (type) {
|
||||
case FLOAT: return *_float;
|
||||
case INT: return *_int;
|
||||
case BOOL: return *_bool ? 1 : 0;
|
||||
case FLOAT_FN: return floatFn();
|
||||
case INT_FN: return intFn();
|
||||
case BOOL_FN: return boolFn() ? 1 : 0;
|
||||
default: return NAN;
|
||||
}
|
||||
};
|
||||
|
||||
void set(float value) const {
|
||||
switch (type) {
|
||||
case FLOAT: *_float = value; break;
|
||||
case INT: *_int = value; break;
|
||||
case BOOL: *_bool = (value != 0); break;
|
||||
default: break;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Rate limiter
|
||||
class Rate {
|
||||
public:
|
||||
|
||||
+2
-2
@@ -58,7 +58,7 @@ void sendWiFi(const uint8_t *buf, int len) {
|
||||
espnow.write(buf, len);
|
||||
|
||||
static Rate discovery(2);
|
||||
if (discovery) espnowBroadcast.write((const uint8_t *)"flix", 4); // broadcast message to help finding this device
|
||||
if (espnow.isEncrypted() && discovery) espnowBroadcast.write((const uint8_t *)"flix", 4); // broadcast message to help finding this device
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ void printWiFiInfo() {
|
||||
print("MAC: %s\n", WiFi.softAPmacAddress().c_str());
|
||||
print("Peer MAC: %s\n", MacAddress(espnow.addr()).toString().c_str());
|
||||
print("Encrypted: %d\n", espnow.isEncrypted());
|
||||
print("Channel: %d\n", espnow.getChannel());
|
||||
print("Channel: %d\n", WiFi.channel());
|
||||
print("Lost packets: %d\n", espnow.lost);
|
||||
} else if (WiFi.getMode() == WIFI_MODE_AP) {
|
||||
print("Mode: Access Point (AP)\n");
|
||||
|
||||
@@ -20,6 +20,10 @@
|
||||
#define radians(deg) ((deg)*DEG_TO_RAD)
|
||||
#define degrees(rad) ((rad)*RAD_TO_DEG)
|
||||
|
||||
#define MALLOC_CAP_SPIRAM (1<<10)
|
||||
#define MALLOC_CAP_8BIT (1<<2)
|
||||
#define ESP_NOW_MAX_DATA_LEN_V2 1470
|
||||
|
||||
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
|
||||
template<typename T> T max(T a, T b) { return a > b ? a : b; }
|
||||
template<typename T> T min(T a, T b) { return a < b ? a : b; }
|
||||
@@ -156,6 +160,8 @@ HardwareSerial Serial, Serial1, Serial2;
|
||||
class EspClass {
|
||||
public:
|
||||
void restart() { Serial.println("Ignore reboot in simulation"); }
|
||||
uint32_t getFreeHeap() { return 300 * 1024; } // assume 300 KB free heap
|
||||
uint32_t getFreePsram() { return 8 * 1024 * 1024; } // assume 8 MB free PSRAM
|
||||
} ESP;
|
||||
|
||||
unsigned long __delayTime = 0;
|
||||
@@ -165,11 +171,16 @@ void delay(uint32_t ms) {
|
||||
__delayTime += ms * 1000;
|
||||
}
|
||||
|
||||
void *heap_caps_calloc(size_t n, size_t size, uint32_t caps) {
|
||||
return calloc(n, size);
|
||||
}
|
||||
|
||||
bool ledcAttach(uint8_t pin, uint32_t freq, uint8_t resolution) { return true; }
|
||||
bool ledcWrite(uint8_t pin, uint32_t duty) { return true; }
|
||||
uint32_t ledcChangeFrequency(uint8_t pin, uint32_t freq, uint8_t resolution) { return freq; }
|
||||
int8_t digitalPinToAnalogChannel(uint8_t pin) { return -1; }
|
||||
uint32_t analogReadMilliVolts(uint8_t pin) { return 0; }
|
||||
float temperatureRead() { return 0; }
|
||||
|
||||
unsigned long __micros;
|
||||
unsigned long __resetTime = 0;
|
||||
|
||||
+17
-2
@@ -9,7 +9,7 @@
|
||||
#include "quaternion.h"
|
||||
#include "Arduino.h"
|
||||
#include "wifi.h"
|
||||
#include "lpf.h"
|
||||
#include "filter.h"
|
||||
|
||||
extern float t, dt;
|
||||
extern float controlRoll, controlPitch, controlYaw, controlThrottle, controlMode;
|
||||
@@ -48,8 +48,17 @@ void normalizeRC();
|
||||
void calibrateRC();
|
||||
void calibrateRCChannel(int*, uint16_t[16], uint16_t[16], const char*);
|
||||
void printRCCalibration();
|
||||
void loopLog();
|
||||
void resetLog();
|
||||
void writeLog(const void *data, size_t size);
|
||||
void readLog(void *data, size_t position, size_t size);
|
||||
bool isTopicUpdated(const uint8_t topic);
|
||||
void printLogInfo();
|
||||
int estimateLogDuration();
|
||||
void printLogHeader();
|
||||
void printLogData();
|
||||
void printLogValues(const char *filter);
|
||||
void configLogThrottle(const char *name, float throttle);
|
||||
void exposeLogValue(const char *name);
|
||||
void processMavlink();
|
||||
void sendMavlink();
|
||||
void sendMessage(const void *msg);
|
||||
@@ -63,6 +72,7 @@ void failsafe();
|
||||
void rcLossFailsafe();
|
||||
void descend();
|
||||
void autoFailsafe();
|
||||
void tiltFailsafe();
|
||||
int parametersCount();
|
||||
const char *getParameterName(int index);
|
||||
float getParameter(int index);
|
||||
@@ -79,3 +89,8 @@ void printIMUInfo() {};
|
||||
void printWiFiInfo() {};
|
||||
void configWiFi(bool, const char*, const char*) { print("Skip WiFi config\n"); };
|
||||
void setWiFiMode(const String& mode) { print("Skip WiFi mode set\n"); };
|
||||
|
||||
class IMU {
|
||||
public:
|
||||
float getTemp() { return 0; }
|
||||
} imu;
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
#include "estimate.ino"
|
||||
#include "safety.ino"
|
||||
#include "log.ino"
|
||||
#include "lpf.h"
|
||||
#include "filter.h"
|
||||
#include "mavlink.ino"
|
||||
#include "motors.ino"
|
||||
#include "parameters.ino"
|
||||
@@ -55,6 +55,7 @@ public:
|
||||
initNode();
|
||||
Serial.begin(0);
|
||||
setupParameters();
|
||||
setupLog();
|
||||
rcRxPin = 1; // set rc pin to enable rc reading
|
||||
gzmsg << "Flix plugin loaded" << endl;
|
||||
}
|
||||
@@ -88,7 +89,7 @@ public:
|
||||
|
||||
applyMotorForces();
|
||||
publishTopics();
|
||||
logData();
|
||||
loopLog();
|
||||
syncParameters();
|
||||
}
|
||||
|
||||
|
||||
+10
-1
@@ -9,6 +9,7 @@ Usage:
|
||||
import csv
|
||||
import json
|
||||
import docopt
|
||||
import math
|
||||
from mcap.writer import Writer
|
||||
|
||||
args = docopt.docopt(__doc__)
|
||||
@@ -39,7 +40,15 @@ channel_id = writer.register_channel(
|
||||
)
|
||||
|
||||
for row in csv_reader:
|
||||
data = {key: float(value) for key, value in zip(header, row)}
|
||||
if row[0] == '': continue
|
||||
data = {}
|
||||
for key, value in zip(header, row):
|
||||
if value == '' or math.isnan(float(value)):
|
||||
data[key] = None
|
||||
else:
|
||||
data[key] = float(value)
|
||||
|
||||
data = {key: float(value) if value != '' else None for key, value in zip(header, row)}
|
||||
timestamp = round(float(row[0]) * 1e9)
|
||||
writer.add_message(channel_id=channel_id, log_time=timestamp, data=json.dumps(data).encode(), publish_time=timestamp,)
|
||||
|
||||
|
||||
@@ -11,18 +11,22 @@
|
||||
#include <Preferences.h>
|
||||
#include "../../flix/util.h"
|
||||
|
||||
const int CHANNEL = 6;
|
||||
const bool DISABLE_SWARM = true;
|
||||
const int CHANNEL = -1; // -1 means auto search
|
||||
char key[ESP_NOW_KEY_LEN + 1] = {0}; // with trailing null
|
||||
|
||||
Preferences storage;
|
||||
|
||||
std::vector<ESPNOWSerial *> peers;
|
||||
bool stop = false;
|
||||
|
||||
void onNewPeer(const esp_now_recv_info_t *info, const uint8_t *data, int len, void *arg) {
|
||||
if (len != 4 || memcmp(data, "flix", 4) != 0) return; // check if discovery message
|
||||
|
||||
if (stop) return;
|
||||
|
||||
Serial.printf("New peer: " MACSTR "\n", MAC2STR(info->src_addr));
|
||||
ESPNOWSerial *link = new ESPNOWSerial(info->src_addr, CHANNEL, WIFI_IF_AP);
|
||||
ESPNOWSerial *link = new ESPNOWSerial(info->src_addr, WiFi.channel(), WIFI_IF_STA);
|
||||
link->begin();
|
||||
link->setKey((const uint8_t *)key);
|
||||
peers.push_back(link);
|
||||
@@ -30,9 +34,8 @@ void onNewPeer(const esp_now_recv_info_t *info, const uint8_t *data, int len, vo
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
WiFi.mode(WIFI_AP);
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.setSleep(false);
|
||||
WiFi.setChannel(CHANNEL);
|
||||
|
||||
ESP_NOW.onNewPeer(onNewPeer, NULL);
|
||||
ESP_NOW.begin();
|
||||
@@ -43,12 +46,6 @@ void setup() {
|
||||
storage.putString("key", key);
|
||||
}
|
||||
strcpy(key, storage.getString("key").c_str());
|
||||
|
||||
// Discover the first peer
|
||||
while (peers.empty()) {
|
||||
Serial.printf("espnow %s %s\n", WiFi.softAPmacAddress().c_str(), key);
|
||||
delay(500);
|
||||
}
|
||||
}
|
||||
|
||||
void generateRandomKey() {
|
||||
@@ -61,6 +58,20 @@ void generateRandomKey() {
|
||||
void loop() {
|
||||
uint8_t buf[5000];
|
||||
|
||||
static int channelIndex = 0;
|
||||
static const int channels[] = {6, 11, 1, 2, 6, 11, 3, 4, 5, 6, 1, 11, 8, 6, 9, 10, 11, 6, 1, 12, 13}; // 6, 1 and 11 are most common
|
||||
|
||||
static unsigned long last = 0;
|
||||
if (!stop && millis() - last > 500) {
|
||||
// Change search channel
|
||||
last = millis();
|
||||
channelIndex = (channelIndex + 1) % (sizeof(channels) / sizeof(channels[0]));
|
||||
int channel = CHANNEL < 0 ? channels[channelIndex] : CHANNEL;
|
||||
Serial.printf("Run on Flix: espnow %s %s\n", WiFi.STA.macAddress().c_str(), key);
|
||||
Serial.printf("Searching channel %d\n", channel);
|
||||
WiFi.setChannel(channel);
|
||||
}
|
||||
|
||||
// Send from Serial to ESP-NOW
|
||||
while (Serial.available() > 0) {
|
||||
int b = Serial.read();
|
||||
@@ -81,6 +92,15 @@ void loop() {
|
||||
// Send from ESP-NOW to Serial
|
||||
for (ESPNOWSerial *link : peers) {
|
||||
int len = link->read(buf, sizeof(buf));
|
||||
if (!stop) {
|
||||
for (int i = 0; i < len; i++) {
|
||||
if (buf[i] == MAVLINK_STX) {
|
||||
// Got MAVLink message, stop discovery
|
||||
Serial.printf("Received MAVLink from " MACSTR "\n", MAC2STR(link->addr()));
|
||||
if (DISABLE_SWARM) stop = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (len > 0) {
|
||||
Serial.write(buf, len);
|
||||
}
|
||||
|
||||
Executable
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""Convert flight from Flix format to CSV
|
||||
|
||||
Usage:
|
||||
log_to_csv.py <input_file>
|
||||
"""
|
||||
|
||||
import os
|
||||
from pyflix import Flix
|
||||
import docopt
|
||||
import struct
|
||||
import csv
|
||||
|
||||
DIR = os.path.dirname(os.path.realpath(__file__))
|
||||
HEADER_FILE = os.path.join(DIR, 'log/log_header.txt')
|
||||
|
||||
# Read log header
|
||||
try:
|
||||
# read from file
|
||||
header = open(HEADER_FILE, 'r').read()
|
||||
except FileNotFoundError:
|
||||
flix = Flix()
|
||||
header = flix.cli('log header') # receive the log schema
|
||||
open(HEADER_FILE, 'w').write(header) # save to file
|
||||
|
||||
# Parse log header
|
||||
topics = []
|
||||
for line in header.splitlines():
|
||||
if not line.startswith(' '):
|
||||
topics.append([])
|
||||
elif 'not logged' not in line:
|
||||
topics[-1].append(line.strip())
|
||||
|
||||
# Read log file
|
||||
args = docopt.docopt(__doc__)
|
||||
input_file = args['<input_file>']
|
||||
outfile_file = input_file + '.csv'
|
||||
data = open(input_file, 'rb').read()
|
||||
|
||||
# Search for sync marker
|
||||
SYNC_MARKER = bytes.fromhex('1A 91 4F F6 7F')
|
||||
sync_offset = data.find(SYNC_MARKER)
|
||||
if sync_offset == -1:
|
||||
raise ValueError('Sync marker not found in log file')
|
||||
data = data[sync_offset + len(SYNC_MARKER):]
|
||||
data = data.replace(SYNC_MARKER, b'') # remove all other sync markers
|
||||
|
||||
header_row = [f'{value}' for topic in topics for value in topic]
|
||||
rows = []
|
||||
|
||||
offset = 0
|
||||
while offset < len(data):
|
||||
try:
|
||||
topic = struct.unpack_from('B', data, offset)[0]
|
||||
offset += 1
|
||||
|
||||
if topic >= len(topics):
|
||||
raise ValueError(f'Invalid topic {topic} at offset {offset}')
|
||||
|
||||
if topic == 0 or not rows:
|
||||
rows.append({})
|
||||
|
||||
for name in topics[topic]:
|
||||
value = struct.unpack_from('<f', data, offset)[0]
|
||||
offset += 4
|
||||
rows[-1][name] = value
|
||||
except struct.error as e:
|
||||
break
|
||||
|
||||
# Write CSV file
|
||||
with open(outfile_file, 'w', newline='') as f:
|
||||
writer = csv.DictWriter(f, fieldnames=header_row, extrasaction='ignore')
|
||||
writer.writeheader()
|
||||
rows = filter(lambda row: float(row.get('t', 0)), rows)
|
||||
writer.writerows(rows)
|
||||
Reference in New Issue
Block a user