204 Commits
Author SHA1 Message Date
Oleg Kalachev bbe753add0 Enable motor pins only for classic esp32 by default
Also simplify flix2 config code.
2026-08-16 01:26:34 +03:00
Oleg Kalachev 815ccfc08f Docs fix 2026-08-16 00:10:19 +03:00
Oleg Kalachev 3f11fa11e8 Test simulation run 2026-08-14 09:41:35 +03:00
Oleg Kalachev a05e35540e Bring back simpler version of Value::set 2026-08-14 06:18:17 +03:00
Oleg Kalachev 6098293776 Utilize Value class in parameters for
Now bool parameters also may be used.
2026-08-14 06:11:43 +03:00
Oleg Kalachev 2d1efac05f Change type hints of the most List arguments to Sequence in pyflix
These arguments are effectively immutable, so Sequence makes more sense - the user may use tuples in addition to lists.
2026-08-14 05:57:58 +03:00
Oleg Kalachev f99a9998b1 Add rates_extra argument to pyflix' set_attitude method
For controlling rates feed forward.
2026-08-14 05:32:39 +03:00
Oleg Kalachev 4d77c6c369 Simply set_attitude_target handler
Rates ignore flags are efficiently the same as zeros, so can be ignored.
2026-08-14 05:21:45 +03:00
Oleg Kalachev 94c70994b6 Fix simulation run 2026-08-14 04:19:25 +03:00
Oleg Kalachev 78be5b3a8d Minor changes 2026-08-14 03:15:27 +03:00
Oleg Kalachev 9b1f0bd593 Remove test line 2026-08-14 03:04:00 +03:00
Oleg Kalachev b72a10dd7b Trigger build 2026-08-14 02:25:29 +03:00
Oleg Kalachev d2d1c74842 Update all used actions
Some of them were deprecated.
2026-08-14 01:51:21 +03:00
Oleg Kalachev 7308159b74 Show cloc diff with the previous commit 2026-08-14 01:41:57 +03:00
Oleg Kalachev 87ce9c20cb Count and print sloc count in tools workflow 2026-08-14 01:30:51 +03:00
Oleg Kalachev d6b9228282 Fix default windup value in pid
INFINITY makes much more sense, since otherwise i term would be ineffective at all by default
2026-08-13 02:21:03 +03:00
Oleg Kalachev f355cc2938 Upload binaries to docs only in my repo and in master and dev branches 2026-08-12 07:19:23 +03:00
Oleg Kalachev 0139d71b12 Show git hash commit in sys command 2026-08-12 01:58:13 +03:00
Oleg Kalachev 58da0b9959 Add binaries to the docs only of DOCS_BINARIES repo variable is truthy 2026-08-11 21:28:16 +03:00
Oleg Kalachev 355f4ad49d Merge remote-tracking branch 'origin/master' into dev 2026-08-11 18:43:18 +03:00
Oleg Kalachev 55398a660d Remove unused variable 2026-08-11 04:59:54 +03:00
Oleg Kalachev 63bbea4d8b Fix 2026-08-11 02:26:20 +03:00
Oleg Kalachev 5543a363b3 Add yaw rate windup parameter 2026-08-11 01:56:49 +03:00
Oleg Kalachev 363c756c00 Fix windup for yaw rate 2026-08-11 01:56:41 +03:00
Oleg Kalachev 57b853361c Fix motor pins for Flix2 2026-08-11 01:55:56 +03:00
Oleg Kalachev ce37e5b724 Simplify parameter defaults definition 2026-08-11 00:48:10 +03:00
Oleg Kalachev 36b050a896 Add config for Flix2 board 2026-08-10 03:52:57 +03:00
Oleg Kalachev 93ebf75a44 Fix 2026-08-10 03:51:16 +03:00
Oleg Kalachev a60c84ce7a Forgotten image 2026-08-10 03:45:38 +03:00
Oleg Kalachev ae8931cb25 Move most parameter defaults to config.h 2026-08-10 03:45:28 +03:00
Oleg Kalachev e6072b0bc4 Make i and d arguments optional in pid constructor 2026-08-10 03:43:37 +03:00
Oleg Kalachev 67e772a23f Update wait-on-check-action version 2026-08-10 03:33:27 +03:00
Oleg Kalachev 04a24c4939 Add minor comment 2026-08-10 03:27:23 +03:00
Oleg Kalachev f62e176313 Update the docs to reflect possibility for using prebuilt binaries 2026-08-10 03:17:32 +03:00
Oleg Kalachev 8ae06eef85 Docs updates 2026-08-10 03:16:54 +03:00
Oleg Kalachev 9a17ca848d Simplify 2026-08-10 02:41:53 +03:00
Oleg Kalachev b8f93becca Make Rate always trigger on first step 2026-08-10 02:31:54 +03:00
Oleg Kalachev 5fc2143994 Make brushless motors separated block to avoid confusion 2026-08-10 02:31:14 +03:00
Oleg Kalachev b7102d395c Make default fqbn plain esp32
It works on d1 as well
2026-08-10 02:15:30 +03:00
Oleg Kalachev 58ea75d335 Fixes 2026-08-10 01:18:29 +03:00
Oleg Kalachev 93b3077fa7 Add I2C pin parameters 2026-08-09 23:59:45 +03:00
Oleg Kalachev 4c74768131 Fixes 2026-08-09 22:42:14 +03:00
Oleg Kalachev 9880eeccd3 Disable imu by default 2026-08-09 20:41:03 +03:00
Oleg Kalachev a26d096dc0 Disable motors by default 2026-08-09 20:40:58 +03:00
Oleg Kalachev 8a91201cf4 Add targets with psram 2026-08-09 06:35:54 +03:00
Oleg Kalachev 51ca049b97 Download binaries to docs site 2026-08-09 04:23:16 +03:00
Oleg Kalachev 2decd2d6dd Fix simulation build 2026-08-08 02:19:38 +03:00
Oleg Kalachev abb2e9f79b Use up-to-date method for installing arduino-cli in simulator ci 2026-08-08 02:19:28 +03:00
Oleg Kalachev 6c907b77f6 Fix simulation build 2026-08-08 01:31:41 +03:00
Oleg Kalachev 0a53170097 Make imu configuration parameters work 2026-08-08 01:24:43 +03:00
Oleg Kalachev 6b36488245 Use dev version of FlixPeriph 2026-08-08 01:21:01 +03:00
Oleg Kalachev f30a182b20 Add parameter WIFI_BROADCAST for always broadcasting mode
May be used in some cases, like multiple gcs
2026-08-08 01:04:20 +03:00
Oleg Kalachev 90b506e084 Allow hot reconnection from another gcs over wifi
Switch back to udp broadcasting if no messages from gcs for 5 seconds
2026-08-07 18:24:23 +03:00
Oleg Kalachev 5f9aae62b9 Upload all binaries to artifacts 2026-08-06 03:04:05 +03:00
Oleg Kalachev 0e0867ceab Merge branch 'master' into dev 2026-08-05 01:26:28 +03:00
Oleg Kalachev 8e276bde38 Add Oleg1405 build 2026-08-04 22:48:39 +03:00
Oleg Kalachev 83aac78cf7 Merge branch 'master' into dev 2026-08-03 16:02:29 +03:00
Oleg Kalachev eb93b0b29d Merge branch 'master' into dev 2026-08-03 16:01:39 +03:00
Oleg Kalachev a5991930d1 Disable voltage lpf by default
Filtering does more harm than good in voltage monitoring.
(alpha = 1 efficiently disables the filter.)
2026-08-03 15:57:29 +03:00
Oleg Kalachev 406f7a4af5 Add tilt disarm failsafe 2026-08-02 02:13:50 +03:00
Oleg Kalachev 5ee6d91440 Don't send discovery message if encrypting is disabled in espnow 2026-08-02 02:07:17 +03:00
Oleg Kalachev 38925d7885 Updates and fixes in usage article 2026-08-02 02:02:28 +03:00
Oleg Kalachev 5c81181221 Add threshold for rc sticks move for quitting auto mode 2026-08-02 01:58:16 +03:00
Oleg Kalachev fd249fcaa6 Add position control demo video to the readme 2026-08-01 22:33:26 +03:00
Oleg Kalachev 9289b042af Add espnow-proxy build to ci 2026-07-17 23:45:54 +03:00
Oleg Kalachev 1203a3ae8f Make imu model and pins configurable using parameters 2026-07-16 23:09:07 +03:00
Oleg Kalachev d48b71fb1a Disable voltage lpf by default
(Setting alpha = 1 efficiently disables the filter.)
Filtering does more harm than good in voltage monitoring.
2026-07-15 18:42:34 +03:00
Oleg Kalachev 8917849711 Remove unneeded declaration from the sim 2026-07-15 18:40:51 +03:00
Oleg Kalachev 1cdc7a8641 Fix rc in simulator
Virtual rc is disabled if rxRxPin < 0
2026-07-15 18:40:35 +03:00
Oleg Kalachev 0439407d76 Remove unneeded declaration from the sim 2026-07-15 18:29:36 +03:00
Oleg Kalachev c2005a2ca2 Fix rc in simulator 2026-07-15 17:40:11 +03:00
Oleg Kalachev 6a804862da Fix simulator build with new logging 2026-07-15 14:17:24 +03:00
Oleg Kalachev 590bfe10b0 Minor doc changes 2026-07-15 10:52:52 +03:00
Oleg Kalachev 70af1a1c09 Remove DebugLevel from fqbn in usage article 2026-07-15 10:38:04 +03:00
Oleg Kalachev 9e9dafbdfb Support feed forward rates in mavlink control 2026-07-15 10:11:15 +03:00
Oleg Kalachev 86a4418813 Move debug level definition from fbqn to arduino-cli commaand 2026-07-13 22:05:31 +03:00
Oleg Kalachev d64bf24c6d Add alicanerus' build 2026-07-08 22:29:33 +03:00
Oleg Kalachev 7c53e88963 Add notch filter for the gyro 2026-07-08 16:07:03 +03:00
Oleg Kalachev 28f015569b Add log reset command to cli 2026-07-08 01:07:59 +03:00
Oleg Kalachev fabd5e072d Fixes in the docs 2026-07-04 21:40:39 +03:00
Oleg Kalachev 1ae85ff118 Add argument to motor testing commands for specifying thrust 2026-07-02 22:22:33 +03:00
Oleg Kalachev 83d1c5c68a Implement entirely new logging subsystem
Make topic-based logging mechanics.
Print any log value to console.
Possibility to expose any logging value to mavlink.
2026-06-30 13:03:43 +03:00
Oleg Kalachev 26a0dd65be Minor fixes and updates 2026-06-30 12:19:29 +03:00
Oleg Kalachev 9d439afd80 Store only changed parameters in flash instead of all
Rationale:
1. Parameters NVS storage is limited and storing unchanged parameters is wasteful.
2. This allows changing parameters in the code without having to erase the flash storage.
3. Updating the firmware version may change the parameter defaults.
2026-06-28 17:21:07 +03:00
Oleg Kalachev 64b21a3a6b Show default parameter values in p command output
Also move float comparing logic to a distinct util function.
2026-06-24 06:42:09 +03:00
Oleg Kalachev 545eed8944 Add Nerush and Konstantinos Paraskevas builds 2026-06-19 05:15:17 +03:00
Oleg Kalachev 518abf1555 Simplify rc code
Utilize the new method for getting channel values.
2026-06-14 04:45:42 +03:00
Oleg Kalachev 17df1c5396 Separate repository vscode settings and local vscode settings
Use dangmai.workspace-default-settings externsion for that.
2026-06-11 20:37:35 +03:00
Oleg Kalachev 8e2ffd7c69 Remove core installation when running the sim
Split `dependencies` target to `core` and `libs` targets.
Move additional urls declaration and connection timeout from arduino-cli.yaml to Makefile for simplicity and transparency.
Update ESP32 core url.
Remove arduino-cli.yaml.
2026-06-10 18:10:42 +03:00
Oleg Kalachev 52b74afba6 Bring back espnow tx buffering keeping resends disabled
Buffering is needed for sending large prints, otherwise the espnow internal buffer overflows.
Make onSent always think there was success send, so there won't be any resends.
Print lost espnow packets count on wifi console command.
2026-06-09 03:23:30 +03:00
Oleg Kalachev 0ca2473655 Make each mavlink message rate configured separately
Add parameters:
* MAV_RATE_ATT - ATTITUDE_QUATERNION rate.
* MAV_RATE_RC - RC_CHANNELS_RAW rate.
* MAV_RATE_MOT - ACTUATOR_CONTROL_TARGET rate.
* MAV_RATE_IMU - SCALED_IMU rate.
2026-06-09 02:59:10 +03:00
Oleg Kalachev b4c2fe3988 Print total RAM in sys command 2026-06-09 02:49:39 +03:00
Oleg Kalachev e51b47b798 Add command for setting the wifi mode easier 2026-06-09 02:44:09 +03:00
Oleg Kalachev 71abe1bcdb Minor changes
Simplify the code, print imu temperature
2026-06-09 02:25:20 +03:00
Oleg Kalachev 0f2e384ce6 Don't apply level correction on idle thrust 2026-06-09 02:12:27 +03:00
Oleg Kalachev 5e153a210d Update ESP32-Core to 3.3.10 2026-06-09 02:05:52 +03:00
Oleg Kalachev 9d47bcb82e Minor changes in docs 2026-05-31 18:10:00 +03:00
Oleg Kalachev 1fafc27b39 Make it possible to unassign motor pin using -1 parameter value 2026-05-30 16:57:27 +03:00
Oleg Kalachev faca48ced3 Replace ps and psq commands with st command + minor changes
Re-arrange commands order.
Make command parser consider \r in addition to \n.
2026-05-30 16:51:15 +03:00
Oleg Kalachev a5dbd2c829 Add erase command to makefile 2026-05-30 16:48:12 +03:00
Oleg Kalachev 59f9528d34 Increase buffer for print, make sys output more correct
usStackHighWaterMark is not stack size, it's the minimum stack size
2026-05-30 11:11:35 +03:00
Oleg Kalachev 607b2ff0b7 Add malagis custom pcb version of Flix project to builds 2026-05-28 20:15:09 +03:00
Oleg Kalachev 22c06f76c4 Add Awab Anas' build 2026-05-28 19:29:05 +03:00
Oleg Kalachev 488ceb3004 Set the debug level to error by default to see the errors 2026-05-28 19:25:29 +03:00
Oleg Kalachev b83c9b3845 Consider mavlink connected only when the gcs message is parsed 2026-05-28 18:41:34 +03:00
Oleg Kalachev 2f4b1423e6 Typo and minor code style changes 2026-05-28 18:39:44 +03:00
Oleg Kalachev 4e32414dae Support ESP-NOW connection in pyflix
Set arbitrary pymavlink connection string using device parameter or FLIX_DEVICE env variable.
pyflix@0.16.
2026-05-28 18:22:16 +03:00
Oleg Kalachev a294883dea Make p command show all parameters starting with the arg 2026-05-27 13:58:51 +03:00
Oleg Kalachev cdfba72a0b Fix simulator run
Add missing extern variables.
Fix warning.
2026-05-27 11:03:50 +03:00
Oleg Kalachev 18e81720e0 Add video of pcb version flights to the readme 2026-05-26 14:23:56 +03:00
Oleg Kalachev 91173d06c9 Various minor changes 2026-05-22 08:03:46 +03:00
Oleg KalachevandGitHub fdcc9533b3 Implement ESP-NOW support (#40) 2026-05-21 10:48:31 +03:00
Oleg Kalachev bd2b1bd5de Improve voltage measurement
Apply PWM_VOLT_PIN without reboot.
Check if the voltage pin can be used with ADC when setting up.
Set voltage to NAN, when it's unknown (including pyflix).
pyflix@0.15.
Don't send BATTERY_STATUS when voltage is unknown.
Add dummy voltage to the simulator.
2026-05-18 00:30:42 +03:00
Oleg Kalachev 4530c05b5c Add Flix 1.5 to builds 2026-05-17 06:46:11 +03:00
Oleg Kalachev 3816ae376f Bring back initializing the lpf with the first input value
It's much better for voltage measuring and slightly better for gyro bias estimation.
2026-05-17 06:21:13 +03:00
Oleg Kalachev 72a72fde80 Some docs improvements 2026-05-14 21:59:15 +03:00
Oleg Kalachev e53051a349 Fix console command parsing 2026-05-13 06:00:51 +03:00
Oleg Kalachev f8a9f1f838 Remove reboot requirement when changing RC_RX_PIN 2026-05-13 01:27:01 +03:00
Oleg Kalachev 76af83fc88 Improve firmware overview article 2026-05-13 00:35:43 +03:00
Oleg Kalachev dd176180a7 Update help message
Remove 'welcome to', add copyright and repo link.
2026-05-12 17:50:28 +03:00
Oleg Kalachev 48c33c7050 Fix and improve wifi subsystem
Fix a fault when wifi is disabled (udp can't be used without wifi).
Print RSSI and channel in wifi command.
2026-05-10 22:39:34 +03:00
Oleg Kalachev 35e94f6ea6 Support ESP32-C3
User Serial1 for rc instead of Serial2, as ESP32-C3 has only 2 Serials.
Add CI build for ESP32-C3.
2026-05-10 21:07:20 +03:00
Oleg Kalachev 1f48e379e3 Improve the rc calibration code
More convenient steps order.
Improve the readability a bit.
2026-05-10 19:05:27 +03:00
Oleg Kalachev ee3c6999ab Add mavlink joystick app usage to the docs 2026-05-10 14:50:27 +03:00
Oleg Kalachev 34c6993842 Some fixes in the docs 2026-05-10 02:33:03 +03:00
Oleg Kalachev b62f2f9427 Rename some wifi parameters for better alphabetical sort 2026-05-09 17:55:55 +03:00
Oleg KalachevandMarina Tikhomirova 7dfef17165 Add Ina Tix' build
Co-authored-by: Marina Tikhomirova <Ina.tix@yandex.ru>
2026-05-09 17:49:59 +03:00
Oleg Kalachev 8c8046676b Simplify port definition in Makefile 2026-05-09 17:14:29 +03:00
Oleg Kalachev 702ec9792e Some updates in troubleshooting article 2026-05-09 15:57:25 +03:00
Oleg Kalachev 06e2047097 Make motor testing signal 0.2 instead of full power
Testing with full power is too dangerous and inconvenient.
2026-05-08 00:53:19 +03:00
Oleg Kalachev 87480476c2 Fix motors pwm frequency for esp32s3 etc in the docs 2026-05-08 00:47:29 +03:00
Oleg Kalachev 68271c508c Print firmware build date and time in sys command 2026-05-08 00:31:51 +03:00
Oleg Kalachev e81e84e7fc Some updates to docs 2026-05-07 20:15:55 +03:00
Oleg Kalachev 5f1a938d4f Fix imu rotation definition
The X axis should be pointing to the mounting holes, not pins side.
2026-05-07 19:54:16 +03:00
Oleg Kalachev bd270db493 Reduce angle drift by adding level correction to the estimator
Leverage a priori knowledge that the drone's average attitude is level.
Explanation: https://t.me/opensourcequadcopter/158.
2026-05-05 21:27:47 +03:00
Oleg Kalachev dbf24ea611 Expose lpf alpha of rate pids to parameters
Add parameters: CTL_R_RATE_D_A, CTL_P_RATE_D_A, CTL_Y_RATE_D_A.
2026-05-03 15:04:16 +03:00
Oleg Kalachev 08683d696d Some updates in the usage doc 2026-05-01 15:26:59 +03:00
Oleg Kalachev 9ca6841558 Exit auto mode when sticks moved only when mode switch is not configured 2026-04-29 15:07:44 +03:00
Oleg Kalachev 28da2d3c8e Fix in pyflix documentation
pyflix@0.14
2026-04-28 20:46:49 +03:00
Oleg Kalachev c6632ae6e4 Add info on setting flight modes using rc mode switch 2026-04-28 20:43:52 +03:00
Oleg Kalachev 35ca754583 Fix Vector::rotationVectorBetween implementation for parallel vectors 2026-04-28 15:38:52 +03:00
Oleg Kalachev 2ccda03573 Implement motors output desaturation
So the drone continues stabilization on max thrust.
2026-04-28 13:23:42 +03:00
Oleg Kalachev 485a39e740 Disable wi-fi power save to improve responsiveness 2026-04-27 16:46:36 +03:00
Oleg Kalachev 9bffe5b52f Some fixes in docs 2026-04-26 06:05:02 +03:00
Oleg Kalachev d6a79d6c66 Pass acc data in mG in SCALED_IMU to comply with mavlink standard
https://mavlink.io/en/messages/common.html#SCALED_IMU
pyflix@0.13
2026-04-24 07:42:39 +03:00
Oleg Kalachev 350a82bfed Minor fix 2026-04-23 15:34:54 +03:00
Oleg Kalachev 6e439859bc Move disabling brown-out code to power subsystem 2026-04-23 15:06:07 +03:00
Oleg Kalachev 835b2243e8 Minor fix in sys command
String works with printf %s, but actually it's a UB.
2026-04-23 07:25:59 +03:00
Oleg Kalachev ed4e2d87d1 Fix imu command output
Gyro field contained filtered gyro instead of scaled only gyro.
2026-04-23 07:12:25 +03:00
Oleg Kalachev 51cd5fc691 Implement battery voltage monitoring
Add power subsystem.
Add PWR_VOLT_PIN, PWR_VOLT_SCALE, PWR_VOLT_LPF_A parameters.
Support BATTERY_STATUS mavlink messages streaming.
Add pw cli command.
Add voltage field to pyflix library.
pyflix@0.12.
2026-04-22 11:35:37 +03:00
Oleg Kalachev d8591ea2a9 Fix working with parameters in pyflix examples
PITCH_P parameter was renamed to CTL_P_P
2026-04-18 05:23:47 +03:00
Oleg Kalachev c434107eaf Add parameter for configuring sbus pin number, disable sbus by default 2026-03-27 00:56:34 +03:00
Oleg Kalachev 814427dbfd Minor docs change 2026-03-27 00:40:19 +03:00
Oleg Kalachev 0730ceeffa Add new user builds 2026-02-21 07:12:36 +03:00
Oleg Kalachev a687303062 Make motor parameters apply without reboot
Add callback to parameter definition to call after parameter is changed.
2026-02-19 04:56:12 +03:00
Oleg Kalachev b2daf2587f Minor parameters code simplifications
readOnly is false by default
INFINITY == INFINITY, so remove redundant check
2026-02-19 02:59:38 +03:00
Oleg Kalachev a8c25d8ac0 Minor updates to usage article 2026-02-04 17:52:23 +03:00
Oleg Kalachev 3e49d41986 Make rc channel numbers and calibration params use int instead of float
As parameter subsystems supports int now, and int is much more natural here.
2026-02-02 20:36:22 +03:00
Oleg Kalachev 67430c7aac Several minor changes 2026-02-02 18:46:36 +03:00
Oleg Kalachev 3631743a29 Drop messages from another systems in pyflix
We shouldn't pass messages where system id != our system id. 
This change may be useful when there are many drones in one network.
2026-02-02 18:28:20 +03:00
Oleg Kalachev 3dde380bb7 Add parameters for list of modes bound to rc switch
Parameters: CTL_FLT_MODE_0, CTL_FLT_MODE_1, CTL_FLT_MODE_2.
Also fix a bug with incorrect choosing the mode from controlMode.
2026-01-27 16:38:20 +03:00
Oleg Kalachev 377b21429b Fix error when launching the sim
Also make the parameters WIFI_LOC_PORT and WIFI_REM_PORT work in the sim.
2026-01-27 16:32:52 +03:00
Oleg Kalachev 1ac443d6f8 Add a build by Arky Matsekh 2026-01-27 15:17:58 +03:00
Oleg Kalachev 964c0f7bc1 Make setting parameter in console printing actual parameter value.
In some cases, it would not be equal to the requested value.
2026-01-27 09:28:01 +03:00
Oleg Kalachev 40bdaacedb Make motor subsystem configurable using parameters
Motor pins: MOT_PIN_FL, MOT_PIN_FR, MOT_PIN_RL, MOT_PIN_RR.
PWM configuration: MOT_PWM_FREQ, MOT_PWM_RES, MOT_PWM_STOP, MOT_PWM_MIN, MOT_PWM_MAX.
MOT_PWM_MAX = -1 chooses duty cycle mode for brushed motors (default).
2026-01-27 08:40:52 +03:00
Oleg Kalachev 7d74f3d5cd Minor docs fixes 2026-01-27 07:21:21 +03:00
Oleg Kalachev 9fd35ba361 Simplify lpf filter code
Begin with zero instead of the initializing value, as the latter doesn't make much sense in practice, but complicates the code much.
2026-01-24 09:43:46 +03:00
Oleg Kalachev ca50f75576 Various minor fixes 2026-01-24 09:34:16 +03:00
Oleg Kalachev e47a31f981 Fix mavlink parameter set acknowledgement value
If the parameter is integer the acknowledgement should contain the rounded value.
2026-01-24 09:32:49 +03:00
Oleg Kalachev 7ad3022798 Add parameter for configuring gyro bias lpf
+ reset the filter on `reset` command
2026-01-24 09:31:32 +03:00
Oleg Kalachev 5b654e4d8e Update ESP32-Core to 3.3.6 2026-01-23 02:41:43 +03:00
Oleg Kalachev cf10ec6161 Update MAVLink-Arduino to 2.0.16 2026-01-23 01:11:35 +03:00
Oleg Kalachev 6d01cd2e79 Make failsafe configurable using parameters
SF_RC_LOSS_TIME - time without rc to activate failsafe.
SD_DESCEND_TIME - total time to decrease the throttle to zero.
Make controlTime nan on the start to simplify the logic.
2026-01-22 23:57:52 +03:00
Oleg Kalachev 0abb18c616 Make parameter names case-insensitive
+ minor fix
2026-01-22 23:11:47 +03:00
Oleg Kalachev 30326a5662 Add parameters for configuring the mavlink subsystem
MAV_SYS_ID - mavlink system id.
MAV_RATE_SLOW - rate of slow telemetry (e. g. heartbeats).
MAV_RATE_FAST - rate of fast telemetry (e. g. attitude, imu data).
2026-01-22 23:04:45 +03:00
Oleg Kalachev dd3575174b Add wifi configuration using parameters and cli
Add console commands to setup wifi.
Add a parameter for choosing between STA and AP mode.
Add parameters for udp ports.
Remove WIFI_ENABLED macro.
2026-01-22 22:58:43 +03:00
Oleg Kalachev c0f3301da4 Support integer parameters in addition to floats
The variable pointer is stored as a union field.
If `.integer` field is true, then integer pointer should be used.
Interfaces to parameters (cli and mavlink) keep working using floats.
Setting a non-finite value to int parameter will cause an error.
`.value` field is renamed to `.cache`.
2026-01-22 22:54:05 +03:00
a.golubtsovandOleg Kalachev a6bad3a69b Add log dir creation before log writing 2026-01-22 17:56:23 +03:00
Oleg Kalachev 9a9bd07251 Add correct attitude estimation video to the usage article 2026-01-15 23:46:23 +03:00
Oleg Kalachev 28f5855a57 Re-arrange control.ino declarations to make a bit more sensible
So the control command is above the PID controllers.
2026-01-13 17:43:53 +03:00
Oleg Kalachev 7e24ee30f7 Documentation and book updates
Improve the main list of features.
Use lowercase imu variable for consistency with the firmware code.
Minor fixes.
2026-01-13 17:26:40 +03:00
Oleg Kalachev 2a8faf5759 Fix logo svg slightly 2026-01-08 19:45:08 +03:00
Oleg Kalachev f4e58a652a Add project logo 2026-01-08 17:58:59 +03:00
Oleg Kalachev 6c46328da1 Minor doc fixes 2026-01-04 15:01:53 +03:00
Oleg Kalachev c8e5e08b03 Move all global variable declarations to the appropriate subsystems
As it makes the subsystems code easier to understand.
Declare the most used variables in main sketch file as forward declarations.
Make all control input zero by default (except controlMode).
Minor changes.
2026-01-03 13:28:18 +03:00
Oleg Kalachev a5e3dfcf69 Some updates to the docs 2026-01-03 12:18:47 +03:00
Oleg Kalachev d6e8be0c05 Add parameters for easier IMU orientation definition 2025-12-26 21:14:15 +03:00
Oleg Kalachev 68d16855df Add motors rotation diagram to usage article 2025-12-25 07:22:09 +03:00
Oleg Kalachev 0547ea548b Add parameters for acc weight and rates lpf alpha 2025-12-24 05:43:55 +03:00
Oleg Kalachev c02dba6812 Rename gyroCalibrationFilter to gyroBiasFilter
Which seems a better name
2025-12-24 05:36:43 +03:00
Oleg Kalachev f1dc4a0400 Updates to user builds article 2025-12-17 02:21:51 +03:00
Oleg Kalachev 158827ac55 Add new user builds, add school 548 course overview
+ minor doc fixes.
2025-12-13 21:09:33 +03:00
Oleg Kalachev 36ca30c3e4 Minor docs fix 2025-11-27 18:34:32 +03:00
Oleg Kalachev 48711b55e1 Add tip about CNT_TILT_MAX parameter to the simulator article 2025-11-26 17:34:08 +03:00
Oleg Kalachev 4d583185a9 Rename manual mode to raw mode
Make it callable from the console.
Increase the coefficient.
Corresponding change in pyflix.
pyflix@0.11.
2025-11-25 04:44:16 +03:00
Oleg Kalachev d757ffa853 Move yaw dead zone handling from mavlink to control subsystem
So yaw dead zone works the same for rc and mavlink.
2025-11-22 05:11:46 +03:00
Oleg Kalachev 5352386486 Minor updates to pyflix library, pyflix@0.10
Fixes to documentation.
Improve logger format.
2025-11-22 05:07:46 +03:00
Oleg Kalachev 9b5872740f Add wifi cli command
To show wi-fi info.
2025-11-22 04:46:54 +03:00
Oleg Kalachev 31dbdaf241 Group control parameters
Also add IMU group to accelerometer calibration parameters.
2025-11-19 01:50:46 +03:00
Oleg Kalachev f4b56262b1 Remove unneeded SERIAL_BAUDRATE define 2025-11-14 20:23:15 +03:00
Oleg Kalachev 49039f752d Refactor Wi-Fi log download
Use MAVLink LOG_REQUEST_DATA and LOG_DATA for download log instead of console.
Make Wi-Fi download default way of downloading the log.
Make `log` command only print the header and `log dump` dump the log.
2025-11-14 20:21:05 +03:00
Oleg Kalachev 348721acc9 Updates in documentation
Fixes, updates, new illustrations.
2025-11-10 20:16:14 +03:00
Oleg Kalachev 774144c430 Many updates to documentation
Updates to main readme.
Add much more info to usage article.
Move simulator building to simulation's readme.
Improve assembly article.
Many fixes.
Updates in diagrams.
2025-11-06 13:55:52 +03:00
Oleg Kalachev 0e6651ab82 Add Rate class for running the code at fixed rate 2025-11-06 13:41:33 +03:00
30 changed files with 833 additions and 589 deletions
+19 -12
View File
@@ -13,7 +13,7 @@ jobs:
env:
ARDUINO_SKETCH_ALWAYS_EXPORT_BINARIES: 1
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Install Arduino CLI
run: curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh
- name: Build firmware for ESP32
@@ -27,23 +27,21 @@ jobs:
- name: Build firmware for ESP32-S3 with OPI PSRAM
run: make BOARD=esp32:esp32:esp32s3:CDCOnBoot=cdc,PSRAM=opi EXTRA=--output-dir=flix/build/esp32.esp32.esp32s3.opi
- name: Build firmware for Flix2
run: make BOARD=esp32:esp32:esp32s3:FlashSize=4M,CDCOnBoot=cdc,PSRAM=opi EXTRA='--build-property "compiler.cpp.extra_flags=-DFLIX2" --output-dir=flix/build/esp32.esp32.flix2'
- name: Build firmware for STM32F4
run: |
arduino-cli core install STMicroelectronics:stm32 --additional-urls https://github.com/stm32duino/BoardManagerFiles/raw/main/package_stmicroelectronics_index.json
make BOARD=STMicroelectronics:stm32:GenF4
run: make BOARD=esp32:esp32:esp32s3:FlashSize=4M,CDCOnBoot=cdc,PSRAM=opi FLAGS=-DFLIX2 EXTRA=--output-dir=flix/build/esp32.esp32.flix2
- name: Upload binaries
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: firmware-binary
path: flix/build
- 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
build_macos:
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Install Arduino CLI
run: brew install arduino-cli
- name: Build firmware
@@ -54,7 +52,7 @@ jobs:
build_windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Install Arduino CLI
run: choco install arduino-cli
- name: Install Make
@@ -75,7 +73,7 @@ jobs:
DEBIAN_FRONTEND=noninteractive apt-get install -y curl wget build-essential cmake g++ pkg-config gnupg2 lsb-release sudo
- name: Install Arduino CLI
run: curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Install Gazebo
run: |
sudo sh -c 'echo "deb http://packages.osrfoundation.org/gazebo/ubuntu-stable `lsb_release -cs` main" > /etc/apt/sources.list.d/gazebo-stable.list'
@@ -86,7 +84,16 @@ jobs:
run: sudo apt-get install -y libsdl2-dev
- name: Build simulator
run: make build_simulator
- uses: actions/upload-artifact@v4
- name: Run simulator
env:
GAZEBO_MODEL_PATH: ${{ github.workspace }}/gazebo/models
GAZEBO_PLUGIN_PATH: ${{ github.workspace }}/gazebo/build
run: |
OUT=$(timeout -k 10s 120s gzserver --verbose gazebo/flix.world 2>&1 | tee /dev/stderr)
if echo "$OUT" | grep -Pq "\[Err\](?! \[RenderEngine)"; then
exit 1
fi
- uses: actions/upload-artifact@v7
with:
name: gazebo-plugin-binary
path: gazebo/build/*.so
@@ -98,7 +105,7 @@ jobs:
steps:
- name: Install Arduino CLI
run: brew install arduino-cli
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Clean up python binaries # Workaround for https://github.com/actions/setup-python/issues/577
run: |
rm -f /usr/local/bin/2to3*
+12 -6
View File
@@ -16,7 +16,7 @@ jobs:
markdownlint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Install markdownlint
run: npm install -g markdownlint-cli2
- name: Run markdownlint
@@ -25,13 +25,16 @@ jobs:
build_book:
runs-on: ubuntu-latest
needs: markdownlint
env:
BINARIES: ${{ github.event_name == 'push' && (github.ref_name == 'master' || github.ref_name == 'dev') && github.repository == 'okalachev/flix' }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Install mdBook
run: cargo install mdbook --vers 0.4.43 --locked
- name: Build book
run: cd docs && mdbook build
- name: Wait for Build to complete
if: ${{ env.BINARIES }}
uses: lewagon/wait-on-check-action@v1.9.1
with:
ref: ${{ github.sha }}
@@ -39,6 +42,7 @@ jobs:
repo-token: ${{ secrets.GITHUB_TOKEN }}
wait-interval: 30
- name: Find firmware binaries
if: ${{ env.BINARIES }}
id: build_run
run: |
RUN_ID=$(gh api "repos/${{ github.repository }}/actions/workflows/build.yml/runs?head_sha=${{ github.sha }}&per_page=1" --jq '.workflow_runs[0].id')
@@ -46,7 +50,8 @@ jobs:
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Download firmware binaries
uses: actions/download-artifact@v4
if: ${{ env.BINARIES }}
uses: actions/download-artifact@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
repository: ${{ github.repository }}
@@ -54,6 +59,7 @@ jobs:
name: firmware-binary
path: docs/build
- name: Create shortcuts for firmware binaries
if: ${{ env.BINARIES }}
working-directory: docs/build
run: |
for FQBN in esp32.esp32.*; do
@@ -64,12 +70,12 @@ jobs:
ln -s "$FQBN/flix.ino.bootloader.bin" "flix.$BOARD.bootloader.bin"
done
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
uses: actions/upload-pages-artifact@v5
with:
path: docs/build
deploy:
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
if: ${{ github.event_name == 'push' && github.ref_name == 'master' }}
concurrency:
group: "pages"
cancel-in-progress: true
@@ -81,4 +87,4 @@ jobs:
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
uses: actions/deploy-pages@v5
+24 -4
View File
@@ -10,7 +10,7 @@ jobs:
csv_to_ulog:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Build csv_to_ulog
run: cd tools/csv_to_ulog && mkdir build && cd build && cmake .. && make
- name: Test csv_to_ulog
@@ -22,13 +22,13 @@ jobs:
pyflix:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Install Python build tools
run: pip install build
- name: Build pyflix
run: python3 -m build tools
- name: Upload artifacts
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: pyflix
path: |
@@ -37,7 +37,7 @@ jobs:
python_tools:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Install Python dependencies
run: pip install -r tools/requirements.txt
- name: Test csv_to_mcap tool
@@ -46,3 +46,23 @@ jobs:
echo -e "t,x,y,z\n0,1,2,3\n1,4,5,6" > log.csv
./csv_to_mcap.py log.csv
test $(stat -c %s log.mcap) -eq 883
sloc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- run: sudo apt-get install -y cloc jq
- name: Print source lines of code
run: cloc --by-file-by-lang flix
- name: Checkout previous revision
uses: actions/checkout@v7
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }}
path: prev
- name: Annotate total source lines
run: |
SLOC_CURR=$(cloc flix --json | jq -r '.SUM.code')
SLOC_PREV=$(cloc prev/flix --json | jq -r '.SUM.code')
DIFF=$(printf '%+d' "$((SLOC_CURR - SLOC_PREV))")
echo "* Current SLOC: $SLOC_CURR" >> $GITHUB_STEP_SUMMARY
echo "* Previous SLOC: $SLOC_PREV" >> $GITHUB_STEP_SUMMARY
echo "* Diff: $DIFF" >> $GITHUB_STEP_SUMMARY
+9 -5
View File
@@ -1,13 +1,17 @@
BOARD = esp32:esp32:esp32
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*))
VERSION = $(shell git describe --always --dirty)
export ARDUINO_NETWORK_CONNECTION_TIMEOUT := 1h
build: .core .libs
arduino-cli compile --fqbn $(BOARD) --build-property "build.core_debug_level=1" flix $(EXTRA)
arduino-cli compile flix \
--fqbn $(BOARD) \
--build-property "build.core_debug_level=1" \
--build-property "compiler.cpp.extra_flags=-DVERSION=$(VERSION) $(FLAGS)" $(EXTRA)
upload: build
arduino-cli upload --fqbn $(BOARD) -p "$(PORT)" flix
arduino-cli upload flix --fqbn $(BOARD) -p "$(PORT)"
erase:
arduino-cli burn-bootloader --fqbn $(BOARD) -p "$(PORT)" -P esptool
@@ -22,13 +26,13 @@ core .core:
libs .libs:
arduino-cli lib update-index
arduino-cli lib install "FlixPeriph"
ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=1 arduino-cli lib install --git-url 'https://github.com/okalachev/flixperiph.git#dev'
arduino-cli lib install "MAVLink"@2.0.25
touch .libs
upload_proxy: .core .libs
arduino-cli compile --fqbn $(BOARD) tools/espnow-proxy
arduino-cli upload --fqbn $(BOARD) -p "$(PORT)" tools/espnow-proxy
arduino-cli compile tools/espnow-proxy --fqbn $(BOARD)
arduino-cli upload tools/espnow-proxy --fqbn $(BOARD) -p "$(PORT)"
gazebo/build cmake: gazebo/CMakeLists.txt
mkdir -p gazebo/build
+1 -1
View File
@@ -31,7 +31,7 @@
* [`vector.h`](https://github.com/okalachev/flix/blob/master/flix/vector.h), [`quaternion.h`](https://github.com/okalachev/flix/blob/master/flix/quaternion.h) — библиотеки векторов и кватернионов.
* [`pid.h`](https://github.com/okalachev/flix/blob/master/flix/pid.h) — ПИД-регулятор.
* [`lpf.h`](https://github.com/okalachev/flix/blob/master/flix/lpf.h) — фильтр нижних частот.
* [`filter.h`](https://github.com/okalachev/flix/blob/master/flix/filter.h) — фильтр нижних частот.
### Подсистема управления
+2 -2
View File
@@ -34,7 +34,7 @@ Utility files:
* [`vector.h`](../flix/vector.h), [`quaternion.h`](../flix/quaternion.h) — vector and quaternion libraries.
* [`pid.h`](../flix/pid.h) — generic PID controller.
* [`lpf.h`](../flix/lpf.h) — generic low-pass filter.
* [`filter.h`](../flix/filter.h) — generic low-pass filter.
### Control subsystem
@@ -73,7 +73,7 @@ Parameters subsystem (`parameters.ino`) uses standard [Preferences.h](https://do
To add a new parameter:
1. Define a global variable for the parameter, two types are supported: `float` and `int`.
1. Define a global variable for the parameter, three types are supported: `float`, `int`, and `bool`.
2. Add an entry to the `parameters` array, with the parameter name, a pointer to the variable, and optionally a callback function to call when the parameter is changed.
3. Everything else will be handled automatically.
+26 -6
View File
@@ -6,7 +6,7 @@
#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;
@@ -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";
@@ -99,7 +105,7 @@ void doCommand(String str, bool echo = false) {
if (success) {
print("%s = %g\n", arg0.c_str(), getParameter(arg0.c_str()));
} else {
print("Parameter not found: %s\n", arg0.c_str());
print("Cannot set parameter: %s\n", arg0.c_str());
}
} else if (command == "preset") {
resetParameters();
@@ -153,9 +159,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,7 +189,12 @@ 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("Firmware: " __DATE__ " " __TIME__ "\n");
print("PSRAM: %d KB\n", ESP.getPsramSize() / 1024);
print("Free PSRAM: %d KB\n", ESP.getFreePsram() / 1024);
#ifdef VERSION
print("Version: %s\n", STRINGIFY(VERSION));
#endif
print("Build date: " __DATE__ " " __TIME__ "\n");
// Print tasks table
print("Num Task MinSt Prio Core CPU%%\n");
int taskCount = uxTaskGetNumberOfTasks();
+12 -6
View File
@@ -12,16 +12,22 @@ void setDefaults() {
pwmFrequency = 38000;
#endif
#ifdef CONFIG_IDF_TARGET_ESP32
// classic esp32 configuration
motorPins[0] = 12;
motorPins[1] = 13;
motorPins[2] = 14;
motorPins[3] = 15;
#endif
#ifdef FLIX2
imuModel = 4; // ICM-40609-D
imuIntPin = 10;
imuCsPin = 14;
motorPins[MOTOR_REAR_LEFT] = 41;
motorPins[MOTOR_REAR_RIGHT] = 7;
motorPins[MOTOR_FRONT_RIGHT] = 18;
motorPins[MOTOR_FRONT_LEFT] = 38;
voltagePin = 3;
motorPins[0] = 41;
motorPins[1] = 7;
motorPins[2] = 18;
motorPins[3] = 38;
#endif
}
+2 -2
View File
@@ -6,7 +6,7 @@
#include "vector.h"
#include "quaternion.h"
#include "pid.h"
#include "lpf.h"
#include "filter.h"
#include "util.h"
const int RAW = 0, ACRO = 1, STAB = 2, AUTO = 3; // flight modes
@@ -16,7 +16,7 @@ bool armed = false;
Quaternion attitudeTarget;
Vector ratesTarget;
Vector ratesExtra; // feedforward rates
Vector torqueTarget;
Vector torqueTarget; // 0 - no torque, 1 - maximum torque
float thrustTarget;
PID rollRatePID(0.05, 0.2, 0.001, 0.3, 0.2);
+8 -1
View File
@@ -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,6 +15,12 @@ bool landed;
float accWeight = 0.003;
float levelWeight = 0.0002;
LowPassFilter<Vector> ratesFilter(0.2); // cutoff frequency ~ 40 Hz
NotchFilter<Vector> ratesNotch(382, 40);
void setupEstimate() {
print("Setup estimation\n");
ratesNotch.reset();
}
void estimate() {
applyGyro();
@@ -25,6 +31,7 @@ void estimate() {
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));
+98
View File
@@ -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
View File
@@ -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
View File
@@ -7,7 +7,7 @@
#include <Wire.h>
#include <FlixPeriph.h>
#include "vector.h"
#include "lpf.h"
#include "filter.h"
#include "util.h"
IMU *imu;
+247 -52
View File
@@ -1,77 +1,272 @@
// 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 = 0; // 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},
{"rates.x", &rates.x},
{"rates.y", &rates.y},
{"rates.z", &rates.z},
{"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}
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) {};
};
const int logColumns = sizeof(logEntries) / sizeof(logEntries[0]);
float logBuffer[LOG_SIZE][logColumns];
LogTopic logTopics[] = {
// time
LogTopic({"t", &t}), // must be the first topic
LogTopic(1, {"loopRate", &loopRate}),
void prepareLogData() {
attitudeEuler = attitude.toEuler();
attitudeTargetEuler = attitudeTarget.toEuler();
}
// imu
LogTopic(
{"gyro.x", &gyro.x},
{"gyro.y", &gyro.y},
{"gyro.z", &gyro.z}),
void logData() {
if (!armed) return;
static int logPointer = 0;
static Rate period(LOG_RATE);
if (!period) return;
LogTopic(50,
{"acc.x", &acc.x},
{"acc.y", &acc.y},
{"acc.z", &acc.z}),
prepareLogData();
LogTopic(10,
{"gyroBias.x", &gyroBias.x},
{"gyroBias.y", &gyroBias.y},
{"gyroBias.z", &gyroBias.z}),
for (int i = 0; i < logColumns; i++) {
logBuffer[logPointer][i] = *logEntries[i].value;
}
// 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(); }}),
logPointer++;
if (logPointer >= LOG_SIZE) {
logPointer = 0;
// 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},
{"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(); }}),
};
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 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 printLogHeader() {
for (int i = 0; i < logColumns; i++) {
print("%s%s", logEntries[i].name, i < logColumns - 1 ? "," : "\n");
}
}
void loopLog() {
if (logBuffer == nullptr || !armed) return;
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");
if (!logLength) resetLog(); // reset state on first log write
static Rate sync(2);
if (sync) {
const uint8_t marker[] = {0x1A, 0x91, 0x4F, 0xF6, 0x7F};
writeLog(&marker, sizeof(marker)); // write sync marker
}
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() {
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 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
View File
@@ -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;
};
+61 -17
View File
@@ -16,6 +16,7 @@ Rate telemetryAttitude(20);
Rate telemetryRC(10);
Rate telemetryMotors(10);
Rate telemetryIMU(15);
Rate telemetryTopic(10);
float mavlinkTime = NAN; // time of last received message
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);
@@ -196,18 +223,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;
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);
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]; // convert to flu
attitudeTarget.z = -m.q[3];
ratesExtra.x = m.body_roll_rate;
ratesExtra.y = -m.body_pitch_rate;
ratesExtra.z = -m.body_yaw_rate;
} else {
// Rates control
attitudeTarget.invalidate();
ratesTarget.x = m.body_roll_rate;
ratesTarget.y = -m.body_pitch_rate;
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 +258,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 -10
View File
@@ -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;
@@ -19,27 +19,18 @@ const int MOTOR_REAR_LEFT = 0, MOTOR_REAR_RIGHT = 1, MOTOR_FRONT_RIGHT = 2, MOTO
void setupMotors() {
print("Setup motors\n");
// Configure pins
#ifdef ESP32
for (int i = 0; i < 4; i++) {
if (motorPins[i] < 0) continue; // skip unassigned motors
ledcAttach(motorPins[i], pwmFrequency, pwmResolution);
pwmFrequency = ledcChangeFrequency(motorPins[i], pwmFrequency, pwmResolution); // when reconfiguring
}
#else
analogWriteResolution(pwmResolution);
analogWriteFrequency(pwmFrequency);
#endif
sendMotors();
}
void sendMotors() {
for (int i = 0; i < 4; i++) {
if (motorPins[i] < 0) continue; // skip unassigned motors
#ifdef ESP32
ledcWrite(motorPins[i], getDutyCycle(motors[i]));
#else
analogWrite(motorPins[i], getDutyCycle(motors[i]));
#endif
}
}
+35 -22
View File
@@ -3,7 +3,7 @@
// Parameters storage in flash memory
#include "prefs.h"
#include <Preferences.h>
#include "util.h"
extern int channelZero[16], channelMax[16];
@@ -20,15 +20,11 @@ Preferences storage;
struct Parameter {
const char *name; // max length is 15
bool integer;
union { float *f; int *i; }; // pointer to the variable
float inital; // default value
Value value; // pointer to the variable
float initial; // default value
float cache; // what's stored in flash
void (*callback)(); // called after parameter change
Parameter(const char *name, float *variable, void (*callback)() = nullptr) : name(name), integer(false), f(variable), callback(callback) {};
Parameter(const char *name, int *variable, void (*callback)() = nullptr) : name(name), integer(true), i(variable), callback(callback) {};
float getValue() const { return integer ? *i : *f; };
void setValue(const float value) { if (integer) *i = value; else *f = value; };
Parameter(const char *name, Value value, void (*callback)() = nullptr) : name(name), value(value), callback(callback) {};
};
Parameter parameters[] = {
@@ -86,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},
@@ -134,6 +132,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},
@@ -150,11 +164,11 @@ void setupParameters() {
storage.begin("flix");
// Read parameters from storage
for (auto &parameter : parameters) {
parameter.inital = parameter.getValue();
parameter.initial = parameter.value.get();
if (storage.isKey(parameter.name)) {
parameter.setValue(storage.getFloat(parameter.name));
parameter.value.set(storage.getFloat(parameter.name));
}
parameter.cache = parameter.getValue();
parameter.cache = parameter.value.get();
}
}
@@ -169,13 +183,13 @@ const char *getParameterName(int index) {
float getParameter(int index) {
if (index < 0 || index >= parametersCount()) return NAN;
return parameters[index].getValue();
return parameters[index].value.get();
}
float getParameter(const char *name) {
for (auto &parameter : parameters) {
if (strcasecmp(parameter.name, name) == 0) {
return parameter.getValue();
return parameter.value.get();
}
}
return NAN;
@@ -184,10 +198,9 @@ float getParameter(const char *name) {
bool setParameter(const char *name, const float value) {
for (auto &parameter : parameters) {
if (strcasecmp(parameter.name, name) == 0) {
if (parameter.integer && !isfinite(value)) return false; // can't set integer to NaN or Inf
parameter.setValue(value);
bool success = parameter.value.set(value);
if (parameter.callback) parameter.callback();
return true;
return success;
}
}
return false;
@@ -199,10 +212,10 @@ void syncParameters() {
if (motorsActive()) return; // don't use flash while flying, it may cause a delay
for (auto &parameter : parameters) {
if (floatEquals(parameter.getValue(), parameter.cache)) continue; // no change
if (floatEquals(parameter.value.get(), parameter.cache)) continue; // no change
storage.putFloat(parameter.name, parameter.getValue());
parameter.cache = parameter.getValue(); // update cache
storage.putFloat(parameter.name, parameter.value.get());
parameter.cache = parameter.value.get(); // update cache
}
}
@@ -211,10 +224,10 @@ void printParameters(const char *filter) {
for (auto &parameter : parameters) {
if (strncasecmp(parameter.name, filter, strlen(filter))) continue;
if (floatEquals(parameter.getValue(), parameter.inital)) { // parameter changed
print("%-15s %-13g\n", parameter.name, parameter.getValue());
if (floatEquals(parameter.value.get(), parameter.initial)) { // parameter changed
print("%-15s %-13g\n", parameter.name, parameter.value.get());
} else {
print("%-15s %-13g [%g]\n", parameter.name, parameter.getValue(), parameter.inital);
print("%-15s %-13g [%g]\n", parameter.name, parameter.value.get(), parameter.initial);
}
}
}
+2 -2
View File
@@ -5,7 +5,7 @@
#pragma once
#include "lpf.h"
#include "filter.h"
class PID {
public:
@@ -18,7 +18,7 @@ public:
LowPassFilter<float> lpf; // low pass filter for derivative term
PID(float p, float i = 0, float d = 0, float windup = 0, float dAlpha = 1, float dtMax = 0.1) :
PID(float p, float i = 0, float d = 0, float windup = INFINITY, float dAlpha = 1, float dtMax = 0.1) :
p(p), i(i), d(d), windup(windup), lpf(dAlpha), dtMax(dtMax) {}
float update(float error) {
+1 -5
View File
@@ -3,11 +3,9 @@
// Power management
#ifdef ESP32
#include <soc/soc.h>
#include <soc/rtc_cntl_reg.h>
#endif
#include "lpf.h"
#include "filter.h"
#include "util.h"
float voltage = NAN;
@@ -16,9 +14,7 @@ int voltagePin = -1;
float voltageScale = 2;
void setupPower() {
#ifdef ESP32
REG_CLR_BIT(RTC_CNTL_BROWN_OUT_REG, RTC_CNTL_BROWN_OUT_ENA); // disable reset on low voltage
#endif
if (digitalPinToAnalogChannel(voltagePin) == -1) voltagePin = -1; // test ADC pin
}
-283
View File
@@ -1,283 +0,0 @@
#ifdef ESP32
#include <Preferences.h>
#else
#include <Arduino.h>
#include <EEPROM.h>
#include <string.h>
class Preferences {
public:
Preferences() = default;
~Preferences() = default;
bool begin(const char *name, bool readOnly = false, const char *partition_label = NULL) {
(void)name;
(void)readOnly;
(void)partition_label;
load();
started = true;
return true;
}
void end() {
started = false;
}
bool clear() {
if (!started) return false;
for (auto &entry : entries) {
entry = Entry();
}
return save();
}
size_t putFloat(const char *key, float value) {
if (!started) return 0;
int index = ensureKey(key);
if (index < 0) return 0;
entries[index].hasFloat = true;
entries[index].hasString = false;
entries[index].stringValue = "";
entries[index].floatValue = value;
if (!save()) return 0;
return sizeof(float);
}
float getFloat(const char *key, float defaultValue = NAN) {
if (!started) return defaultValue;
int index = findKey(key);
if (index < 0 || !entries[index].hasFloat) return defaultValue;
return entries[index].floatValue;
}
size_t putString(const char *key, const char *value) {
if (!started) return 0;
int index = ensureKey(key);
if (index < 0) return 0;
if (!value) value = "";
if (strlen(value) > MAX_STRING_LEN) return 0;
entries[index].hasString = true;
entries[index].hasFloat = false;
entries[index].stringValue = value;
if (!save()) return 0;
return entries[index].stringValue.length();
}
size_t putString(const char *key, String value) {
return putString(key, value.c_str());
}
String getString(const char *key, String defaultValue = String()) {
if (!started) return defaultValue;
int index = findKey(key);
if (index < 0 || !entries[index].hasString) return defaultValue;
return entries[index].stringValue;
}
bool isKey(const char *key) {
if (!started) return false;
return findKey(key) >= 0;
}
private:
static const int MAX_ENTRIES = 128;
static const int MAX_KEY_LEN = 15;
static const int MAX_STRING_LEN = 95;
static const uint32_t MAGIC = 0x46504B56; // "VKPF"
static const uint8_t VERSION = 1;
static const uint8_t TYPE_FLOAT = 1;
static const uint8_t TYPE_STRING = 2;
static const int STORAGE_SIZE = 4096;
struct Entry {
bool used = false;
char key[MAX_KEY_LEN + 1] = {};
bool hasFloat = false;
float floatValue = NAN;
bool hasString = false;
String stringValue;
};
bool started = false;
Entry entries[MAX_ENTRIES];
static void writeU16(uint8_t *dst, uint16_t value) {
dst[0] = static_cast<uint8_t>(value & 0xFF);
dst[1] = static_cast<uint8_t>((value >> 8) & 0xFF);
}
static void writeU32(uint8_t *dst, uint32_t value) {
dst[0] = static_cast<uint8_t>(value & 0xFF);
dst[1] = static_cast<uint8_t>((value >> 8) & 0xFF);
dst[2] = static_cast<uint8_t>((value >> 16) & 0xFF);
dst[3] = static_cast<uint8_t>((value >> 24) & 0xFF);
}
static uint16_t readU16(const uint8_t *src) {
return static_cast<uint16_t>(src[0]) |
(static_cast<uint16_t>(src[1]) << 8);
}
static uint32_t readU32(const uint8_t *src) {
return static_cast<uint32_t>(src[0]) |
(static_cast<uint32_t>(src[1]) << 8) |
(static_cast<uint32_t>(src[2]) << 16) |
(static_cast<uint32_t>(src[3]) << 24);
}
int availableStorageSize() {
int n = STORAGE_SIZE;
if (EEPROM.length() > 0 && EEPROM.length() < n) n = EEPROM.length();
return n;
}
bool save() {
const int storageSize = availableStorageSize();
if (storageSize < 16) return false;
uint8_t buffer[STORAGE_SIZE] = {};
int pos = 0;
writeU32(buffer + pos, MAGIC);
pos += 4;
buffer[pos++] = VERSION;
buffer[pos++] = 0;
int lengthPos = pos;
pos += 2;
for (int i = 0; i < MAX_ENTRIES; i++) {
if (!entries[i].used) continue;
if (!entries[i].hasFloat && !entries[i].hasString) continue;
const uint8_t keyLen = static_cast<uint8_t>(strnlen(entries[i].key, MAX_KEY_LEN));
if (keyLen == 0) continue;
if (entries[i].hasFloat) {
const int recordSize = 3 + keyLen + 4;
if (pos + recordSize > storageSize) return false;
buffer[pos++] = TYPE_FLOAT;
buffer[pos++] = keyLen;
buffer[pos++] = 4;
memcpy(buffer + pos, entries[i].key, keyLen);
pos += keyLen;
float value = entries[i].floatValue;
memcpy(buffer + pos, &value, sizeof(value));
pos += sizeof(value);
} else if (entries[i].hasString) {
const uint8_t valueLen = static_cast<uint8_t>(entries[i].stringValue.length());
const int recordSize = 3 + keyLen + valueLen;
if (pos + recordSize > storageSize) return false;
buffer[pos++] = TYPE_STRING;
buffer[pos++] = keyLen;
buffer[pos++] = valueLen;
memcpy(buffer + pos, entries[i].key, keyLen);
pos += keyLen;
if (valueLen > 0) {
memcpy(buffer + pos, entries[i].stringValue.c_str(), valueLen);
pos += valueLen;
}
}
}
writeU16(buffer + lengthPos, static_cast<uint16_t>(pos));
for (int i = 0; i < storageSize; i++) {
EEPROM.write(i, buffer[i]);
}
EEPROM.commit();
return true;
}
void load() {
const int storageSize = availableStorageSize();
if (storageSize < 16) return;
for (auto &entry : entries) entry = Entry();
uint8_t buffer[STORAGE_SIZE] = {};
for (int i = 0; i < storageSize; i++) {
buffer[i] = EEPROM.read(i);
}
int pos = 0;
if (readU32(buffer + pos) != MAGIC) return;
pos += 4;
if (buffer[pos++] != VERSION) return;
pos++; // flags
const uint16_t totalLen = readU16(buffer + pos);
pos += 2;
if (totalLen < pos || totalLen > storageSize) return;
while (pos + 3 <= totalLen) {
const uint8_t type = buffer[pos++];
const uint8_t keyLen = buffer[pos++];
const uint8_t valueLen = buffer[pos++];
if (keyLen == 0 || keyLen > MAX_KEY_LEN) return;
if (pos + keyLen + valueLen > totalLen) return;
char key[MAX_KEY_LEN + 1] = {};
memcpy(key, buffer + pos, keyLen);
key[keyLen] = '\0';
pos += keyLen;
int index = ensureKey(key);
if (index < 0) return;
if (type == TYPE_FLOAT && valueLen == 4) {
float value = NAN;
memcpy(&value, buffer + pos, sizeof(value));
entries[index].hasFloat = true;
entries[index].hasString = false;
entries[index].stringValue = "";
entries[index].floatValue = value;
} else if (type == TYPE_STRING && valueLen <= MAX_STRING_LEN) {
char value[MAX_STRING_LEN + 1] = {};
if (valueLen > 0) memcpy(value, buffer + pos, valueLen);
value[valueLen] = '\0';
entries[index].hasString = true;
entries[index].hasFloat = false;
entries[index].stringValue = value;
}
pos += valueLen;
}
}
int findKey(const char *key) {
if (!key) return -1;
for (int i = 0; i < MAX_ENTRIES; i++) {
if (!entries[i].used) continue;
if (strncmp(entries[i].key, key, MAX_KEY_LEN + 1) == 0) return i;
}
return -1;
}
int ensureKey(const char *key) {
if (!key) return -1;
if (strlen(key) > MAX_KEY_LEN) return -1;
int index = findKey(key);
if (index >= 0) return index;
for (int i = 0; i < MAX_ENTRIES; i++) {
if (entries[i].used) continue;
entries[i].used = true;
entries[i].hasFloat = false;
entries[i].hasString = false;
entries[i].floatValue = NAN;
entries[i].stringValue = "";
strncpy(entries[i].key, key, MAX_KEY_LEN);
entries[i].key[MAX_KEY_LEN] = '\0';
return i;
}
return -1;
}
};
#endif
+46 -6
View File
@@ -6,15 +6,13 @@
#pragma once
#include <math.h>
#ifdef ESP32
#include <soc/soc.h>
#include <soc/rtc_cntl_reg.h>
#include <ESP32_NOW_Serial.h>
#endif
const float ONE_G = 9.80665;
extern float t;
#define STRINGIFY(x) __STRINGIFY(x)
float mapf(float x, float in_min, float in_max, float out_min, float out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
@@ -57,7 +55,6 @@ void splitString(String& str, String& token0, String& token1, String& token2) {
if (token2.c_str() == NULL) token2 = "";
}
#ifdef ESP32
// Simplified ESP-NOW Serial without resends
class ESPNOWSerial : public ESP_NOW_Serial_Class {
public:
@@ -68,7 +65,50 @@ public:
ESP_NOW_Serial_Class::onSent(true); // always report success to avoid resends
}
};
#endif
// 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;
}
};
bool set(float value) const {
switch (type) {
case FLOAT: *_float = value; break;
case INT: if (!isfinite(value)) return false; *_int = value; break;
case BOOL: *_bool = (value != 0); break;
default: return false;
}
return true;
}
};
// Rate limiter
class Rate {
+96 -97
View File
@@ -3,13 +3,13 @@
// Wi-Fi and ESP-NOW communication
// #include <WiFi.h>
// #include <WiFiAP.h>
// #include <WiFiUdp.h>
// #include <MacAddress.h>
// #include <ESP32_NOW_Serial.h>
// #include "prefs.h"
// #include "util.h"
#include <WiFi.h>
#include <WiFiAP.h>
#include <WiFiUdp.h>
#include <MacAddress.h>
#include <ESP32_NOW_Serial.h>
#include <Preferences.h>
#include "util.h"
extern Preferences storage; // use the main preferences storage
@@ -20,121 +20,120 @@ int wifiLongRange = 0;
int wifiBroadcast = 0; // 0 - broadcast until connected, 1 - always broadcast
int udpLocalPort = 14550;
int udpRemotePort = 14550;
// IPAddress udpRemoteIP = "255.255.255.255";
// WiFiUDP udp;
IPAddress udpRemoteIP = "255.255.255.255";
WiFiUDP udp;
// ESPNOWSerial espnow(NULL, 0, WIFI_IF_AP);
// ESPNOWSerial espnowBroadcast(ESP_NOW.BROADCAST_ADDR, 0, WIFI_IF_AP);
ESPNOWSerial espnow(NULL, 0, WIFI_IF_AP);
ESPNOWSerial espnowBroadcast(ESP_NOW.BROADCAST_ADDR, 0, WIFI_IF_AP);
int espnowChannel = 6;
void setupWiFi() {
// print("Setup Wi-Fi\n");
// WiFi.enableLongRange(wifiLongRange);
print("Setup Wi-Fi\n");
WiFi.enableLongRange(wifiLongRange);
// if (wifiMode == W_AP) {
// WiFi.softAP(storage.getString("WIFI_AP_SSID", "flix").c_str(), storage.getString("WIFI_AP_PASS", "flixwifi").c_str());
// udp.begin(udpLocalPort);
// }
if (wifiMode == W_AP) {
WiFi.softAP(storage.getString("WIFI_AP_SSID", "flix").c_str(), storage.getString("WIFI_AP_PASS", "flixwifi").c_str());
udp.begin(udpLocalPort);
}
// if (wifiMode == W_STA) {
// WiFi.begin(storage.getString("WIFI_STA_SSID", "").c_str(), storage.getString("WIFI_STA_PASS", "").c_str());
// udp.begin(udpLocalPort);
// }
if (wifiMode == W_STA) {
WiFi.begin(storage.getString("WIFI_STA_SSID", "").c_str(), storage.getString("WIFI_STA_PASS", "").c_str());
udp.begin(udpLocalPort);
}
// if (wifiMode == W_ESPNOW) {
// WiFi.mode(WIFI_AP);
// WiFi.setChannel(espnowChannel);
// espnow.addr(MacAddress(storage.getString("ESPNOW_PEER_MAC", "FF:FF:FF:FF:FF:FF").c_str()));
// String key = storage.getString("ESPNOW_PEER_KEY", "");
// espnow.setKey(key.isEmpty() ? nullptr : (const uint8_t *)key.c_str());
// espnow.begin();
// espnowBroadcast.begin();
// }
if (wifiMode == W_ESPNOW) {
WiFi.mode(WIFI_AP);
WiFi.setChannel(espnowChannel);
espnow.addr(MacAddress(storage.getString("ESPNOW_PEER_MAC", "FF:FF:FF:FF:FF:FF").c_str()));
String key = storage.getString("ESPNOW_PEER_KEY", "");
espnow.setKey(key.isEmpty() ? nullptr : (const uint8_t *)key.c_str());
espnow.begin();
espnowBroadcast.begin();
}
// WiFi.setSleep(false); // disable power save
WiFi.setSleep(false); // disable power save
}
void sendWiFi(const uint8_t *buf, int len) {
// if (espnow) {
// espnow.write(buf, len);
if (espnow) {
espnow.write(buf, len);
// static Rate discovery(2);
// if (espnow.isEncrypted() && discovery) espnowBroadcast.write((const uint8_t *)"flix", 4); // broadcast message to help finding this device
// return;
// }
static Rate discovery(2);
if (espnow.isEncrypted() && discovery) espnowBroadcast.write((const uint8_t *)"flix", 4); // broadcast message to help finding this device
return;
}
// if (WiFi.softAPgetStationNum() == 0 && !WiFi.isConnected()) return;
if (WiFi.softAPgetStationNum() == 0 && !WiFi.isConnected()) return;
// bool broadcast = wifiBroadcast || !(t - mavlinkTime < 5); // broadcast if lost connection
// udp.beginPacket(broadcast ? IPAddress(255, 255, 255, 255) : udpRemoteIP, udpRemotePort);
// udp.write(buf, len);
// udp.endPacket();
bool broadcast = wifiBroadcast || !(t - mavlinkTime < 5); // broadcast if lost connection
udp.beginPacket(broadcast ? IPAddress(255, 255, 255, 255) : udpRemoteIP, udpRemotePort);
udp.write(buf, len);
udp.endPacket();
}
int receiveWiFi(uint8_t *buf, int len) {
// if (espnow) {
// return espnow.read(buf, len);
// }
if (espnow) {
return espnow.read(buf, len);
}
// if (WiFi.softAPgetStationNum() == 0 && !WiFi.isConnected()) return 0;
if (WiFi.softAPgetStationNum() == 0 && !WiFi.isConnected()) return 0;
// udp.parsePacket();
// if (udp.remoteIP()) udpRemoteIP = udp.remoteIP();
// return udp.read(buf, len);
return 0;
udp.parsePacket();
if (udp.remoteIP()) udpRemoteIP = udp.remoteIP();
return udp.read(buf, len);
}
void printWiFiInfo() {
// if (espnow) {
// print("Mode: ESP-NOW\n");
// print("ESP-NOW version: %d\n", ESP_NOW.getVersion());
// print("Max packet size: %d\n", ESP_NOW.getMaxDataLen());
// 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("Lost packets: %d\n", espnow.lost);
// } else if (WiFi.getMode() == WIFI_MODE_AP) {
// print("Mode: Access Point (AP)\n");
// print("MAC: %s\n", WiFi.softAPmacAddress().c_str());
// print("SSID: %s\n", WiFi.softAPSSID().c_str());
// print("Password: ***\n");
// print("Channel: %d\n", WiFi.channel());
// print("Clients: %d\n", WiFi.softAPgetStationNum());
// print("IP: %s\n", WiFi.softAPIP().toString().c_str());
// print("Remote IP: %s\n", udpRemoteIP.toString().c_str());
// } else if (WiFi.getMode() == WIFI_MODE_STA) {
// print("Mode: Client (STA)\n");
// print("Connected: %d\n", WiFi.isConnected());
// print("MAC: %s\n", WiFi.macAddress().c_str());
// print("SSID: %s\n", WiFi.SSID().c_str());
// print("Password: ***\n");
// print("Channel: %d\n", WiFi.channel());
// print("RSSI: %d dBm\n", WiFi.RSSI());
// print("IP: %s\n", WiFi.localIP().toString().c_str());
// print("Remote IP: %s\n", udpRemoteIP.toString().c_str());
// } else {
// print("Mode: Disabled\n");
// }
// print("MAVLink connected: %d\n", valid(mavlinkTime));
if (espnow) {
print("Mode: ESP-NOW\n");
print("ESP-NOW version: %d\n", ESP_NOW.getVersion());
print("Max packet size: %d\n", ESP_NOW.getMaxDataLen());
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("Lost packets: %d\n", espnow.lost);
} else if (WiFi.getMode() == WIFI_MODE_AP) {
print("Mode: Access Point (AP)\n");
print("MAC: %s\n", WiFi.softAPmacAddress().c_str());
print("SSID: %s\n", WiFi.softAPSSID().c_str());
print("Password: ***\n");
print("Channel: %d\n", WiFi.channel());
print("Clients: %d\n", WiFi.softAPgetStationNum());
print("IP: %s\n", WiFi.softAPIP().toString().c_str());
print("Remote IP: %s\n", udpRemoteIP.toString().c_str());
} else if (WiFi.getMode() == WIFI_MODE_STA) {
print("Mode: Client (STA)\n");
print("Connected: %d\n", WiFi.isConnected());
print("MAC: %s\n", WiFi.macAddress().c_str());
print("SSID: %s\n", WiFi.SSID().c_str());
print("Password: ***\n");
print("Channel: %d\n", WiFi.channel());
print("RSSI: %d dBm\n", WiFi.RSSI());
print("IP: %s\n", WiFi.localIP().toString().c_str());
print("Remote IP: %s\n", udpRemoteIP.toString().c_str());
} else {
print("Mode: Disabled\n");
}
print("MAVLink connected: %d\n", valid(mavlinkTime));
}
void configWiFi(int mode, const char *first, const char *second) {
// MacAddress mac;
// if (mode == W_AP && strlen(first) > 0 && strlen(second) >= 8) {
// storage.putString("WIFI_AP_SSID", first);
// storage.putString("WIFI_AP_PASS", second);
// } else if (mode == W_STA && strlen(first) > 0 && strlen(second) >= 8) {
// storage.putString("WIFI_STA_SSID", first);
// storage.putString("WIFI_STA_PASS", second);
// } else if (mode == W_ESPNOW && mac.fromString(first)) {
// storage.putString("ESPNOW_PEER_MAC", first);
// storage.putString("ESPNOW_PEER_KEY", strlen(second) == ESP_NOW_KEY_LEN ? second : "");
// } else {
// print("Invalid configuration\n");
// return;
// }
// print("✓ Reboot to apply new settings\n");
MacAddress mac;
if (mode == W_AP && strlen(first) > 0 && strlen(second) >= 8) {
storage.putString("WIFI_AP_SSID", first);
storage.putString("WIFI_AP_PASS", second);
} else if (mode == W_STA && strlen(first) > 0 && strlen(second) >= 8) {
storage.putString("WIFI_STA_SSID", first);
storage.putString("WIFI_STA_PASS", second);
} else if (mode == W_ESPNOW && mac.fromString(first)) {
storage.putString("ESPNOW_PEER_MAC", first);
storage.putString("ESPNOW_PEER_KEY", strlen(second) == ESP_NOW_KEY_LEN ? second : "");
} else {
print("Invalid configuration\n");
return;
}
print("✓ Reboot to apply new settings\n");
}
void setWiFiMode(const String& mode) {
+11
View File
@@ -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;
+16 -2
View File
@@ -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;
@@ -51,8 +51,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);
@@ -83,3 +92,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;
+3 -2
View File
@@ -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();
}
+1
View File
@@ -14,6 +14,7 @@
// Mocks
int wifiMode = 1;
int wifiLongRange = 0;
int wifiBroadcast = 0;
int espnowChannel = 6;
const int W_DISABLED = 0, W_AP = 1, W_STA = 2, W_ESPNOW = 3;
+10 -1
View File
@@ -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,)
+76
View File
@@ -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)
+10 -9
View File
@@ -243,7 +243,7 @@ class Flix:
time.sleep(1)
@staticmethod
def _mavlink_to_flu(v: List[float]) -> List[float]:
def _mavlink_to_flu(v: Sequence[float]) -> List[float]:
if len(v) == 3: # vector
return [v[0], -v[1], -v[2]]
elif len(v) == 4: # quaternion
@@ -252,8 +252,8 @@ class Flix:
raise ValueError(f'List must have 3 (vector) or 4 (quaternion) elements')
@staticmethod
def _flu_to_mavlink(v: List[float]) -> List[float]:
return Flix._mavlink_to_flu(v)
def _flu_to_mavlink(v: Sequence[float]) -> List[float]:
return Flix._mavlink_to_flu(v) # flu to mavlink is the same as mavlink to flu
def _command_send(self, command: int, params: Sequence[float]):
if len(params) != 7:
@@ -320,13 +320,13 @@ class Flix:
def set_armed(self, armed: bool):
self._command_send(mavlink.MAV_CMD_COMPONENT_ARM_DISARM, (1 if armed else 0, 0, 0, 0, 0, 0, 0))
def set_position(self, position: List[float], yaw: Optional[float] = None, wait: bool = False, tolerance: float = 0.1):
def set_position(self, position: Sequence[float], yaw: Optional[float] = None, wait: bool = False, tolerance: float = 0.1):
raise NotImplementedError('Position control is not implemented yet')
def set_velocity(self, velocity: List[float], yaw: Optional[float] = None):
def set_velocity(self, velocity: Sequence[float], yaw: Optional[float] = None):
raise NotImplementedError('Velocity control is not implemented yet')
def set_attitude(self, attitude: List[float], thrust: float):
def set_attitude(self, attitude: Sequence[float], thrust: float, rates_extra: Sequence[float] = (0, 0, 0)):
if len(attitude) == 3:
attitude = Quaternion([attitude[0], attitude[1], attitude[2]]).q # type: ignore
elif len(attitude) != 4:
@@ -334,12 +334,13 @@ class Flix:
if not (0 <= thrust <= 1):
raise ValueError('Thrust must be in range [0, 1]')
attitude = self._flu_to_mavlink(attitude)
rates_extra = self._flu_to_mavlink(rates_extra)
for _ in range(2): # duplicate to ensure delivery
self.mavlink.set_attitude_target_send(0, self.system_id, 0, 0,
[attitude[0], attitude[1], attitude[2], attitude[3]],
0, 0, 0, thrust)
rates_extra[0], rates_extra[1], rates_extra[2], thrust)
def set_rates(self, rates: List[float], thrust: float):
def set_rates(self, rates: Sequence[float], thrust: float):
if len(rates) != 3:
raise ValueError('Rates must be [roll_rate, pitch_rate, yaw_rate]')
if not (0 <= thrust <= 1):
@@ -351,7 +352,7 @@ class Flix:
[1, 0, 0, 0],
rates[0], rates[1], rates[2], thrust)
def set_motors(self, motors: List[float]):
def set_motors(self, motors: Sequence[float]):
if len(motors) != 4:
raise ValueError('motors must have 4 values')
if not all(0 <= m <= 1 for m in motors):