Initial coding
[inav.git] / src / main / io / osd.c
blobf7bb6f108b9654bdf7237fecd623d3ec18503c18
1 /*
2 * This file is part of Cleanflight.
4 * Cleanflight is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * Cleanflight is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with Cleanflight. If not, see <http://www.gnu.org/licenses/>.
19 Created by Marcin Baliniak
20 some functions based on MinimOSD
22 OSD-CMS separation by jflyper
25 #include <stdbool.h>
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <math.h>
32 #include "platform.h"
34 FILE_COMPILE_FOR_SPEED
36 #ifdef USE_OSD
38 #include "build/debug.h"
39 #include "build/version.h"
41 #include "cms/cms.h"
42 #include "cms/cms_types.h"
43 #include "cms/cms_menu_osd.h"
45 #include "common/axis.h"
46 #include "common/constants.h"
47 #include "common/filter.h"
48 #include "common/log.h"
49 #include "common/olc.h"
50 #include "common/printf.h"
51 #include "common/string_light.h"
52 #include "common/time.h"
53 #include "common/typeconversion.h"
54 #include "common/utils.h"
56 #include "config/feature.h"
57 #include "config/parameter_group.h"
58 #include "config/parameter_group_ids.h"
60 #include "drivers/display.h"
61 #include "drivers/display_canvas.h"
62 #include "drivers/display_font_metadata.h"
63 #include "drivers/osd_symbols.h"
64 #include "drivers/time.h"
65 #include "drivers/vtx_common.h"
67 #include "io/flashfs.h"
68 #include "io/gps.h"
69 #include "io/osd.h"
70 #include "io/osd_common.h"
71 #include "io/osd_hud.h"
72 #include "io/vtx.h"
73 #include "io/vtx_string.h"
75 #include "fc/config.h"
76 #include "fc/controlrate_profile.h"
77 #include "fc/fc_core.h"
78 #include "fc/fc_tasks.h"
79 #include "fc/rc_adjustments.h"
80 #include "fc/rc_controls.h"
81 #include "fc/rc_modes.h"
82 #include "fc/runtime_config.h"
83 #include "fc/settings.h"
85 #include "flight/imu.h"
86 #include "flight/mixer.h"
87 #include "flight/pid.h"
88 #include "flight/power_limits.h"
89 #include "flight/rth_estimator.h"
90 #include "flight/servos.h"
91 #include "flight/wind_estimator.h"
93 #include "navigation/navigation.h"
94 #include "navigation/navigation_private.h"
96 #include "rx/rx.h"
97 #include "rx/msp_override.h"
99 #include "sensors/acceleration.h"
100 #include "sensors/battery.h"
101 #include "sensors/boardalignment.h"
102 #include "sensors/diagnostics.h"
103 #include "sensors/sensors.h"
104 #include "sensors/pitotmeter.h"
105 #include "sensors/temperature.h"
106 #include "sensors/esc_sensor.h"
107 #include "sensors/rangefinder.h"
109 #include "programming/logic_condition.h"
110 #include "programming/global_variables.h"
112 #ifdef USE_HARDWARE_REVISION_DETECTION
113 #include "hardware_revision.h"
114 #endif
116 #define VIDEO_BUFFER_CHARS_PAL 480
117 #define VIDEO_BUFFER_CHARS_HDZERO 900
118 #define VIDEO_BUFFER_CHARS_DJIWTF 1320
120 #define GFORCE_FILTER_TC 0.2
122 #define DELAYED_REFRESH_RESUME_COMMAND (checkStickPosition(THR_HI) || checkStickPosition(PIT_HI))
123 #define STATS_PAGE2 (checkStickPosition(ROL_HI))
124 #define STATS_PAGE1 (checkStickPosition(ROL_LO))
126 #define SPLASH_SCREEN_DISPLAY_TIME 4000 // ms
127 #define ARMED_SCREEN_DISPLAY_TIME 1500 // ms
128 #define STATS_SCREEN_DISPLAY_TIME 60000 // ms
130 #define EFFICIENCY_UPDATE_INTERVAL (5 * 1000)
132 // Adjust OSD_MESSAGE's default position when
133 // changing OSD_MESSAGE_LENGTH
134 #define OSD_MESSAGE_LENGTH 28
135 #define OSD_ALTERNATING_CHOICES(ms, num_choices) ((millis() / ms) % num_choices)
136 #define _CONST_STR_SIZE(s) ((sizeof(s)/sizeof(s[0]))-1) // -1 to avoid counting final '\0'
137 // Wrap all string constants intenteded for display as messages with
138 // this macro to ensure compile time length validation.
139 #define OSD_MESSAGE_STR(x) ({ \
140 STATIC_ASSERT(_CONST_STR_SIZE(x) <= OSD_MESSAGE_LENGTH, message_string_ ## __COUNTER__ ## _too_long); \
141 x; \
144 #define OSD_CHR_IS_NUM(c) (c >= '0' && c <= '9')
146 #define OSD_CENTER_LEN(x) ((osdDisplayPort->cols - x) / 2)
147 #define OSD_CENTER_S(s) OSD_CENTER_LEN(strlen(s))
149 #define OSD_MIN_FONT_VERSION 3
151 static unsigned currentLayout = 0;
152 static int layoutOverride = -1;
153 static bool hasExtendedFont = false; // Wether the font supports characters > 256
154 static timeMs_t layoutOverrideUntil = 0;
155 static pt1Filter_t GForceFilter, GForceFilterAxis[XYZ_AXIS_COUNT];
156 static float GForce, GForceAxis[XYZ_AXIS_COUNT];
158 typedef struct statistic_s {
159 uint16_t max_speed;
160 uint16_t max_3D_speed;
161 uint16_t max_air_speed;
162 uint16_t min_voltage; // /100
163 int16_t max_current;
164 int32_t max_power;
165 int16_t min_rssi;
166 int16_t min_lq; // for CRSF
167 int16_t min_rssi_dbm; // for CRSF
168 int32_t max_altitude;
169 uint32_t max_distance;
170 } statistic_t;
172 static statistic_t stats;
174 static timeUs_t resumeRefreshAt = 0;
175 static bool refreshWaitForResumeCmdRelease;
177 static bool fullRedraw = false;
179 static uint8_t armState;
180 static uint8_t statsPagesCheck = 0;
182 typedef struct osdMapData_s {
183 uint32_t scale;
184 char referenceSymbol;
185 } osdMapData_t;
187 static osdMapData_t osdMapData;
189 static displayPort_t *osdDisplayPort;
190 static bool osdDisplayIsReady = false;
191 #if defined(USE_CANVAS)
192 static displayCanvas_t osdCanvas;
193 static bool osdDisplayHasCanvas;
194 #else
195 #define osdDisplayHasCanvas false
196 #endif
198 #define AH_MAX_PITCH_DEFAULT 20 // Specify default maximum AHI pitch value displayed (degrees)
200 PG_REGISTER_WITH_RESET_TEMPLATE(osdConfig_t, osdConfig, PG_OSD_CONFIG, 7);
201 PG_REGISTER_WITH_RESET_FN(osdLayoutsConfig_t, osdLayoutsConfig, PG_OSD_LAYOUTS_CONFIG, 1);
203 static int digitCount(int32_t value)
205 int digits = 1;
206 while(1) {
207 value = value / 10;
208 if (value == 0) {
209 break;
211 digits++;
213 return digits;
216 bool osdDisplayIsPAL(void)
218 return displayScreenSize(osdDisplayPort) == VIDEO_BUFFER_CHARS_PAL;
221 bool osdDisplayIsHD(void)
223 if (displayScreenSize(osdDisplayPort) >= VIDEO_BUFFER_CHARS_HDZERO)
225 return true;
227 return false;
231 * Formats a number given in cents, to support non integer values
232 * without using floating point math. Value is always right aligned
233 * and spaces are inserted before the number to always yield a string
234 * of the same length. If the value doesn't fit into the provided length
235 * it will be divided by scale and true will be returned.
237 bool osdFormatCentiNumber(char *buff, int32_t centivalue, uint32_t scale, int maxDecimals, int maxScaledDecimals, int length)
239 char *ptr = buff;
240 char *dec;
241 int decimals = maxDecimals;
242 bool negative = false;
243 bool scaled = false;
245 buff[length] = '\0';
247 if (centivalue < 0) {
248 negative = true;
249 centivalue = -centivalue;
250 length--;
253 int32_t integerPart = centivalue / 100;
254 // 3 decimal digits
255 int32_t millis = (centivalue % 100) * 10;
257 int digits = digitCount(integerPart);
258 int remaining = length - digits;
260 if (remaining < 0 && scale > 0) {
261 // Reduce by scale
262 scaled = true;
263 decimals = maxScaledDecimals;
264 integerPart = integerPart / scale;
265 // Multiply by 10 to get 3 decimal digits
266 millis = ((centivalue % (100 * scale)) * 10) / scale;
267 digits = digitCount(integerPart);
268 remaining = length - digits;
271 // 3 decimals at most
272 decimals = MIN(remaining, MIN(decimals, 3));
273 remaining -= decimals;
275 // Done counting. Time to write the characters.
277 // Write spaces at the start
278 while (remaining > 0) {
279 *ptr = SYM_BLANK;
280 ptr++;
281 remaining--;
284 // Write the minus sign if required
285 if (negative) {
286 *ptr = '-';
287 ptr++;
289 // Now write the digits.
290 ui2a(integerPart, 10, 0, ptr);
291 ptr += digits;
292 if (decimals > 0) {
293 *(ptr-1) += SYM_ZERO_HALF_TRAILING_DOT - '0';
294 dec = ptr;
295 int factor = 3; // we're getting the decimal part in millis first
296 while (decimals < factor) {
297 factor--;
298 millis /= 10;
300 int decimalDigits = digitCount(millis);
301 while (decimalDigits < decimals) {
302 decimalDigits++;
303 *ptr = '0';
304 ptr++;
306 ui2a(millis, 10, 0, ptr);
307 *dec += SYM_ZERO_HALF_LEADING_DOT - '0';
309 return scaled;
313 * Aligns text to the left side. Adds spaces at the end to keep string length unchanged.
315 static void osdLeftAlignString(char *buff)
317 uint8_t sp = 0, ch = 0;
318 uint8_t len = strlen(buff);
319 while (buff[sp] == ' ') sp++;
320 for (ch = 0; ch < (len - sp); ch++) buff[ch] = buff[ch + sp];
321 for (sp = ch; sp < len; sp++) buff[sp] = ' ';
325 * Converts distance into a string based on the current unit system
326 * prefixed by a a symbol to indicate the unit used.
327 * @param dist Distance in centimeters
329 static void osdFormatDistanceSymbol(char *buff, int32_t dist, uint8_t decimals)
331 switch ((osd_unit_e)osdConfig()->units) {
332 case OSD_UNIT_UK:
333 FALLTHROUGH;
334 case OSD_UNIT_IMPERIAL:
335 if (osdFormatCentiNumber(buff, CENTIMETERS_TO_CENTIFEET(dist), FEET_PER_MILE, decimals, 3, 3)) {
336 buff[3] = SYM_DIST_MI;
337 } else {
338 buff[3] = SYM_DIST_FT;
340 buff[4] = '\0';
341 break;
342 case OSD_UNIT_METRIC_MPH:
343 FALLTHROUGH;
344 case OSD_UNIT_METRIC:
345 if (osdFormatCentiNumber(buff, dist, METERS_PER_KILOMETER, decimals, 3, 3)) {
346 buff[3] = SYM_DIST_KM;
347 } else {
348 buff[3] = SYM_DIST_M;
350 buff[4] = '\0';
351 break;
352 case OSD_UNIT_GA:
353 if (osdFormatCentiNumber(buff, CENTIMETERS_TO_CENTIFEET(dist), FEET_PER_NAUTICALMILE, decimals, 3, 3)) {
354 buff[3] = SYM_DIST_NM;
355 } else {
356 buff[3] = SYM_DIST_FT;
358 buff[4] = '\0';
359 break;
364 * Converts distance into a string based on the current unit system.
365 * @param dist Distance in centimeters
367 static void osdFormatDistanceStr(char *buff, int32_t dist)
369 int32_t centifeet;
370 switch ((osd_unit_e)osdConfig()->units) {
371 case OSD_UNIT_UK:
372 FALLTHROUGH;
373 case OSD_UNIT_IMPERIAL:
374 centifeet = CENTIMETERS_TO_CENTIFEET(dist);
375 if (abs(centifeet) < FEET_PER_MILE * 100 / 2) {
376 // Show feet when dist < 0.5mi
377 tfp_sprintf(buff, "%d%c", (int)(centifeet / 100), SYM_FT);
378 } else {
379 // Show miles when dist >= 0.5mi
380 tfp_sprintf(buff, "%d.%02d%c", (int)(centifeet / (100*FEET_PER_MILE)),
381 (abs(centifeet) % (100 * FEET_PER_MILE)) / FEET_PER_MILE, SYM_MI);
383 break;
384 case OSD_UNIT_METRIC_MPH:
385 FALLTHROUGH;
386 case OSD_UNIT_METRIC:
387 if (abs(dist) < METERS_PER_KILOMETER * 100) {
388 // Show meters when dist < 1km
389 tfp_sprintf(buff, "%d%c", (int)(dist / 100), SYM_M);
390 } else {
391 // Show kilometers when dist >= 1km
392 tfp_sprintf(buff, "%d.%02d%c", (int)(dist / (100*METERS_PER_KILOMETER)),
393 (abs(dist) % (100 * METERS_PER_KILOMETER)) / METERS_PER_KILOMETER, SYM_KM);
395 break;
396 case OSD_UNIT_GA:
397 centifeet = CENTIMETERS_TO_CENTIFEET(dist);
398 if (abs(centifeet) < 100000) {
399 // Show feet when dist < 1000ft
400 tfp_sprintf(buff, "%d%c", (int)(centifeet / 100), SYM_FT);
401 } else {
402 // Show nautical miles when dist >= 1000ft
403 tfp_sprintf(buff, "%d.%02d%c", (int)(centifeet / (100 * FEET_PER_NAUTICALMILE)),
404 (int)((abs(centifeet) % (int)(100 * FEET_PER_NAUTICALMILE)) / FEET_PER_NAUTICALMILE), SYM_NM);
406 break;
411 * Converts velocity based on the current unit system (kmh or mph).
412 * @param alt Raw velocity (i.e. as taken from gpsSol.groundSpeed in centimeters/second)
414 static int32_t osdConvertVelocityToUnit(int32_t vel)
416 switch ((osd_unit_e)osdConfig()->units) {
417 case OSD_UNIT_UK:
418 FALLTHROUGH;
419 case OSD_UNIT_METRIC_MPH:
420 FALLTHROUGH;
421 case OSD_UNIT_IMPERIAL:
422 return CMSEC_TO_CENTIMPH(vel) / 100; // Convert to mph
423 case OSD_UNIT_METRIC:
424 return CMSEC_TO_CENTIKPH(vel) / 100; // Convert to kmh
425 case OSD_UNIT_GA:
426 return CMSEC_TO_CENTIKNOTS(vel) / 100; // Convert to Knots
428 // Unreachable
429 return -1;
433 * Converts velocity into a string based on the current unit system.
434 * @param vel Raw velocity (i.e. as taken from gpsSol.groundSpeed in centimeters/seconds)
435 * @param _3D is a 3D velocity
436 * @param _max is a maximum velocity
438 void osdFormatVelocityStr(char* buff, int32_t vel, bool _3D, bool _max)
440 switch ((osd_unit_e)osdConfig()->units) {
441 case OSD_UNIT_UK:
442 FALLTHROUGH;
443 case OSD_UNIT_METRIC_MPH:
444 FALLTHROUGH;
445 case OSD_UNIT_IMPERIAL:
446 if (_max) {
447 tfp_sprintf(buff, "%c%3d%c", SYM_MAX, (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_MPH : SYM_MPH));
448 } else {
449 tfp_sprintf(buff, "%3d%c", (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_MPH : SYM_MPH));
451 break;
452 case OSD_UNIT_METRIC:
453 if (_max) {
454 tfp_sprintf(buff, "%c%3d%c", SYM_MAX, (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_KMH : SYM_KMH));
455 } else {
456 tfp_sprintf(buff, "%3d%c", (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_KMH : SYM_KMH));
458 break;
459 case OSD_UNIT_GA:
460 if (_max) {
461 tfp_sprintf(buff, "%c%3d%c", SYM_MAX, (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_KT : SYM_KT));
462 } else {
463 tfp_sprintf(buff, "%3d%c", (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_KT : SYM_KT));
465 break;
470 * Returns the average velocity. This always uses stats, so can be called as an OSD element later if wanted, to show a real time average
472 static void osdGenerateAverageVelocityStr(char* buff) {
473 uint32_t cmPerSec = getTotalTravelDistance() / getFlightTime();
474 osdFormatVelocityStr(buff, cmPerSec, false, false);
478 * Converts wind speed into a string based on the current unit system, using
479 * always 3 digits and an additional character for the unit at the right. buff
480 * is null terminated.
481 * @param ws Raw wind speed in cm/s
483 #ifdef USE_WIND_ESTIMATOR
484 static void osdFormatWindSpeedStr(char *buff, int32_t ws, bool isValid)
486 int32_t centivalue;
487 char suffix;
488 switch (osdConfig()->units) {
489 case OSD_UNIT_UK:
490 FALLTHROUGH;
491 case OSD_UNIT_METRIC_MPH:
492 FALLTHROUGH;
493 case OSD_UNIT_IMPERIAL:
494 centivalue = CMSEC_TO_CENTIMPH(ws);
495 suffix = SYM_MPH;
496 break;
497 case OSD_UNIT_GA:
498 centivalue = CMSEC_TO_CENTIKNOTS(ws);
499 suffix = SYM_KT;
500 break;
501 default:
502 case OSD_UNIT_METRIC:
503 centivalue = CMSEC_TO_CENTIKPH(ws);
504 suffix = SYM_KMH;
505 break;
507 if (isValid) {
508 osdFormatCentiNumber(buff, centivalue, 0, 2, 0, 3);
509 } else {
510 buff[0] = buff[1] = buff[2] = '-';
512 buff[3] = suffix;
513 buff[4] = '\0';
515 #endif
518 * Converts altitude into a string based on the current unit system
519 * prefixed by a a symbol to indicate the unit used.
520 * @param alt Raw altitude/distance (i.e. as taken from baro.BaroAlt in centimeters)
522 void osdFormatAltitudeSymbol(char *buff, int32_t alt)
524 int digits;
525 if (alt < 0) {
526 digits = 4;
527 } else {
528 digits = 3;
529 buff[0] = ' ';
531 switch ((osd_unit_e)osdConfig()->units) {
532 case OSD_UNIT_UK:
533 FALLTHROUGH;
534 case OSD_UNIT_GA:
535 FALLTHROUGH;
536 case OSD_UNIT_IMPERIAL:
537 if (osdFormatCentiNumber(buff + 4 - digits, CENTIMETERS_TO_CENTIFEET(alt), 1000, 0, 2, digits)) {
538 // Scaled to kft
539 buff[4] = SYM_ALT_KFT;
540 } else {
541 // Formatted in feet
542 buff[4] = SYM_ALT_FT;
544 buff[5] = '\0';
545 break;
546 case OSD_UNIT_METRIC_MPH:
547 FALLTHROUGH;
548 case OSD_UNIT_METRIC:
549 // alt is alredy in cm
550 if (osdFormatCentiNumber(buff + 4 - digits, alt, 1000, 0, 2, digits)) {
551 // Scaled to km
552 buff[4] = SYM_ALT_KM;
553 } else {
554 // Formatted in m
555 buff[4] = SYM_ALT_M;
557 buff[5] = '\0';
558 break;
563 * Converts altitude into a string based on the current unit system.
564 * @param alt Raw altitude/distance (i.e. as taken from baro.BaroAlt in centimeters)
566 static void osdFormatAltitudeStr(char *buff, int32_t alt)
568 int32_t value;
569 switch ((osd_unit_e)osdConfig()->units) {
570 case OSD_UNIT_UK:
571 FALLTHROUGH;
572 case OSD_UNIT_GA:
573 FALLTHROUGH;
574 case OSD_UNIT_IMPERIAL:
575 value = CENTIMETERS_TO_FEET(alt);
576 tfp_sprintf(buff, "%d%c", (int)value, SYM_FT);
577 break;
578 case OSD_UNIT_METRIC_MPH:
579 FALLTHROUGH;
580 case OSD_UNIT_METRIC:
581 value = CENTIMETERS_TO_METERS(alt);
582 tfp_sprintf(buff, "%d%c", (int)value, SYM_M);
583 break;
587 static void osdFormatTime(char *buff, uint32_t seconds, char sym_m, char sym_h)
589 uint32_t value = seconds;
590 char sym = sym_m;
591 // Maximum value we can show in minutes is 99 minutes and 59 seconds
592 if (seconds > (99 * 60) + 59) {
593 sym = sym_h;
594 value = seconds / 60;
596 buff[0] = sym;
597 tfp_sprintf(buff + 1, "%02d:%02d", (int)(value / 60), (int)(value % 60));
600 static inline void osdFormatOnTime(char *buff)
602 osdFormatTime(buff, micros() / 1000000, SYM_ON_M, SYM_ON_H);
605 static inline void osdFormatFlyTime(char *buff, textAttributes_t *attr)
607 uint32_t seconds = getFlightTime();
608 osdFormatTime(buff, seconds, SYM_FLY_M, SYM_FLY_H);
609 if (attr && osdConfig()->time_alarm > 0) {
610 if (seconds / 60 >= osdConfig()->time_alarm && ARMING_FLAG(ARMED)) {
611 TEXT_ATTRIBUTES_ADD_BLINK(*attr);
617 * Converts RSSI into a % value used by the OSD.
619 static uint16_t osdConvertRSSI(void)
621 // change range to [0, 99]
622 return constrain(getRSSI() * 100 / RSSI_MAX_VALUE, 0, 99);
625 static uint16_t osdGetCrsfLQ(void)
627 int16_t statsLQ = rxLinkStatistics.uplinkLQ;
628 int16_t scaledLQ = scaleRange(constrain(statsLQ, 0, 100), 0, 100, 170, 300);
629 int16_t displayedLQ;
630 switch (osdConfig()->crsf_lq_format) {
631 case OSD_CRSF_LQ_TYPE1:
632 displayedLQ = statsLQ;
633 break;
634 case OSD_CRSF_LQ_TYPE2:
635 displayedLQ = statsLQ;
636 break;
637 case OSD_CRSF_LQ_TYPE3:
638 displayedLQ = rxLinkStatistics.rfMode >= 2 ? scaledLQ : statsLQ;
639 break;
641 return displayedLQ;
644 static int16_t osdGetCrsfdBm(void)
646 return rxLinkStatistics.uplinkRSSI;
649 * Displays a temperature postfixed with a symbol depending on the current unit system
650 * @param label to display
651 * @param valid true if measurement is valid
652 * @param temperature in deciDegrees Celcius
654 static void osdDisplayTemperature(uint8_t elemPosX, uint8_t elemPosY, uint16_t symbol, const char *label, bool valid, int16_t temperature, int16_t alarm_min, int16_t alarm_max)
656 char buff[TEMPERATURE_LABEL_LEN + 2 < 6 ? 6 : TEMPERATURE_LABEL_LEN + 2];
657 textAttributes_t elemAttr = valid ? TEXT_ATTRIBUTES_NONE : _TEXT_ATTRIBUTES_BLINK_BIT;
658 uint8_t valueXOffset = 0;
660 if (symbol) {
661 buff[0] = symbol;
662 buff[1] = '\0';
663 displayWriteWithAttr(osdDisplayPort, elemPosX, elemPosY, buff, elemAttr);
664 valueXOffset = 1;
666 #ifdef USE_TEMPERATURE_SENSOR
667 else if (label[0] != '\0') {
668 uint8_t label_len = strnlen(label, TEMPERATURE_LABEL_LEN);
669 memcpy(buff, label, label_len);
670 memset(buff + label_len, ' ', TEMPERATURE_LABEL_LEN + 1 - label_len);
671 buff[5] = '\0';
672 displayWriteWithAttr(osdDisplayPort, elemPosX, elemPosY, buff, elemAttr);
673 valueXOffset = osdConfig()->temp_label_align == OSD_ALIGN_LEFT ? 5 : label_len + 1;
675 #else
676 UNUSED(label);
677 #endif
679 if (valid) {
681 if ((temperature <= alarm_min) || (temperature >= alarm_max)) TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
682 if (osdConfig()->units == OSD_UNIT_IMPERIAL) temperature = temperature * 9 / 5.0f + 320;
683 tfp_sprintf(buff, "%3d", temperature / 10);
685 } else
686 strcpy(buff, "---");
688 buff[3] = osdConfig()->units == OSD_UNIT_IMPERIAL ? SYM_TEMP_F : SYM_TEMP_C;
689 buff[4] = '\0';
691 displayWriteWithAttr(osdDisplayPort, elemPosX + valueXOffset, elemPosY, buff, elemAttr);
694 #ifdef USE_TEMPERATURE_SENSOR
695 static void osdDisplayTemperatureSensor(uint8_t elemPosX, uint8_t elemPosY, uint8_t sensorIndex)
697 int16_t temperature;
698 const bool valid = getSensorTemperature(sensorIndex, &temperature);
699 const tempSensorConfig_t *sensorConfig = tempSensorConfig(sensorIndex);
700 uint16_t symbol = sensorConfig->osdSymbol ? SYM_TEMP_SENSOR_FIRST + sensorConfig->osdSymbol - 1 : 0;
701 osdDisplayTemperature(elemPosX, elemPosY, symbol, sensorConfig->label, valid, temperature, sensorConfig->alarm_min, sensorConfig->alarm_max);
703 #endif
705 static void osdFormatCoordinate(char *buff, char sym, int32_t val)
707 // up to 4 for number + 1 for the symbol + null terminator + fill the rest with decimals
708 const int coordinateLength = osdConfig()->coordinate_digits + 1;
710 buff[0] = sym;
711 int32_t integerPart = val / GPS_DEGREES_DIVIDER;
712 // Latitude maximum integer width is 3 (-90) while
713 // longitude maximum integer width is 4 (-180).
714 int integerDigits = tfp_sprintf(buff + 1, (integerPart == 0 && val < 0) ? "-%d" : "%d", (int)integerPart);
715 // We can show up to 7 digits in decimalPart.
716 int32_t decimalPart = abs(val % GPS_DEGREES_DIVIDER);
717 STATIC_ASSERT(GPS_DEGREES_DIVIDER == 1e7, adjust_max_decimal_digits);
718 int decimalDigits = tfp_sprintf(buff + 1 + integerDigits, "%07d", (int)decimalPart);
719 // Embbed the decimal separator
720 buff[1 + integerDigits - 1] += SYM_ZERO_HALF_TRAILING_DOT - '0';
721 buff[1 + integerDigits] += SYM_ZERO_HALF_LEADING_DOT - '0';
722 // Fill up to coordinateLength with zeros
723 int total = 1 + integerDigits + decimalDigits;
724 while(total < coordinateLength) {
725 buff[total] = '0';
726 total++;
728 buff[coordinateLength] = '\0';
731 static void osdFormatCraftName(char *buff)
733 if (strlen(systemConfig()->name) == 0)
734 strcpy(buff, "CRAFT_NAME");
735 else {
736 for (int i = 0; i < MAX_NAME_LENGTH; i++) {
737 buff[i] = sl_toupper((unsigned char)systemConfig()->name[i]);
738 if (systemConfig()->name[i] == 0)
739 break;
744 static const char * osdArmingDisabledReasonMessage(void)
746 const char *message = NULL;
747 char messageBuf[MAX(SETTING_MAX_NAME_LENGTH, OSD_MESSAGE_LENGTH+1)];
749 switch (isArmingDisabledReason()) {
750 case ARMING_DISABLED_FAILSAFE_SYSTEM:
751 // See handling of FAILSAFE_RX_LOSS_MONITORING in failsafe.c
752 if (failsafePhase() == FAILSAFE_RX_LOSS_MONITORING) {
753 if (failsafeIsReceivingRxData()) {
754 // If we're not using sticks, it means the ARM switch
755 // hasn't been off since entering FAILSAFE_RX_LOSS_MONITORING
756 // yet
757 return OSD_MESSAGE_STR(OSD_MSG_TURN_ARM_SW_OFF);
759 // Not receiving RX data
760 return OSD_MESSAGE_STR(OSD_MSG_RC_RX_LINK_LOST);
762 return OSD_MESSAGE_STR(OSD_MSG_DISABLED_BY_FS);
763 case ARMING_DISABLED_NOT_LEVEL:
764 return OSD_MESSAGE_STR(OSD_MSG_AIRCRAFT_UNLEVEL);
765 case ARMING_DISABLED_SENSORS_CALIBRATING:
766 return OSD_MESSAGE_STR(OSD_MSG_SENSORS_CAL);
767 case ARMING_DISABLED_SYSTEM_OVERLOADED:
768 return OSD_MESSAGE_STR(OSD_MSG_SYS_OVERLOADED);
769 case ARMING_DISABLED_NAVIGATION_UNSAFE:
770 // Check the exact reason
771 switch (navigationIsBlockingArming(NULL)) {
772 char buf[6];
773 case NAV_ARMING_BLOCKER_NONE:
774 break;
775 case NAV_ARMING_BLOCKER_MISSING_GPS_FIX:
776 return OSD_MESSAGE_STR(OSD_MSG_WAITING_GPS_FIX);
777 case NAV_ARMING_BLOCKER_NAV_IS_ALREADY_ACTIVE:
778 return OSD_MESSAGE_STR(OSD_MSG_DISABLE_NAV_FIRST);
779 case NAV_ARMING_BLOCKER_FIRST_WAYPOINT_TOO_FAR:
780 osdFormatDistanceSymbol(buf, distanceToFirstWP(), 0);
781 tfp_sprintf(messageBuf, "FIRST WP TOO FAR (%s)", buf);
782 return message = messageBuf;
783 case NAV_ARMING_BLOCKER_JUMP_WAYPOINT_ERROR:
784 return OSD_MESSAGE_STR(OSD_MSG_JUMP_WP_MISCONFIG);
786 break;
787 case ARMING_DISABLED_COMPASS_NOT_CALIBRATED:
788 return OSD_MESSAGE_STR(OSD_MSG_MAG_NOT_CAL);
789 case ARMING_DISABLED_ACCELEROMETER_NOT_CALIBRATED:
790 return OSD_MESSAGE_STR(OSD_MSG_ACC_NOT_CAL);
791 case ARMING_DISABLED_ARM_SWITCH:
792 return OSD_MESSAGE_STR(OSD_MSG_DISARM_1ST);
793 case ARMING_DISABLED_HARDWARE_FAILURE:
795 if (!HW_SENSOR_IS_HEALTHY(getHwGyroStatus())) {
796 return OSD_MESSAGE_STR(OSD_MSG_GYRO_FAILURE);
798 if (!HW_SENSOR_IS_HEALTHY(getHwAccelerometerStatus())) {
799 return OSD_MESSAGE_STR(OSD_MSG_ACC_FAIL);
801 if (!HW_SENSOR_IS_HEALTHY(getHwCompassStatus())) {
802 return OSD_MESSAGE_STR(OSD_MSG_MAG_FAIL);
804 if (!HW_SENSOR_IS_HEALTHY(getHwBarometerStatus())) {
805 return OSD_MESSAGE_STR(OSD_MSG_BARO_FAIL);
807 if (!HW_SENSOR_IS_HEALTHY(getHwGPSStatus())) {
808 return OSD_MESSAGE_STR(OSD_MSG_GPS_FAIL);
810 if (!HW_SENSOR_IS_HEALTHY(getHwRangefinderStatus())) {
811 return OSD_MESSAGE_STR(OSD_MSG_RANGEFINDER_FAIL);
813 if (!HW_SENSOR_IS_HEALTHY(getHwPitotmeterStatus())) {
814 return OSD_MESSAGE_STR(OSD_MSG_PITOT_FAIL);
817 return OSD_MESSAGE_STR(OSD_MSG_HW_FAIL);
818 case ARMING_DISABLED_BOXFAILSAFE:
819 return OSD_MESSAGE_STR(OSD_MSG_FS_EN);
820 case ARMING_DISABLED_BOXKILLSWITCH:
821 return OSD_MESSAGE_STR(OSD_MSG_KILL_SW_EN);
822 case ARMING_DISABLED_RC_LINK:
823 return OSD_MESSAGE_STR(OSD_MSG_NO_RC_LINK);
824 case ARMING_DISABLED_THROTTLE:
825 return OSD_MESSAGE_STR(OSD_MSG_THROTTLE_NOT_LOW);
826 case ARMING_DISABLED_ROLLPITCH_NOT_CENTERED:
827 return OSD_MESSAGE_STR(OSD_MSG_ROLLPITCH_OFFCENTER);
828 case ARMING_DISABLED_SERVO_AUTOTRIM:
829 return OSD_MESSAGE_STR(OSD_MSG_AUTOTRIM_ACTIVE);
830 case ARMING_DISABLED_OOM:
831 return OSD_MESSAGE_STR(OSD_MSG_NOT_ENOUGH_MEMORY);
832 case ARMING_DISABLED_INVALID_SETTING:
833 return OSD_MESSAGE_STR(OSD_MSG_INVALID_SETTING);
834 case ARMING_DISABLED_CLI:
835 return OSD_MESSAGE_STR(OSD_MSG_CLI_ACTIVE);
836 case ARMING_DISABLED_PWM_OUTPUT_ERROR:
837 return OSD_MESSAGE_STR(OSD_MSG_PWM_INIT_ERROR);
838 case ARMING_DISABLED_NO_PREARM:
839 return OSD_MESSAGE_STR(OSD_MSG_NO_PREARM);
840 case ARMING_DISABLED_DSHOT_BEEPER:
841 return OSD_MESSAGE_STR(OSD_MSG_DSHOT_BEEPER);
842 // Cases without message
843 case ARMING_DISABLED_LANDING_DETECTED:
844 FALLTHROUGH;
845 case ARMING_DISABLED_CMS_MENU:
846 FALLTHROUGH;
847 case ARMING_DISABLED_OSD_MENU:
848 FALLTHROUGH;
849 case ARMING_DISABLED_ALL_FLAGS:
850 FALLTHROUGH;
851 case ARMED:
852 FALLTHROUGH;
853 case SIMULATOR_MODE:
854 FALLTHROUGH;
855 case WAS_EVER_ARMED:
856 break;
858 return NULL;
861 static const char * osdFailsafePhaseMessage(void)
863 // See failsafe.h for each phase explanation
864 switch (failsafePhase()) {
865 case FAILSAFE_RETURN_TO_HOME:
866 // XXX: Keep this in sync with OSD_FLYMODE.
867 return OSD_MESSAGE_STR(OSD_MSG_RTH_FS);
868 case FAILSAFE_LANDING:
869 // This should be considered an emergengy landing
870 return OSD_MESSAGE_STR(OSD_MSG_EMERG_LANDING_FS);
871 case FAILSAFE_RX_LOSS_MONITORING:
872 // Only reachable from FAILSAFE_LANDED, which performs
873 // a disarm. Since aircraft has been disarmed, we no
874 // longer show failsafe details.
875 FALLTHROUGH;
876 case FAILSAFE_LANDED:
877 // Very brief, disarms and transitions into
878 // FAILSAFE_RX_LOSS_MONITORING. Note that it prevents
879 // further rearming via ARMING_DISABLED_FAILSAFE_SYSTEM,
880 // so we'll show the user how to re-arm in when
881 // that flag is the reason to prevent arming.
882 FALLTHROUGH;
883 case FAILSAFE_RX_LOSS_IDLE:
884 // This only happens when user has chosen NONE as FS
885 // procedure. The recovery messages should be enough.
886 FALLTHROUGH;
887 case FAILSAFE_IDLE:
888 // Failsafe not active
889 FALLTHROUGH;
890 case FAILSAFE_RX_LOSS_DETECTED:
891 // Very brief, changes to FAILSAFE_RX_LOSS_RECOVERED
892 // or the FS procedure immediately.
893 FALLTHROUGH;
894 case FAILSAFE_RX_LOSS_RECOVERED:
895 // Exiting failsafe
896 break;
898 return NULL;
901 static const char * osdFailsafeInfoMessage(void)
903 if (failsafeIsReceivingRxData()) {
904 // User must move sticks to exit FS mode
905 return OSD_MESSAGE_STR(OSD_MSG_MOVE_EXIT_FS);
907 return OSD_MESSAGE_STR(OSD_MSG_RC_RX_LINK_LOST);
909 #if defined(USE_SAFE_HOME)
910 static const char * divertingToSafehomeMessage(void)
912 if (NAV_Status.state != MW_NAV_STATE_HOVER_ABOVE_HOME && safehome_applied) {
913 return OSD_MESSAGE_STR(OSD_MSG_DIVERT_SAFEHOME);
915 return NULL;
917 #endif
919 static const char * navigationStateMessage(void)
921 switch (NAV_Status.state) {
922 case MW_NAV_STATE_NONE:
923 break;
924 case MW_NAV_STATE_RTH_START:
925 return OSD_MESSAGE_STR(OSD_MSG_STARTING_RTH);
926 case MW_NAV_STATE_RTH_CLIMB:
927 return OSD_MESSAGE_STR(OSD_MSG_RTH_CLIMB);
928 case MW_NAV_STATE_RTH_ENROUTE:
929 if (posControl.flags.rthTrackbackActive) {
930 return OSD_MESSAGE_STR(OSD_MSG_RTH_TRACKBACK);
931 } else {
932 return OSD_MESSAGE_STR(OSD_MSG_HEADING_HOME);
934 case MW_NAV_STATE_HOLD_INFINIT:
935 // Used by HOLD flight modes. No information to add.
936 break;
937 case MW_NAV_STATE_HOLD_TIMED:
938 // "HOLDING WP FOR xx S" Countdown added in osdGetSystemMessage
939 break;
940 case MW_NAV_STATE_WP_ENROUTE:
941 // "TO WP" + WP countdown added in osdGetSystemMessage
942 break;
943 case MW_NAV_STATE_PROCESS_NEXT:
944 return OSD_MESSAGE_STR(OSD_MSG_PREPARE_NEXT_WP);
945 case MW_NAV_STATE_DO_JUMP:
946 // Not used
947 break;
948 case MW_NAV_STATE_LAND_START:
949 // Not used
950 break;
951 case MW_NAV_STATE_EMERGENCY_LANDING:
952 return OSD_MESSAGE_STR(OSD_MSG_EMERG_LANDING);
953 case MW_NAV_STATE_LAND_IN_PROGRESS:
954 return OSD_MESSAGE_STR(OSD_MSG_LANDING);
955 case MW_NAV_STATE_HOVER_ABOVE_HOME:
956 if (STATE(FIXED_WING_LEGACY)) {
957 #if defined(USE_SAFE_HOME)
958 if (safehome_applied) {
959 return OSD_MESSAGE_STR(OSD_MSG_LOITERING_SAFEHOME);
961 #endif
962 return OSD_MESSAGE_STR(OSD_MSG_LOITERING_HOME);
964 return OSD_MESSAGE_STR(OSD_MSG_HOVERING);
965 case MW_NAV_STATE_LANDED:
966 return OSD_MESSAGE_STR(OSD_MSG_LANDED);
967 case MW_NAV_STATE_LAND_SETTLE:
968 return OSD_MESSAGE_STR(OSD_MSG_PREPARING_LAND);
969 case MW_NAV_STATE_LAND_START_DESCENT:
970 // Not used
971 break;
973 return NULL;
976 static void osdFormatMessage(char *buff, size_t size, const char *message, bool isCenteredText)
978 // String is always filled with Blanks
979 memset(buff, SYM_BLANK, size);
980 if (message) {
981 size_t messageLength = strlen(message);
982 int rem = isCenteredText ? MAX(0, (int)size - (int)messageLength) : 0;
983 strncpy(buff + rem / 2, message, MIN((int)size - rem / 2, (int)messageLength));
985 // Ensure buff is zero terminated
986 buff[size] = '\0';
990 * Draws the battery symbol filled in accordingly to the
991 * battery voltage to buff[0].
993 static void osdFormatBatteryChargeSymbol(char *buff)
995 uint8_t p = calculateBatteryPercentage();
996 p = (100 - p) / 16.6;
997 buff[0] = SYM_BATT_FULL + p;
1000 static void osdUpdateBatteryCapacityOrVoltageTextAttributes(textAttributes_t *attr)
1002 if ((getBatteryState() != BATTERY_NOT_PRESENT) && ((batteryUsesCapacityThresholds() && (getBatteryRemainingCapacity() <= currentBatteryProfile->capacity.warning - currentBatteryProfile->capacity.critical)) || ((!batteryUsesCapacityThresholds()) && (getBatteryVoltage() <= getBatteryWarningVoltage()))))
1003 TEXT_ATTRIBUTES_ADD_BLINK(*attr);
1006 void osdCrosshairPosition(uint8_t *x, uint8_t *y)
1008 *x = osdDisplayPort->cols / 2;
1009 *y = osdDisplayPort->rows / 2;
1010 *y -= osdConfig()->horizon_offset; // positive horizon_offset moves the HUD up, negative moves down
1014 * Formats throttle position prefixed by its symbol.
1015 * Shows output to motor, not stick position
1017 static void osdFormatThrottlePosition(char *buff, bool autoThr, textAttributes_t *elemAttr)
1019 buff[0] = SYM_BLANK;
1020 buff[1] = SYM_THR;
1021 if (autoThr && navigationIsControllingThrottle()) {
1022 buff[0] = SYM_AUTO_THR0;
1023 buff[1] = SYM_AUTO_THR1;
1024 if (isFixedWingAutoThrottleManuallyIncreased()) {
1025 TEXT_ATTRIBUTES_ADD_BLINK(*elemAttr);
1028 #ifdef USE_POWER_LIMITS
1029 if (powerLimiterIsLimiting()) {
1030 TEXT_ATTRIBUTES_ADD_BLINK(*elemAttr);
1032 #endif
1033 tfp_sprintf(buff + 2, "%3d", getThrottlePercent());
1037 * Formats gvars prefixed by its number (0-indexed). If autoThr
1039 static void osdFormatGVar(char *buff, uint8_t index)
1041 buff[0] = 'G';
1042 buff[1] = '0'+index;
1043 buff[2] = ':';
1044 #ifdef USE_PROGRAMMING_FRAMEWORK
1045 osdFormatCentiNumber(buff + 3, (int32_t)gvGet(index)*(int32_t)100, 1, 0, 0, 5);
1046 #endif
1049 #if defined(USE_ESC_SENSOR)
1050 static void osdFormatRpm(char *buff, uint32_t rpm)
1052 buff[0] = SYM_RPM;
1053 if (rpm) {
1054 if ( digitCount(rpm) > osdConfig()->esc_rpm_precision) {
1055 uint8_t rpmMaxDecimals = (osdConfig()->esc_rpm_precision - 3);
1056 osdFormatCentiNumber(buff + 1, rpm / 10, 0, rpmMaxDecimals, rpmMaxDecimals, osdConfig()->esc_rpm_precision-1);
1057 buff[osdConfig()->esc_rpm_precision] = 'K';
1058 buff[osdConfig()->esc_rpm_precision+1] = '\0';
1060 else {
1061 switch(osdConfig()->esc_rpm_precision) {
1062 case 6:
1063 tfp_sprintf(buff + 1, "%6lu", rpm);
1064 break;
1065 case 5:
1066 tfp_sprintf(buff + 1, "%5lu", rpm);
1067 break;
1068 case 4:
1069 tfp_sprintf(buff + 1, "%4lu", rpm);
1070 break;
1071 case 3:
1072 default:
1073 tfp_sprintf(buff + 1, "%3lu", rpm);
1074 break;
1080 else {
1081 uint8_t buffPos = 1;
1082 while (buffPos <=( osdConfig()->esc_rpm_precision)) {
1083 strcpy(buff + buffPos++, "-");
1087 #endif
1089 int32_t osdGetAltitude(void)
1091 return getEstimatedActualPosition(Z);
1094 static inline int32_t osdGetAltitudeMsl(void)
1096 return getEstimatedActualPosition(Z)+GPS_home.alt;
1099 uint16_t osdGetRemainingGlideTime(void) {
1100 float value = getEstimatedActualVelocity(Z);
1101 static pt1Filter_t glideTimeFilterState;
1102 const timeMs_t curTimeMs = millis();
1103 static timeMs_t glideTimeUpdatedMs;
1105 value = pt1FilterApply4(&glideTimeFilterState, isnormal(value) ? value : 0, 0.5, MS2S(curTimeMs - glideTimeUpdatedMs));
1106 glideTimeUpdatedMs = curTimeMs;
1108 if (value < 0) {
1109 value = osdGetAltitude() / abs((int)value);
1110 } else {
1111 value = 0;
1114 return (uint16_t)round(value);
1117 static bool osdIsHeadingValid(void)
1119 return isImuHeadingValid();
1122 int16_t osdGetHeading(void)
1124 return attitude.values.yaw;
1127 int16_t osdPanServoHomeDirectionOffset(void)
1129 int8_t servoIndex = osdConfig()->pan_servo_index;
1130 int16_t servoPosition = servo[servoIndex];
1131 int16_t servoMiddle = servoParams(servoIndex)->middle;
1132 return (int16_t)CENTIDEGREES_TO_DEGREES((servoPosition - servoMiddle) * osdConfig()->pan_servo_pwm2centideg);
1135 // Returns a heading angle in degrees normalized to [0, 360).
1136 int osdGetHeadingAngle(int angle)
1138 while (angle < 0) {
1139 angle += 360;
1141 while (angle >= 360) {
1142 angle -= 360;
1144 return angle;
1147 #if defined(USE_GPS)
1149 /* Draws a map with the given symbol in the center and given point of interest
1150 * defined by its distance in meters and direction in degrees.
1151 * referenceHeading indicates the up direction in the map, in degrees, while
1152 * referenceSym (if non-zero) is drawn at the upper right corner below a small
1153 * arrow to indicate the map reference to the user. The drawn argument is an
1154 * in-out used to store the last position where the craft was drawn to avoid
1155 * erasing all screen on each redraw.
1157 static void osdDrawMap(int referenceHeading, uint16_t referenceSym, uint16_t centerSym,
1158 uint32_t poiDistance, int16_t poiDirection, uint16_t poiSymbol,
1159 uint16_t *drawn, uint32_t *usedScale)
1161 // TODO: These need to be tested with several setups. We might
1162 // need to make them configurable.
1163 const int hMargin = 5;
1164 const int vMargin = 3;
1166 // TODO: Get this from the display driver?
1167 const int charWidth = 12;
1168 const int charHeight = 18;
1170 uint8_t minX = hMargin;
1171 uint8_t maxX = osdDisplayPort->cols - 1 - hMargin;
1172 uint8_t minY = vMargin;
1173 uint8_t maxY = osdDisplayPort->rows - 1 - vMargin;
1174 uint8_t midX = osdDisplayPort->cols / 2;
1175 uint8_t midY = osdDisplayPort->rows / 2;
1177 // Fixed marks
1178 displayWriteChar(osdDisplayPort, midX, midY, centerSym);
1180 // First, erase the previous drawing.
1181 if (OSD_VISIBLE(*drawn)) {
1182 displayWriteChar(osdDisplayPort, OSD_X(*drawn), OSD_Y(*drawn), SYM_BLANK);
1183 *drawn = 0;
1186 uint32_t initialScale;
1187 const unsigned scaleMultiplier = 2;
1188 // We try to reduce the scale when the POI will be around half the distance
1189 // between the center and the closers map edge, to avoid too much jumping
1190 const int scaleReductionMultiplier = MIN(midX - hMargin, midY - vMargin) / 2;
1192 switch (osdConfig()->units) {
1193 case OSD_UNIT_UK:
1194 FALLTHROUGH;
1195 case OSD_UNIT_IMPERIAL:
1196 initialScale = 16; // 16m ~= 0.01miles
1197 break;
1198 case OSD_UNIT_GA:
1199 initialScale = 18; // 18m ~= 0.01 nautical miles
1200 break;
1201 default:
1202 case OSD_UNIT_METRIC_MPH:
1203 FALLTHROUGH;
1204 case OSD_UNIT_METRIC:
1205 initialScale = 10; // 10m as initial scale
1206 break;
1209 // Try to keep the same scale when getting closer until we draw over the center point
1210 uint32_t scale = initialScale;
1211 if (*usedScale) {
1212 scale = *usedScale;
1213 if (scale > initialScale && poiDistance < *usedScale * scaleReductionMultiplier) {
1214 scale /= scaleMultiplier;
1218 if (STATE(GPS_FIX)) {
1220 int directionToPoi = osdGetHeadingAngle(poiDirection - referenceHeading);
1221 float poiAngle = DEGREES_TO_RADIANS(directionToPoi);
1222 float poiSin = sin_approx(poiAngle);
1223 float poiCos = cos_approx(poiAngle);
1225 // Now start looking for a valid scale that lets us draw everything
1226 int ii;
1227 for (ii = 0; ii < 50; ii++) {
1228 // Calculate location of the aircraft in map
1229 int points = poiDistance / ((float)scale / charHeight);
1231 float pointsX = points * poiSin;
1232 int poiX = midX - roundf(pointsX / charWidth);
1233 if (poiX < minX || poiX > maxX) {
1234 scale *= scaleMultiplier;
1235 continue;
1238 float pointsY = points * poiCos;
1239 int poiY = midY + roundf(pointsY / charHeight);
1240 if (poiY < minY || poiY > maxY) {
1241 scale *= scaleMultiplier;
1242 continue;
1245 if (poiX == midX && poiY == midY) {
1246 // We're over the map center symbol, so we would be drawing
1247 // over it even if we increased the scale. Alternate between
1248 // drawing the center symbol or drawing the POI.
1249 if (centerSym != SYM_BLANK && OSD_ALTERNATING_CHOICES(1000, 2) == 0) {
1250 break;
1252 } else {
1254 uint16_t c;
1255 if (displayReadCharWithAttr(osdDisplayPort, poiX, poiY, &c, NULL) && c != SYM_BLANK) {
1256 // Something else written here, increase scale. If the display doesn't support reading
1257 // back characters, we assume there's nothing.
1259 // If we're close to the center, decrease scale. Otherwise increase it.
1260 uint8_t centerDeltaX = (maxX - minX) / (scaleMultiplier * 2);
1261 uint8_t centerDeltaY = (maxY - minY) / (scaleMultiplier * 2);
1262 if (poiX >= midX - centerDeltaX && poiX <= midX + centerDeltaX &&
1263 poiY >= midY - centerDeltaY && poiY <= midY + centerDeltaY &&
1264 scale > scaleMultiplier) {
1266 scale /= scaleMultiplier;
1267 } else {
1268 scale *= scaleMultiplier;
1270 continue;
1274 // Draw the point on the map
1275 if (poiSymbol == SYM_ARROW_UP) {
1276 // Drawing aircraft, rotate
1277 int mapHeading = osdGetHeadingAngle(DECIDEGREES_TO_DEGREES(osdGetHeading()) - referenceHeading);
1278 poiSymbol += mapHeading * 2 / 45;
1280 displayWriteChar(osdDisplayPort, poiX, poiY, poiSymbol);
1282 // Update saved location
1283 *drawn = OSD_POS(poiX, poiY) | OSD_VISIBLE_FLAG;
1284 break;
1288 *usedScale = scale;
1290 // Update global map data for scale and reference
1291 osdMapData.scale = scale;
1292 osdMapData.referenceSymbol = referenceSym;
1295 /* Draws a map with the home in the center and the craft moving around.
1296 * See osdDrawMap() for reference.
1298 static void osdDrawHomeMap(int referenceHeading, uint8_t referenceSym, uint16_t *drawn, uint32_t *usedScale)
1300 osdDrawMap(referenceHeading, referenceSym, SYM_HOME, GPS_distanceToHome, GPS_directionToHome, SYM_ARROW_UP, drawn, usedScale);
1303 /* Draws a map with the aircraft in the center and the home moving around.
1304 * See osdDrawMap() for reference.
1306 static void osdDrawRadar(uint16_t *drawn, uint32_t *usedScale)
1308 int16_t reference = DECIDEGREES_TO_DEGREES(osdGetHeading());
1309 int16_t poiDirection = osdGetHeadingAngle(GPS_directionToHome + 180);
1310 osdDrawMap(reference, 0, SYM_ARROW_UP, GPS_distanceToHome, poiDirection, SYM_HOME, drawn, usedScale);
1313 static uint16_t crc_accumulate(uint8_t data, uint16_t crcAccum)
1315 uint8_t tmp;
1316 tmp = data ^ (uint8_t)(crcAccum & 0xff);
1317 tmp ^= (tmp << 4);
1318 crcAccum = (crcAccum >> 8) ^ (tmp << 8) ^ (tmp << 3) ^ (tmp >> 4);
1319 return crcAccum;
1323 static void osdDisplayTelemetry(void)
1325 uint32_t trk_data;
1326 uint16_t trk_crc = 0;
1327 char trk_buffer[31];
1328 static int16_t trk_elevation = 127;
1329 static uint16_t trk_bearing = 0;
1331 if (ARMING_FLAG(ARMED)) {
1332 if (STATE(GPS_FIX)){
1333 if (GPS_distanceToHome > 5) {
1334 trk_bearing = GPS_directionToHome;
1335 trk_bearing += 360 + 180;
1336 trk_bearing %= 360;
1337 int32_t alt = CENTIMETERS_TO_METERS(osdGetAltitude());
1338 float at = atan2(alt, GPS_distanceToHome);
1339 trk_elevation = (float)at * 57.2957795; // 57.2957795 = 1 rad
1340 trk_elevation += 37; // because elevation in telemetry should be from -37 to 90
1341 if (trk_elevation < 0) {
1342 trk_elevation = 0;
1347 else{
1348 trk_elevation = 127;
1349 trk_bearing = 0;
1352 trk_data = 0; // bit 0 - packet type 0 = bearing/elevation, 1 = 2 byte data packet
1353 trk_data = trk_data | (uint32_t)(0x7F & trk_elevation) << 1; // bits 1-7 - elevation angle to target. NOTE number is abused. constrained value of -37 to 90 sent as 0 to 127.
1354 trk_data = trk_data | (uint32_t)trk_bearing << 8; // bits 8-17 - bearing angle to target. 0 = true north. 0 to 360
1355 trk_crc = crc_accumulate(0xFF & trk_data, trk_crc); // CRC First Byte bits 0-7
1356 trk_crc = crc_accumulate(0xFF & trk_bearing, trk_crc); // CRC Second Byte bits 8-15
1357 trk_crc = crc_accumulate(trk_bearing >> 8, trk_crc); // CRC Third Byte bits 16-17
1358 trk_data = trk_data | (uint32_t)trk_crc << 17; // bits 18-29 CRC & 0x3FFFF
1360 for (uint8_t t_ctr = 0; t_ctr < 30; t_ctr++) { // Prepare screen buffer and write data line.
1361 if (trk_data & (uint32_t)1 << t_ctr){
1362 trk_buffer[29 - t_ctr] = SYM_TELEMETRY_0;
1364 else{
1365 trk_buffer[29 - t_ctr] = SYM_TELEMETRY_1;
1368 trk_buffer[30] = 0;
1369 displayWrite(osdDisplayPort, 0, 0, trk_buffer);
1370 if (osdConfig()->telemetry>1){
1371 displayWrite(osdDisplayPort, 0, 3, trk_buffer); // Test display because normal telemetry line is not visible
1374 #endif
1376 static void osdFormatPidControllerOutput(char *buff, const char *label, const pidController_t *pidController, uint8_t scale, bool showDecimal) {
1377 strcpy(buff, label);
1378 for (uint8_t i = strlen(label); i < 5; ++i) buff[i] = ' ';
1379 uint8_t decimals = showDecimal ? 1 : 0;
1380 osdFormatCentiNumber(buff + 5, pidController->proportional * scale, 0, decimals, 0, 4);
1381 buff[9] = ' ';
1382 osdFormatCentiNumber(buff + 10, pidController->integrator * scale, 0, decimals, 0, 4);
1383 buff[14] = ' ';
1384 osdFormatCentiNumber(buff + 15, pidController->derivative * scale, 0, decimals, 0, 4);
1385 buff[19] = ' ';
1386 osdFormatCentiNumber(buff + 20, pidController->output_constrained * scale, 0, decimals, 0, 4);
1387 buff[24] = '\0';
1390 static void osdDisplayBatteryVoltage(uint8_t elemPosX, uint8_t elemPosY, uint16_t voltage, uint8_t digits, uint8_t decimals)
1392 char buff[6];
1393 textAttributes_t elemAttr = TEXT_ATTRIBUTES_NONE;
1395 osdFormatBatteryChargeSymbol(buff);
1396 buff[1] = '\0';
1397 osdUpdateBatteryCapacityOrVoltageTextAttributes(&elemAttr);
1398 displayWriteWithAttr(osdDisplayPort, elemPosX, elemPosY, buff, elemAttr);
1400 elemAttr = TEXT_ATTRIBUTES_NONE;
1401 digits = MIN(digits, 4);
1402 osdFormatCentiNumber(buff, voltage, 0, decimals, 0, digits);
1403 buff[digits] = SYM_VOLT;
1404 buff[digits+1] = '\0';
1405 if ((getBatteryState() != BATTERY_NOT_PRESENT) && (getBatteryVoltage() <= getBatteryWarningVoltage()))
1406 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1407 displayWriteWithAttr(osdDisplayPort, elemPosX + 1, elemPosY, buff, elemAttr);
1410 static void osdDisplayFlightPIDValues(uint8_t elemPosX, uint8_t elemPosY, const char *str, pidIndex_e pidIndex, adjustmentFunction_e adjFuncP, adjustmentFunction_e adjFuncI, adjustmentFunction_e adjFuncD, adjustmentFunction_e adjFuncFF)
1412 textAttributes_t elemAttr;
1413 char buff[4];
1415 const pid8_t *pid = &pidBank()->pid[pidIndex];
1416 pidType_e pidType = pidIndexGetType(pidIndex);
1418 displayWrite(osdDisplayPort, elemPosX, elemPosY, str);
1420 if (pidType == PID_TYPE_NONE) {
1421 // PID is not used in this configuration. Draw dashes.
1422 // XXX: Keep this in sync with the %3d format and spacing used below
1423 displayWrite(osdDisplayPort, elemPosX + 6, elemPosY, "- - - -");
1424 return;
1427 elemAttr = TEXT_ATTRIBUTES_NONE;
1428 tfp_sprintf(buff, "%3d", pid->P);
1429 if ((isAdjustmentFunctionSelected(adjFuncP)) || (((adjFuncP == ADJUSTMENT_ROLL_P) || (adjFuncP == ADJUSTMENT_PITCH_P)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_P))))
1430 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1431 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
1433 elemAttr = TEXT_ATTRIBUTES_NONE;
1434 tfp_sprintf(buff, "%3d", pid->I);
1435 if ((isAdjustmentFunctionSelected(adjFuncI)) || (((adjFuncI == ADJUSTMENT_ROLL_I) || (adjFuncI == ADJUSTMENT_PITCH_I)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_I))))
1436 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1437 displayWriteWithAttr(osdDisplayPort, elemPosX + 8, elemPosY, buff, elemAttr);
1439 elemAttr = TEXT_ATTRIBUTES_NONE;
1440 tfp_sprintf(buff, "%3d", pid->D);
1441 if ((isAdjustmentFunctionSelected(adjFuncD)) || (((adjFuncD == ADJUSTMENT_ROLL_D) || (adjFuncD == ADJUSTMENT_PITCH_D)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_D))))
1442 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1443 displayWriteWithAttr(osdDisplayPort, elemPosX + 12, elemPosY, buff, elemAttr);
1445 elemAttr = TEXT_ATTRIBUTES_NONE;
1446 tfp_sprintf(buff, "%3d", pid->FF);
1447 if ((isAdjustmentFunctionSelected(adjFuncFF)) || (((adjFuncFF == ADJUSTMENT_ROLL_FF) || (adjFuncFF == ADJUSTMENT_PITCH_FF)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_FF))))
1448 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1449 displayWriteWithAttr(osdDisplayPort, elemPosX + 16, elemPosY, buff, elemAttr);
1452 static void osdDisplayNavPIDValues(uint8_t elemPosX, uint8_t elemPosY, const char *str, pidIndex_e pidIndex, adjustmentFunction_e adjFuncP, adjustmentFunction_e adjFuncI, adjustmentFunction_e adjFuncD)
1454 textAttributes_t elemAttr;
1455 char buff[4];
1457 const pid8_t *pid = &pidBank()->pid[pidIndex];
1458 pidType_e pidType = pidIndexGetType(pidIndex);
1460 displayWrite(osdDisplayPort, elemPosX, elemPosY, str);
1462 if (pidType == PID_TYPE_NONE) {
1463 // PID is not used in this configuration. Draw dashes.
1464 // XXX: Keep this in sync with the %3d format and spacing used below
1465 displayWrite(osdDisplayPort, elemPosX + 6, elemPosY, "- - -");
1466 return;
1469 elemAttr = TEXT_ATTRIBUTES_NONE;
1470 tfp_sprintf(buff, "%3d", pid->P);
1471 if ((isAdjustmentFunctionSelected(adjFuncP)) || (((adjFuncP == ADJUSTMENT_ROLL_P) || (adjFuncP == ADJUSTMENT_PITCH_P)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_P))))
1472 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1473 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
1475 elemAttr = TEXT_ATTRIBUTES_NONE;
1476 tfp_sprintf(buff, "%3d", pid->I);
1477 if ((isAdjustmentFunctionSelected(adjFuncI)) || (((adjFuncI == ADJUSTMENT_ROLL_I) || (adjFuncI == ADJUSTMENT_PITCH_I)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_I))))
1478 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1479 displayWriteWithAttr(osdDisplayPort, elemPosX + 8, elemPosY, buff, elemAttr);
1481 elemAttr = TEXT_ATTRIBUTES_NONE;
1482 tfp_sprintf(buff, "%3d", pidType == PID_TYPE_PIFF ? pid->FF : pid->D);
1483 if ((isAdjustmentFunctionSelected(adjFuncD)) || (((adjFuncD == ADJUSTMENT_ROLL_D) || (adjFuncD == ADJUSTMENT_PITCH_D)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_D))))
1484 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1485 displayWriteWithAttr(osdDisplayPort, elemPosX + 12, elemPosY, buff, elemAttr);
1488 static void osdDisplayAdjustableDecimalValue(uint8_t elemPosX, uint8_t elemPosY, const char *str, const uint8_t valueOffset, const float value, const uint8_t valueLength, const uint8_t maxDecimals, adjustmentFunction_e adjFunc) {
1489 char buff[8];
1490 textAttributes_t elemAttr;
1491 displayWrite(osdDisplayPort, elemPosX, elemPosY, str);
1493 elemAttr = TEXT_ATTRIBUTES_NONE;
1494 osdFormatCentiNumber(buff, value * 100, 0, maxDecimals, 0, MIN(valueLength, 8));
1495 if (isAdjustmentFunctionSelected(adjFunc))
1496 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1497 displayWriteWithAttr(osdDisplayPort, elemPosX + strlen(str) + 1 + valueOffset, elemPosY, buff, elemAttr);
1500 int8_t getGeoWaypointNumber(int8_t waypointIndex)
1502 static int8_t lastWaypointIndex = 1;
1503 static int8_t geoWaypointIndex;
1505 if (waypointIndex != lastWaypointIndex) {
1506 lastWaypointIndex = geoWaypointIndex = waypointIndex;
1507 for (uint8_t i = posControl.startWpIndex; i <= waypointIndex; i++) {
1508 if (posControl.waypointList[i].action == NAV_WP_ACTION_SET_POI ||
1509 posControl.waypointList[i].action == NAV_WP_ACTION_SET_HEAD ||
1510 posControl.waypointList[i].action == NAV_WP_ACTION_JUMP) {
1511 geoWaypointIndex -= 1;
1516 return geoWaypointIndex - posControl.startWpIndex + 1;
1519 void osdDisplaySwitchIndicator(const char *swName, int rcValue, char *buff) {
1520 int8_t ptr = 0;
1522 if (osdConfig()->osd_switch_indicators_align_left) {
1523 for (ptr = 0; ptr < constrain(strlen(swName), 0, OSD_SWITCH_INDICATOR_NAME_LENGTH); ptr++) {
1524 buff[ptr] = swName[ptr];
1527 if ( rcValue < 1333) {
1528 buff[ptr++] = SYM_SWITCH_INDICATOR_LOW;
1529 } else if ( rcValue > 1666) {
1530 buff[ptr++] = SYM_SWITCH_INDICATOR_HIGH;
1531 } else {
1532 buff[ptr++] = SYM_SWITCH_INDICATOR_MID;
1534 } else {
1535 if ( rcValue < 1333) {
1536 buff[ptr++] = SYM_SWITCH_INDICATOR_LOW;
1537 } else if ( rcValue > 1666) {
1538 buff[ptr++] = SYM_SWITCH_INDICATOR_HIGH;
1539 } else {
1540 buff[ptr++] = SYM_SWITCH_INDICATOR_MID;
1543 for (ptr = 1; ptr < constrain(strlen(swName), 0, OSD_SWITCH_INDICATOR_NAME_LENGTH) + 1; ptr++) {
1544 buff[ptr] = swName[ptr-1];
1547 ptr++;
1550 buff[ptr] = '\0';
1553 static bool osdDrawSingleElement(uint8_t item)
1555 uint16_t pos = osdLayoutsConfig()->item_pos[currentLayout][item];
1556 if (!OSD_VISIBLE(pos)) {
1557 return false;
1559 uint8_t elemPosX = OSD_X(pos);
1560 uint8_t elemPosY = OSD_Y(pos);
1561 textAttributes_t elemAttr = TEXT_ATTRIBUTES_NONE;
1562 char buff[32] = {0};
1564 switch (item) {
1565 case OSD_RSSI_VALUE:
1567 uint16_t osdRssi = osdConvertRSSI();
1568 buff[0] = SYM_RSSI;
1569 tfp_sprintf(buff + 1, "%2d", osdRssi);
1570 if (osdRssi < osdConfig()->rssi_alarm) {
1571 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1573 break;
1576 case OSD_MAIN_BATT_VOLTAGE:
1577 osdDisplayBatteryVoltage(elemPosX, elemPosY, getBatteryRawVoltage(), 2 + osdConfig()->main_voltage_decimals, osdConfig()->main_voltage_decimals);
1578 return true;
1580 case OSD_SAG_COMPENSATED_MAIN_BATT_VOLTAGE:
1581 osdDisplayBatteryVoltage(elemPosX, elemPosY, getBatterySagCompensatedVoltage(), 2 + osdConfig()->main_voltage_decimals, osdConfig()->main_voltage_decimals);
1582 return true;
1584 case OSD_CURRENT_DRAW:
1585 osdFormatCentiNumber(buff, getAmperage(), 0, 2, 0, 3);
1586 buff[3] = SYM_AMP;
1587 buff[4] = '\0';
1589 uint8_t current_alarm = osdConfig()->current_alarm;
1590 if ((current_alarm > 0) && ((getAmperage() / 100.0f) > current_alarm)) {
1591 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1593 break;
1595 case OSD_MAH_DRAWN: {
1596 if (osdFormatCentiNumber(buff, getMAhDrawn() * 100, 1000, 0, (osdConfig()->mAh_used_precision - 2), osdConfig()->mAh_used_precision)) {
1597 // Shown in mAh
1598 buff[osdConfig()->mAh_used_precision] = SYM_AH;
1599 } else {
1600 // Shown in Ah
1601 buff[osdConfig()->mAh_used_precision] = SYM_MAH;
1603 buff[(osdConfig()->mAh_used_precision + 1)] = '\0';
1604 osdUpdateBatteryCapacityOrVoltageTextAttributes(&elemAttr);
1605 break;
1607 case OSD_WH_DRAWN:
1608 osdFormatCentiNumber(buff, getMWhDrawn() / 10, 0, 2, 0, 3);
1609 osdUpdateBatteryCapacityOrVoltageTextAttributes(&elemAttr);
1610 buff[3] = SYM_WH;
1611 buff[4] = '\0';
1612 break;
1614 case OSD_BATTERY_REMAINING_CAPACITY:
1616 if (currentBatteryProfile->capacity.value == 0)
1617 tfp_sprintf(buff, " NA");
1618 else if (!batteryWasFullWhenPluggedIn())
1619 tfp_sprintf(buff, " NF");
1620 else if (currentBatteryProfile->capacity.unit == BAT_CAPACITY_UNIT_MAH)
1621 tfp_sprintf(buff, "%4lu", getBatteryRemainingCapacity());
1622 else // currentBatteryProfile->capacity.unit == BAT_CAPACITY_UNIT_MWH
1623 osdFormatCentiNumber(buff + 1, getBatteryRemainingCapacity() / 10, 0, 2, 0, 3);
1625 buff[4] = currentBatteryProfile->capacity.unit == BAT_CAPACITY_UNIT_MAH ? SYM_MAH : SYM_WH;
1626 buff[5] = '\0';
1628 if ((getBatteryState() != BATTERY_NOT_PRESENT) && batteryUsesCapacityThresholds() && (getBatteryRemainingCapacity() <= currentBatteryProfile->capacity.warning - currentBatteryProfile->capacity.critical))
1629 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1631 break;
1633 case OSD_BATTERY_REMAINING_PERCENT:
1634 osdFormatBatteryChargeSymbol(buff);
1635 tfp_sprintf(buff + 1, "%3d%%", calculateBatteryPercentage());
1636 osdUpdateBatteryCapacityOrVoltageTextAttributes(&elemAttr);
1637 break;
1639 case OSD_POWER_SUPPLY_IMPEDANCE:
1640 if (isPowerSupplyImpedanceValid())
1641 tfp_sprintf(buff, "%3d", getPowerSupplyImpedance());
1642 else
1643 strcpy(buff, "---");
1644 buff[3] = SYM_MILLIOHM;
1645 buff[4] = '\0';
1646 break;
1648 #ifdef USE_GPS
1649 case OSD_GPS_SATS:
1650 buff[0] = SYM_SAT_L;
1651 buff[1] = SYM_SAT_R;
1652 tfp_sprintf(buff + 2, "%2d", gpsSol.numSat);
1653 if (!STATE(GPS_FIX)) {
1654 if (getHwGPSStatus() == HW_SENSOR_UNAVAILABLE || getHwGPSStatus() == HW_SENSOR_UNHEALTHY) {
1655 strcpy(buff + 2, "X!");
1657 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1659 break;
1661 case OSD_GPS_SPEED:
1662 osdFormatVelocityStr(buff, gpsSol.groundSpeed, false, false);
1663 break;
1665 case OSD_GPS_MAX_SPEED:
1666 osdFormatVelocityStr(buff, stats.max_speed, false, true);
1667 break;
1669 case OSD_3D_SPEED:
1670 osdFormatVelocityStr(buff, osdGet3DSpeed(), true, false);
1671 break;
1673 case OSD_3D_MAX_SPEED:
1674 osdFormatVelocityStr(buff, stats.max_3D_speed, true, true);
1675 break;
1677 case OSD_GLIDESLOPE:
1679 float horizontalSpeed = gpsSol.groundSpeed;
1680 float sinkRate = -getEstimatedActualVelocity(Z);
1681 static pt1Filter_t gsFilterState;
1682 const timeMs_t currentTimeMs = millis();
1683 static timeMs_t gsUpdatedTimeMs;
1684 float glideSlope = horizontalSpeed / sinkRate;
1685 glideSlope = pt1FilterApply4(&gsFilterState, isnormal(glideSlope) ? glideSlope : 200, 0.5, MS2S(currentTimeMs - gsUpdatedTimeMs));
1686 gsUpdatedTimeMs = currentTimeMs;
1688 buff[0] = SYM_GLIDESLOPE;
1689 if (glideSlope > 0.0f && glideSlope < 100.0f) {
1690 osdFormatCentiNumber(buff + 1, glideSlope * 100.0f, 0, 2, 0, 3);
1691 } else {
1692 buff[1] = buff[2] = buff[3] = '-';
1694 buff[4] = '\0';
1695 break;
1698 case OSD_GPS_LAT:
1699 osdFormatCoordinate(buff, SYM_LAT, gpsSol.llh.lat);
1700 break;
1702 case OSD_GPS_LON:
1703 osdFormatCoordinate(buff, SYM_LON, gpsSol.llh.lon);
1704 break;
1706 case OSD_HOME_DIR:
1708 if (STATE(GPS_FIX) && STATE(GPS_FIX_HOME) && isImuHeadingValid()) {
1709 if (GPS_distanceToHome < (navConfig()->general.min_rth_distance / 100) ) {
1710 displayWriteChar(osdDisplayPort, elemPosX, elemPosY, SYM_HOME_NEAR);
1712 else
1714 int16_t panHomeDirOffset = 0;
1715 if (!(osdConfig()->pan_servo_pwm2centideg == 0)){
1716 panHomeDirOffset = osdPanServoHomeDirectionOffset();
1718 int homeDirection = GPS_directionToHome - DECIDEGREES_TO_DEGREES(osdGetHeading()) + panHomeDirOffset;
1719 osdDrawDirArrow(osdDisplayPort, osdGetDisplayPortCanvas(), OSD_DRAW_POINT_GRID(elemPosX, elemPosY), homeDirection);
1721 } else {
1722 // No home or no fix or unknown heading, blink.
1723 // If we're unarmed, show the arrow pointing up so users can see the arrow
1724 // while configuring the OSD. If we're armed, show a '-' indicating that
1725 // we don't know the direction to home.
1726 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1727 displayWriteCharWithAttr(osdDisplayPort, elemPosX, elemPosY, ARMING_FLAG(ARMED) ? '-' : SYM_ARROW_UP, elemAttr);
1729 return true;
1732 case OSD_HOME_HEADING_ERROR:
1734 buff[0] = SYM_HOME;
1735 buff[1] = SYM_HEADING;
1737 if (isImuHeadingValid() && navigationPositionEstimateIsHealthy()) {
1738 int16_t h = lrintf(CENTIDEGREES_TO_DEGREES((float)wrap_18000(DEGREES_TO_CENTIDEGREES((int32_t)GPS_directionToHome) - DECIDEGREES_TO_CENTIDEGREES((int32_t)osdGetHeading()))));
1739 tfp_sprintf(buff + 2, "%4d", h);
1740 } else {
1741 strcpy(buff + 2, "----");
1744 buff[6] = SYM_DEGREES;
1745 buff[7] = '\0';
1746 break;
1749 case OSD_HOME_DIST:
1751 buff[0] = SYM_HOME;
1752 osdFormatDistanceSymbol(&buff[1], GPS_distanceToHome * 100, 0);
1753 uint16_t dist_alarm = osdConfig()->dist_alarm;
1754 if (dist_alarm > 0 && GPS_distanceToHome > dist_alarm) {
1755 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1758 break;
1760 case OSD_TRIP_DIST:
1761 buff[0] = SYM_TOTAL;
1762 osdFormatDistanceSymbol(buff + 1, getTotalTravelDistance(), 0);
1763 break;
1765 case OSD_HEADING:
1767 buff[0] = SYM_HEADING;
1768 if (osdIsHeadingValid()) {
1769 int16_t h = DECIDEGREES_TO_DEGREES(osdGetHeading());
1770 if (h < 0) {
1771 h += 360;
1773 tfp_sprintf(&buff[1], "%3d", h);
1774 } else {
1775 buff[1] = buff[2] = buff[3] = '-';
1777 buff[4] = SYM_DEGREES;
1778 buff[5] = '\0';
1779 break;
1782 case OSD_COURSE_HOLD_ERROR:
1784 if (ARMING_FLAG(ARMED) && !FLIGHT_MODE(NAV_COURSE_HOLD_MODE)) {
1785 displayWrite(osdDisplayPort, elemPosX, elemPosY, " ");
1786 return true;
1789 buff[0] = SYM_HEADING;
1791 if ((!ARMING_FLAG(ARMED)) || (FLIGHT_MODE(NAV_COURSE_HOLD_MODE) && isAdjustingPosition())) {
1792 buff[1] = buff[2] = buff[3] = '-';
1793 } else if (FLIGHT_MODE(NAV_COURSE_HOLD_MODE)) {
1794 int16_t herr = lrintf(CENTIDEGREES_TO_DEGREES((float)navigationGetHeadingError()));
1795 if (ABS(herr) > 99)
1796 strcpy(buff + 1, ">99");
1797 else
1798 tfp_sprintf(buff + 1, "%3d", herr);
1801 buff[4] = SYM_DEGREES;
1802 buff[5] = '\0';
1803 break;
1806 case OSD_COURSE_HOLD_ADJUSTMENT:
1808 int16_t heading_adjust = lrintf(CENTIDEGREES_TO_DEGREES((float)getCruiseHeadingAdjustment()));
1810 if (ARMING_FLAG(ARMED) && ((!FLIGHT_MODE(NAV_COURSE_HOLD_MODE)) || !(isAdjustingPosition() || isAdjustingHeading() || (heading_adjust != 0)))) {
1811 displayWrite(osdDisplayPort, elemPosX, elemPosY, " ");
1812 return true;
1815 buff[0] = SYM_HEADING;
1817 if (!ARMING_FLAG(ARMED)) {
1818 buff[1] = buff[2] = buff[3] = buff[4] = '-';
1819 } else if (FLIGHT_MODE(NAV_COURSE_HOLD_MODE)) {
1820 tfp_sprintf(buff + 1, "%4d", heading_adjust);
1823 buff[5] = SYM_DEGREES;
1824 buff[6] = '\0';
1825 break;
1828 case OSD_GPS_HDOP:
1830 buff[0] = SYM_HDP_L;
1831 buff[1] = SYM_HDP_R;
1832 int32_t centiHDOP = 100 * gpsSol.hdop / HDOP_SCALE;
1833 osdFormatCentiNumber(&buff[2], centiHDOP, 0, 1, 0, 2);
1834 break;
1837 case OSD_MAP_NORTH:
1839 static uint16_t drawn = 0;
1840 static uint32_t scale = 0;
1841 osdDrawHomeMap(0, 'N', &drawn, &scale);
1842 return true;
1844 case OSD_MAP_TAKEOFF:
1846 static uint16_t drawn = 0;
1847 static uint32_t scale = 0;
1848 osdDrawHomeMap(CENTIDEGREES_TO_DEGREES(navigationGetHomeHeading()), 'T', &drawn, &scale);
1849 return true;
1851 case OSD_RADAR:
1853 static uint16_t drawn = 0;
1854 static uint32_t scale = 0;
1855 osdDrawRadar(&drawn, &scale);
1856 return true;
1858 #endif // GPS
1860 case OSD_ALTITUDE:
1862 int32_t alt = osdGetAltitude();
1863 osdFormatAltitudeSymbol(buff, alt);
1864 uint16_t alt_alarm = osdConfig()->alt_alarm;
1865 uint16_t neg_alt_alarm = osdConfig()->neg_alt_alarm;
1866 if ((alt_alarm > 0 && CENTIMETERS_TO_METERS(alt) > alt_alarm) ||
1867 (neg_alt_alarm > 0 && alt < 0 && -CENTIMETERS_TO_METERS(alt) > neg_alt_alarm)) {
1869 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1871 break;
1874 case OSD_ALTITUDE_MSL:
1876 int32_t alt = osdGetAltitudeMsl();
1877 osdFormatAltitudeSymbol(buff, alt);
1878 break;
1881 #ifdef USE_RANGEFINDER
1882 case OSD_RANGEFINDER:
1884 int32_t range = rangefinderGetLatestRawAltitude();
1885 if (range < 0) {
1886 buff[0] = '-';
1887 } else {
1888 osdFormatDistanceSymbol(buff, range, 1);
1891 break;
1892 #endif
1894 case OSD_ONTIME:
1896 osdFormatOnTime(buff);
1897 break;
1900 case OSD_FLYTIME:
1902 osdFormatFlyTime(buff, &elemAttr);
1903 break;
1906 case OSD_ONTIME_FLYTIME:
1908 if (ARMING_FLAG(ARMED)) {
1909 osdFormatFlyTime(buff, &elemAttr);
1910 } else {
1911 osdFormatOnTime(buff);
1913 break;
1916 case OSD_REMAINING_FLIGHT_TIME_BEFORE_RTH:
1918 /*static int32_t updatedTimeSeconds = 0;*/
1919 static int32_t timeSeconds = -1;
1920 #if defined(USE_ADC) && defined(USE_GPS)
1921 static timeUs_t updatedTimestamp = 0;
1922 timeUs_t currentTimeUs = micros();
1923 if (cmpTimeUs(currentTimeUs, updatedTimestamp) >= MS2US(1000)) {
1924 #ifdef USE_WIND_ESTIMATOR
1925 timeSeconds = calculateRemainingFlightTimeBeforeRTH(osdConfig()->estimations_wind_compensation);
1926 #else
1927 timeSeconds = calculateRemainingFlightTimeBeforeRTH(false);
1928 #endif
1929 updatedTimestamp = currentTimeUs;
1931 #endif
1932 if ((!ARMING_FLAG(ARMED)) || (timeSeconds == -1)) {
1933 buff[0] = SYM_FLY_M;
1934 strcpy(buff + 1, "--:--");
1935 #if defined(USE_ADC) && defined(USE_GPS)
1936 updatedTimestamp = 0;
1937 #endif
1938 } else if (timeSeconds == -2) {
1939 // Wind is too strong to come back with cruise throttle
1940 buff[0] = SYM_FLY_M;
1941 buff[1] = buff[2] = buff[4] = buff[5] = SYM_WIND_HORIZONTAL;
1942 buff[3] = ':';
1943 buff[6] = '\0';
1944 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1945 } else {
1946 osdFormatTime(buff, timeSeconds, SYM_FLY_M, SYM_FLY_H);
1947 if (timeSeconds == 0)
1948 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1951 break;
1953 case OSD_REMAINING_DISTANCE_BEFORE_RTH:;
1954 static int32_t distanceMeters = -1;
1955 #if defined(USE_ADC) && defined(USE_GPS)
1956 static timeUs_t updatedTimestamp = 0;
1957 timeUs_t currentTimeUs = micros();
1958 if (cmpTimeUs(currentTimeUs, updatedTimestamp) >= MS2US(1000)) {
1959 #ifdef USE_WIND_ESTIMATOR
1960 distanceMeters = calculateRemainingDistanceBeforeRTH(osdConfig()->estimations_wind_compensation);
1961 #else
1962 distanceMeters = calculateRemainingDistanceBeforeRTH(false);
1963 #endif
1964 updatedTimestamp = currentTimeUs;
1966 #endif
1967 buff[0] = SYM_TRIP_DIST;
1968 if ((!ARMING_FLAG(ARMED)) || (distanceMeters == -1)) {
1969 buff[4] = SYM_BLANK;
1970 buff[5] = '\0';
1971 strcpy(buff + 1, "---");
1972 } else if (distanceMeters == -2) {
1973 // Wind is too strong to come back with cruise throttle
1974 buff[1] = buff[2] = buff[3] = SYM_WIND_HORIZONTAL;
1975 switch ((osd_unit_e)osdConfig()->units){
1976 case OSD_UNIT_UK:
1977 FALLTHROUGH;
1978 case OSD_UNIT_IMPERIAL:
1979 buff[4] = SYM_DIST_MI;
1980 break;
1981 case OSD_UNIT_METRIC_MPH:
1982 FALLTHROUGH;
1983 case OSD_UNIT_METRIC:
1984 buff[4] = SYM_DIST_KM;
1985 break;
1986 case OSD_UNIT_GA:
1987 buff[4] = SYM_DIST_NM;
1988 break;
1990 buff[5] = '\0';
1991 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1992 } else {
1993 osdFormatDistanceSymbol(buff + 1, distanceMeters * 100, 0);
1994 if (distanceMeters == 0)
1995 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1997 break;
1999 case OSD_FLYMODE:
2001 char *p = "ACRO";
2003 if (FLIGHT_MODE(FAILSAFE_MODE))
2004 p = "!FS!";
2005 else if (FLIGHT_MODE(MANUAL_MODE))
2006 p = "MANU";
2007 else if (FLIGHT_MODE(TURTLE_MODE))
2008 p = "TURT";
2009 else if (FLIGHT_MODE(NAV_RTH_MODE))
2010 p = isWaypointMissionRTHActive() ? "WRTH" : "RTH ";
2011 else if (FLIGHT_MODE(NAV_POSHOLD_MODE))
2012 p = "HOLD";
2013 else if (FLIGHT_MODE(NAV_COURSE_HOLD_MODE) && FLIGHT_MODE(NAV_ALTHOLD_MODE))
2014 p = "CRUZ";
2015 else if (FLIGHT_MODE(NAV_COURSE_HOLD_MODE))
2016 p = "CRSH";
2017 else if (FLIGHT_MODE(NAV_WP_MODE))
2018 p = " WP ";
2019 else if (FLIGHT_MODE(NAV_ALTHOLD_MODE) && navigationRequiresAngleMode()) {
2020 // If navigationRequiresAngleMode() returns false when ALTHOLD is active,
2021 // it means it can be combined with ANGLE, HORIZON, ACRO, etc...
2022 // and its display is handled by OSD_MESSAGES rather than OSD_FLYMODE.
2023 p = " AH ";
2025 else if (FLIGHT_MODE(ANGLE_MODE))
2026 p = "ANGL";
2027 else if (FLIGHT_MODE(HORIZON_MODE))
2028 p = "HOR ";
2030 displayWrite(osdDisplayPort, elemPosX, elemPosY, p);
2031 return true;
2034 case OSD_CRAFT_NAME:
2035 osdFormatCraftName(buff);
2036 break;
2038 case OSD_THROTTLE_POS:
2040 osdFormatThrottlePosition(buff, false, &elemAttr);
2041 break;
2044 case OSD_VTX_CHANNEL:
2046 vtxDeviceOsdInfo_t osdInfo;
2047 vtxCommonGetOsdInfo(vtxCommonDevice(), &osdInfo);
2049 tfp_sprintf(buff, "CH:%c%s:", osdInfo.bandLetter, osdInfo.channelName);
2050 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
2052 tfp_sprintf(buff, "%c", osdInfo.powerIndexLetter);
2053 if (isAdjustmentFunctionSelected(ADJUSTMENT_VTX_POWER_LEVEL)) TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2054 displayWriteWithAttr(osdDisplayPort, elemPosX + 6, elemPosY, buff, elemAttr);
2055 return true;
2057 break;
2059 case OSD_VTX_POWER:
2061 vtxDeviceOsdInfo_t osdInfo;
2062 vtxCommonGetOsdInfo(vtxCommonDevice(), &osdInfo);
2064 tfp_sprintf(buff, "%c", SYM_VTX_POWER);
2065 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
2067 tfp_sprintf(buff, "%c", osdInfo.powerIndexLetter);
2068 if (isAdjustmentFunctionSelected(ADJUSTMENT_VTX_POWER_LEVEL)) TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2069 displayWriteWithAttr(osdDisplayPort, elemPosX+1, elemPosY, buff, elemAttr);
2070 return true;
2073 #if defined(USE_SERIALRX_CRSF)
2074 case OSD_CRSF_RSSI_DBM:
2076 int16_t rssi = rxLinkStatistics.uplinkRSSI;
2077 buff[0] = (rxLinkStatistics.activeAntenna == 0) ? SYM_RSSI : SYM_2RSS; // Separate symbols for each antenna
2078 if (rssi <= -100) {
2079 tfp_sprintf(buff + 1, "%4d%c", rssi, SYM_DBM);
2080 } else {
2081 tfp_sprintf(buff + 1, "%3d%c%c", rssi, SYM_DBM, ' ');
2083 if (!failsafeIsReceivingRxData()){
2084 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2085 } else if (osdConfig()->rssi_dbm_alarm && rssi < osdConfig()->rssi_dbm_alarm) {
2086 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2088 break;
2090 case OSD_CRSF_LQ:
2092 buff[0] = SYM_LQ;
2093 int16_t statsLQ = rxLinkStatistics.uplinkLQ;
2094 int16_t scaledLQ = scaleRange(constrain(statsLQ, 0, 100), 0, 100, 170, 300);
2095 switch (osdConfig()->crsf_lq_format) {
2096 case OSD_CRSF_LQ_TYPE1:
2097 if (!failsafeIsReceivingRxData()) {
2098 tfp_sprintf(buff+1, "%3d", 0);
2099 } else {
2100 tfp_sprintf(buff+1, "%3d", rxLinkStatistics.uplinkLQ);
2102 break;
2103 case OSD_CRSF_LQ_TYPE2:
2104 if (!failsafeIsReceivingRxData()) {
2105 tfp_sprintf(buff+1, "%s:%3d", " ", 0);
2106 } else {
2107 tfp_sprintf(buff+1, "%d:%3d", rxLinkStatistics.rfMode, rxLinkStatistics.uplinkLQ);
2109 break;
2110 case OSD_CRSF_LQ_TYPE3:
2111 if (!failsafeIsReceivingRxData()) {
2112 tfp_sprintf(buff+1, "%3d", 0);
2113 } else {
2114 tfp_sprintf(buff+1, "%3d", rxLinkStatistics.rfMode >= 2 ? scaledLQ : rxLinkStatistics.uplinkLQ);
2116 break;
2118 if (!failsafeIsReceivingRxData()) {
2119 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2120 } else if (rxLinkStatistics.uplinkLQ < osdConfig()->link_quality_alarm) {
2121 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2123 break;
2126 case OSD_CRSF_SNR_DB:
2128 static pt1Filter_t snrFilterState;
2129 static timeMs_t snrUpdated = 0;
2130 int8_t snrFiltered = pt1FilterApply4(&snrFilterState, rxLinkStatistics.uplinkSNR, 0.5f, MS2S(millis() - snrUpdated));
2131 snrUpdated = millis();
2133 const char* showsnr = "-20";
2134 const char* hidesnr = " ";
2135 if (snrFiltered > osdConfig()->snr_alarm) {
2136 if (cmsInMenu) {
2137 buff[0] = SYM_SNR;
2138 tfp_sprintf(buff + 1, "%s%c", showsnr, SYM_DB);
2139 } else {
2140 buff[0] = SYM_BLANK;
2141 tfp_sprintf(buff + 1, "%s%c", hidesnr, SYM_BLANK);
2143 } else if (snrFiltered <= osdConfig()->snr_alarm) {
2144 buff[0] = SYM_SNR;
2145 if (snrFiltered <= -10) {
2146 tfp_sprintf(buff + 1, "%3d%c", snrFiltered, SYM_DB);
2147 } else {
2148 tfp_sprintf(buff + 1, "%2d%c%c", snrFiltered, SYM_DB, ' ');
2151 break;
2154 case OSD_CRSF_TX_POWER:
2156 if (!failsafeIsReceivingRxData())
2157 tfp_sprintf(buff, "%s%c", " ", SYM_BLANK);
2158 else
2159 tfp_sprintf(buff, "%4d%c", rxLinkStatistics.uplinkTXPower, SYM_MW);
2160 break;
2162 #endif
2164 case OSD_CROSSHAIRS: // Hud is a sub-element of the crosshair
2166 osdCrosshairPosition(&elemPosX, &elemPosY);
2167 osdHudDrawCrosshair(osdGetDisplayPortCanvas(), elemPosX, elemPosY);
2169 if (osdConfig()->hud_homing && STATE(GPS_FIX) && STATE(GPS_FIX_HOME) && isImuHeadingValid()) {
2170 osdHudDrawHoming(elemPosX, elemPosY);
2173 if (STATE(GPS_FIX) && isImuHeadingValid()) {
2175 if (osdConfig()->hud_homepoint || osdConfig()->hud_radar_disp > 0 || osdConfig()->hud_wp_disp > 0) {
2176 osdHudClear();
2179 // -------- POI : Home point
2181 if (osdConfig()->hud_homepoint) { // Display the home point (H)
2182 osdHudDrawPoi(GPS_distanceToHome, GPS_directionToHome, -osdGetAltitude() / 100, 0, SYM_HOME, 0 , 0);
2185 // -------- POI : Nearby aircrafts from ESP32 radar
2187 if (osdConfig()->hud_radar_disp > 0) { // Display the POI from the radar
2188 for (uint8_t i = 0; i < osdConfig()->hud_radar_disp; i++) {
2189 if (radar_pois[i].gps.lat != 0 && radar_pois[i].gps.lon != 0 && radar_pois[i].state < 2) { // state 2 means POI has been lost and must be skipped
2190 fpVector3_t poi;
2191 geoConvertGeodeticToLocal(&poi, &posControl.gpsOrigin, &radar_pois[i].gps, GEO_ALT_RELATIVE);
2192 radar_pois[i].distance = calculateDistanceToDestination(&poi) / 100; // In meters
2194 if (radar_pois[i].distance >= osdConfig()->hud_radar_range_min && radar_pois[i].distance <= osdConfig()->hud_radar_range_max) {
2195 radar_pois[i].direction = calculateBearingToDestination(&poi) / 100; // In °
2196 radar_pois[i].altitude = (radar_pois[i].gps.alt - osdGetAltitudeMsl()) / 100;
2197 osdHudDrawPoi(radar_pois[i].distance, osdGetHeadingAngle(radar_pois[i].direction), radar_pois[i].altitude, 1, 65 + i, radar_pois[i].heading, radar_pois[i].lq);
2203 // -------- POI : Next waypoints from navigation
2205 if (osdConfig()->hud_wp_disp > 0 && posControl.waypointListValid && posControl.waypointCount > 0) { // Display the next waypoints
2206 gpsLocation_t wp2;
2207 int j;
2209 for (int i = osdConfig()->hud_wp_disp - 1; i >= 0 ; i--) { // Display in reverse order so the next WP is always written on top
2210 j = posControl.activeWaypointIndex + i;
2211 if (j > posControl.startWpIndex + posControl.waypointCount - 1) { // limit to max WP index for mission
2212 break;
2214 if (posControl.waypointList[j].lat != 0 && posControl.waypointList[j].lon != 0) {
2215 wp2.lat = posControl.waypointList[j].lat;
2216 wp2.lon = posControl.waypointList[j].lon;
2217 wp2.alt = posControl.waypointList[j].alt;
2218 fpVector3_t poi;
2219 geoConvertGeodeticToLocal(&poi, &posControl.gpsOrigin, &wp2, waypointMissionAltConvMode(posControl.waypointList[j].p3));
2220 int32_t altConvModeAltitude = waypointMissionAltConvMode(posControl.waypointList[j].p3) == GEO_ALT_ABSOLUTE ? osdGetAltitudeMsl() : osdGetAltitude();
2221 j = getGeoWaypointNumber(j);
2222 while (j > 9) j -= 10; // Only the last digit displayed if WP>=10, no room for more (48 = ascii 0)
2223 osdHudDrawPoi(calculateDistanceToDestination(&poi) / 100, osdGetHeadingAngle(calculateBearingToDestination(&poi) / 100), (posControl.waypointList[j].alt - altConvModeAltitude)/ 100, 2, SYM_WAYPOINT, 48 + j, i);
2229 return true;
2230 break;
2232 case OSD_ATTITUDE_ROLL:
2233 buff[0] = SYM_ROLL_LEVEL;
2234 if (ABS(attitude.values.roll) >= 1)
2235 buff[0] += (attitude.values.roll < 0 ? -1 : 1);
2236 osdFormatCentiNumber(buff + 1, DECIDEGREES_TO_CENTIDEGREES(ABS(attitude.values.roll)), 0, 1, 0, 3);
2237 break;
2239 case OSD_ATTITUDE_PITCH:
2240 if (ABS(attitude.values.pitch) < 1)
2241 buff[0] = 'P';
2242 else if (attitude.values.pitch > 0)
2243 buff[0] = SYM_PITCH_DOWN;
2244 else if (attitude.values.pitch < 0)
2245 buff[0] = SYM_PITCH_UP;
2246 osdFormatCentiNumber(buff + 1, DECIDEGREES_TO_CENTIDEGREES(ABS(attitude.values.pitch)), 0, 1, 0, 3);
2247 break;
2249 case OSD_ARTIFICIAL_HORIZON:
2251 float rollAngle = DECIDEGREES_TO_RADIANS(attitude.values.roll);
2252 float pitchAngle = DECIDEGREES_TO_RADIANS(attitude.values.pitch);
2254 pitchAngle -= osdConfig()->ahi_camera_uptilt_comp ? DEGREES_TO_RADIANS(osdConfig()->camera_uptilt) : 0;
2255 pitchAngle += DEGREES_TO_RADIANS(getFixedWingLevelTrim());
2256 if (osdConfig()->ahi_reverse_roll) {
2257 rollAngle = -rollAngle;
2259 osdDrawArtificialHorizon(osdDisplayPort, osdGetDisplayPortCanvas(),
2260 OSD_DRAW_POINT_GRID(elemPosX, elemPosY), rollAngle, pitchAngle);
2261 osdDrawSingleElement(OSD_HORIZON_SIDEBARS);
2262 osdDrawSingleElement(OSD_CROSSHAIRS);
2264 return true;
2267 case OSD_HORIZON_SIDEBARS:
2269 osdDrawSidebars(osdDisplayPort, osdGetDisplayPortCanvas());
2270 return true;
2273 #if defined(USE_BARO) || defined(USE_GPS)
2274 case OSD_VARIO:
2276 float zvel = getEstimatedActualVelocity(Z);
2277 osdDrawVario(osdDisplayPort, osdGetDisplayPortCanvas(), OSD_DRAW_POINT_GRID(elemPosX, elemPosY), zvel);
2278 return true;
2281 case OSD_VARIO_NUM:
2283 int16_t value = getEstimatedActualVelocity(Z);
2284 char sym;
2285 switch ((osd_unit_e)osdConfig()->units) {
2286 case OSD_UNIT_UK:
2287 FALLTHROUGH;
2288 case OSD_UNIT_IMPERIAL:
2289 // Convert to centifeet/s
2290 value = CENTIMETERS_TO_CENTIFEET(value);
2291 sym = SYM_FTS;
2292 break;
2293 case OSD_UNIT_GA:
2294 // Convert to centi-100feet/min
2295 value = CENTIMETERS_TO_FEET(value * 60);
2296 sym = SYM_100FTM;
2297 break;
2298 default:
2299 case OSD_UNIT_METRIC_MPH:
2300 FALLTHROUGH;
2301 case OSD_UNIT_METRIC:
2302 // Already in cm/s
2303 sym = SYM_MS;
2304 break;
2307 osdFormatCentiNumber(buff, value, 0, 1, 0, 3);
2308 buff[3] = sym;
2309 buff[4] = '\0';
2310 break;
2312 case OSD_CLIMB_EFFICIENCY:
2314 // amperage is in centi amps (10mA), vertical speed is in cms/s. We want
2315 // Ah/dist only to show when vertical speed > 1m/s.
2316 static pt1Filter_t veFilterState;
2317 static timeUs_t vEfficiencyUpdated = 0;
2318 int32_t value = 0;
2319 timeUs_t currentTimeUs = micros();
2320 timeDelta_t vEfficiencyTimeDelta = cmpTimeUs(currentTimeUs, vEfficiencyUpdated);
2321 if (getEstimatedActualVelocity(Z) > 0) {
2322 if (vEfficiencyTimeDelta >= EFFICIENCY_UPDATE_INTERVAL) {
2323 // Centiamps (kept for osdFormatCentiNumber) / m/s - Will appear as A / m/s in OSD
2324 value = pt1FilterApply4(&veFilterState, (float)getAmperage() / (getEstimatedActualVelocity(Z) / 100.0f), 1, US2S(vEfficiencyTimeDelta));
2326 vEfficiencyUpdated = currentTimeUs;
2327 } else {
2328 value = veFilterState.state;
2331 bool efficiencyValid = (value > 0) && (getEstimatedActualVelocity(Z) > 100);
2332 switch (osdConfig()->units) {
2333 case OSD_UNIT_UK:
2334 FALLTHROUGH;
2335 case OSD_UNIT_GA:
2336 FALLTHROUGH;
2337 case OSD_UNIT_IMPERIAL:
2338 // mAh/foot
2339 if (efficiencyValid) {
2340 osdFormatCentiNumber(buff, (value * METERS_PER_FOOT), 1, 2, 2, 3);
2341 tfp_sprintf(buff, "%s%c%c", buff, SYM_AH_V_FT_0, SYM_AH_V_FT_1);
2342 } else {
2343 buff[0] = buff[1] = buff[2] = '-';
2344 buff[3] = SYM_AH_V_FT_0;
2345 buff[4] = SYM_AH_V_FT_1;
2346 buff[5] = '\0';
2348 break;
2349 case OSD_UNIT_METRIC_MPH:
2350 FALLTHROUGH;
2351 case OSD_UNIT_METRIC:
2352 // mAh/metre
2353 if (efficiencyValid) {
2354 osdFormatCentiNumber(buff, value, 1, 2, 2, 3);
2355 tfp_sprintf(buff, "%s%c%c", buff, SYM_AH_V_M_0, SYM_AH_V_M_1);
2356 } else {
2357 buff[0] = buff[1] = buff[2] = '-';
2358 buff[3] = SYM_AH_V_M_0;
2359 buff[4] = SYM_AH_V_M_1;
2360 buff[5] = '\0';
2362 break;
2364 break;
2366 case OSD_GLIDE_TIME_REMAINING:
2368 uint16_t glideTime = osdGetRemainingGlideTime();
2369 buff[0] = SYM_GLIDE_MINS;
2370 if (glideTime > 0) {
2371 // Maximum value we can show in minutes is 99 minutes and 59 seconds. It is extremely unlikely that glide
2372 // time will be longer than 99 minutes. If it is, it will show 99:^^
2373 if (glideTime > (99 * 60) + 59) {
2374 tfp_sprintf(buff + 1, "%02d:", (int)(glideTime / 60));
2375 buff[4] = SYM_DIRECTION;
2376 buff[5] = SYM_DIRECTION;
2377 } else {
2378 tfp_sprintf(buff + 1, "%02d:%02d", (int)(glideTime / 60), (int)(glideTime % 60));
2380 } else {
2381 tfp_sprintf(buff + 1, "%s", "--:--");
2383 buff[6] = '\0';
2384 break;
2386 case OSD_GLIDE_RANGE:
2388 uint16_t glideSeconds = osdGetRemainingGlideTime();
2389 buff[0] = SYM_GLIDE_DIST;
2390 if (glideSeconds > 0) {
2391 uint32_t glideRangeCM = glideSeconds * gpsSol.groundSpeed;
2392 osdFormatDistanceSymbol(buff + 1, glideRangeCM, 0);
2393 } else {
2394 tfp_sprintf(buff + 1, "%s%c", "---", SYM_BLANK);
2395 buff[5] = '\0';
2397 break;
2399 #endif
2401 case OSD_SWITCH_INDICATOR_0:
2402 osdDisplaySwitchIndicator(osdConfig()->osd_switch_indicator0_name, rxGetChannelValue(osdConfig()->osd_switch_indicator0_channel - 1), buff);
2403 break;
2405 case OSD_SWITCH_INDICATOR_1:
2406 osdDisplaySwitchIndicator(osdConfig()->osd_switch_indicator1_name, rxGetChannelValue(osdConfig()->osd_switch_indicator1_channel - 1), buff);
2407 break;
2409 case OSD_SWITCH_INDICATOR_2:
2410 osdDisplaySwitchIndicator(osdConfig()->osd_switch_indicator2_name, rxGetChannelValue(osdConfig()->osd_switch_indicator2_channel - 1), buff);
2411 break;
2413 case OSD_SWITCH_INDICATOR_3:
2414 osdDisplaySwitchIndicator(osdConfig()->osd_switch_indicator3_name, rxGetChannelValue(osdConfig()->osd_switch_indicator3_channel - 1), buff);
2415 break;
2417 case OSD_ACTIVE_PROFILE:
2418 tfp_sprintf(buff, "%c%u", SYM_PROFILE, (getConfigProfile() + 1));
2419 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
2420 break;
2422 case OSD_ROLL_PIDS:
2423 osdDisplayFlightPIDValues(elemPosX, elemPosY, "ROL", PID_ROLL, ADJUSTMENT_ROLL_P, ADJUSTMENT_ROLL_I, ADJUSTMENT_ROLL_D, ADJUSTMENT_ROLL_FF);
2424 return true;
2426 case OSD_PITCH_PIDS:
2427 osdDisplayFlightPIDValues(elemPosX, elemPosY, "PIT", PID_PITCH, ADJUSTMENT_PITCH_P, ADJUSTMENT_PITCH_I, ADJUSTMENT_PITCH_D, ADJUSTMENT_PITCH_FF);
2428 return true;
2430 case OSD_YAW_PIDS:
2431 osdDisplayFlightPIDValues(elemPosX, elemPosY, "YAW", PID_YAW, ADJUSTMENT_YAW_P, ADJUSTMENT_YAW_I, ADJUSTMENT_YAW_D, ADJUSTMENT_YAW_FF);
2432 return true;
2434 case OSD_LEVEL_PIDS:
2435 osdDisplayNavPIDValues(elemPosX, elemPosY, "LEV", PID_LEVEL, ADJUSTMENT_LEVEL_P, ADJUSTMENT_LEVEL_I, ADJUSTMENT_LEVEL_D);
2436 return true;
2438 case OSD_POS_XY_PIDS:
2439 osdDisplayNavPIDValues(elemPosX, elemPosY, "PXY", PID_POS_XY, ADJUSTMENT_POS_XY_P, ADJUSTMENT_POS_XY_I, ADJUSTMENT_POS_XY_D);
2440 return true;
2442 case OSD_POS_Z_PIDS:
2443 osdDisplayNavPIDValues(elemPosX, elemPosY, "PZ", PID_POS_Z, ADJUSTMENT_POS_Z_P, ADJUSTMENT_POS_Z_I, ADJUSTMENT_POS_Z_D);
2444 return true;
2446 case OSD_VEL_XY_PIDS:
2447 osdDisplayNavPIDValues(elemPosX, elemPosY, "VXY", PID_VEL_XY, ADJUSTMENT_VEL_XY_P, ADJUSTMENT_VEL_XY_I, ADJUSTMENT_VEL_XY_D);
2448 return true;
2450 case OSD_VEL_Z_PIDS:
2451 osdDisplayNavPIDValues(elemPosX, elemPosY, "VZ", PID_VEL_Z, ADJUSTMENT_VEL_Z_P, ADJUSTMENT_VEL_Z_I, ADJUSTMENT_VEL_Z_D);
2452 return true;
2454 case OSD_HEADING_P:
2455 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "HP", 0, pidBank()->pid[PID_HEADING].P, 3, 0, ADJUSTMENT_HEADING_P);
2456 return true;
2458 case OSD_BOARD_ALIGN_ROLL:
2459 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "AR", 0, DECIDEGREES_TO_DEGREES((float)boardAlignment()->rollDeciDegrees), 4, 1, ADJUSTMENT_ROLL_BOARD_ALIGNMENT);
2460 return true;
2462 case OSD_BOARD_ALIGN_PITCH:
2463 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "AP", 0, DECIDEGREES_TO_DEGREES((float)boardAlignment()->pitchDeciDegrees), 4, 1, ADJUSTMENT_PITCH_BOARD_ALIGNMENT);
2464 return true;
2466 case OSD_RC_EXPO:
2467 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "EXP", 0, currentControlRateProfile->stabilized.rcExpo8, 3, 0, ADJUSTMENT_RC_EXPO);
2468 return true;
2470 case OSD_RC_YAW_EXPO:
2471 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "YEX", 0, currentControlRateProfile->stabilized.rcYawExpo8, 3, 0, ADJUSTMENT_RC_YAW_EXPO);
2472 return true;
2474 case OSD_THROTTLE_EXPO:
2475 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "TEX", 0, currentControlRateProfile->throttle.rcExpo8, 3, 0, ADJUSTMENT_THROTTLE_EXPO);
2476 return true;
2478 case OSD_PITCH_RATE:
2479 displayWrite(osdDisplayPort, elemPosX, elemPosY, "SPR");
2481 elemAttr = TEXT_ATTRIBUTES_NONE;
2482 tfp_sprintf(buff, "%3d", currentControlRateProfile->stabilized.rates[FD_PITCH]);
2483 if (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_RATE) || isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_RATE))
2484 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2485 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
2486 return true;
2488 case OSD_ROLL_RATE:
2489 displayWrite(osdDisplayPort, elemPosX, elemPosY, "SRR");
2491 elemAttr = TEXT_ATTRIBUTES_NONE;
2492 tfp_sprintf(buff, "%3d", currentControlRateProfile->stabilized.rates[FD_ROLL]);
2493 if (isAdjustmentFunctionSelected(ADJUSTMENT_ROLL_RATE) || isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_RATE))
2494 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2495 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
2496 return true;
2498 case OSD_YAW_RATE:
2499 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "SYR", 0, currentControlRateProfile->stabilized.rates[FD_YAW], 3, 0, ADJUSTMENT_YAW_RATE);
2500 return true;
2502 case OSD_MANUAL_RC_EXPO:
2503 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "MEX", 0, currentControlRateProfile->manual.rcExpo8, 3, 0, ADJUSTMENT_MANUAL_RC_EXPO);
2504 return true;
2506 case OSD_MANUAL_RC_YAW_EXPO:
2507 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "MYX", 0, currentControlRateProfile->manual.rcYawExpo8, 3, 0, ADJUSTMENT_MANUAL_RC_YAW_EXPO);
2508 return true;
2510 case OSD_MANUAL_PITCH_RATE:
2511 displayWrite(osdDisplayPort, elemPosX, elemPosY, "MPR");
2513 elemAttr = TEXT_ATTRIBUTES_NONE;
2514 tfp_sprintf(buff, "%3d", currentControlRateProfile->manual.rates[FD_PITCH]);
2515 if (isAdjustmentFunctionSelected(ADJUSTMENT_MANUAL_PITCH_RATE) || isAdjustmentFunctionSelected(ADJUSTMENT_MANUAL_PITCH_ROLL_RATE))
2516 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2517 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
2518 return true;
2520 case OSD_MANUAL_ROLL_RATE:
2521 displayWrite(osdDisplayPort, elemPosX, elemPosY, "MRR");
2523 elemAttr = TEXT_ATTRIBUTES_NONE;
2524 tfp_sprintf(buff, "%3d", currentControlRateProfile->manual.rates[FD_ROLL]);
2525 if (isAdjustmentFunctionSelected(ADJUSTMENT_MANUAL_ROLL_RATE) || isAdjustmentFunctionSelected(ADJUSTMENT_MANUAL_PITCH_ROLL_RATE))
2526 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2527 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
2528 return true;
2530 case OSD_MANUAL_YAW_RATE:
2531 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "MYR", 0, currentControlRateProfile->stabilized.rates[FD_YAW], 3, 0, ADJUSTMENT_YAW_RATE);
2532 return true;
2534 case OSD_NAV_FW_CRUISE_THR:
2535 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "CRZ", 0, currentBatteryProfile->nav.fw.cruise_throttle, 4, 0, ADJUSTMENT_NAV_FW_CRUISE_THR);
2536 return true;
2538 case OSD_NAV_FW_PITCH2THR:
2539 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "P2T", 0, currentBatteryProfile->nav.fw.pitch_to_throttle, 3, 0, ADJUSTMENT_NAV_FW_PITCH2THR);
2540 return true;
2542 case OSD_FW_MIN_THROTTLE_DOWN_PITCH_ANGLE:
2543 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "0TP", 0, (float)currentBatteryProfile->fwMinThrottleDownPitchAngle / 10, 3, 1, ADJUSTMENT_FW_MIN_THROTTLE_DOWN_PITCH_ANGLE);
2544 return true;
2546 case OSD_FW_ALT_PID_OUTPUTS:
2548 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers();
2549 osdFormatPidControllerOutput(buff, "PZO", &nav_pids->fw_alt, 10, true); // display requested pitch degrees
2550 break;
2553 case OSD_FW_POS_PID_OUTPUTS:
2555 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers(); // display requested roll degrees
2556 osdFormatPidControllerOutput(buff, "PXYO", &nav_pids->fw_nav, 1, true);
2557 break;
2560 case OSD_MC_VEL_Z_PID_OUTPUTS:
2562 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers();
2563 osdFormatPidControllerOutput(buff, "VZO", &nav_pids->vel[Z], 100, false); // display throttle adjustment µs
2564 break;
2567 case OSD_MC_VEL_X_PID_OUTPUTS:
2569 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers();
2570 osdFormatPidControllerOutput(buff, "VXO", &nav_pids->vel[X], 100, false); // display requested acceleration cm/s^2
2571 break;
2574 case OSD_MC_VEL_Y_PID_OUTPUTS:
2576 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers();
2577 osdFormatPidControllerOutput(buff, "VYO", &nav_pids->vel[Y], 100, false); // display requested acceleration cm/s^2
2578 break;
2581 case OSD_MC_POS_XYZ_P_OUTPUTS:
2583 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers();
2584 strcpy(buff, "POSO ");
2585 // display requested velocity cm/s
2586 tfp_sprintf(buff + 5, "%4d", (int)lrintf(nav_pids->pos[X].output_constrained * 100));
2587 buff[9] = ' ';
2588 tfp_sprintf(buff + 10, "%4d", (int)lrintf(nav_pids->pos[Y].output_constrained * 100));
2589 buff[14] = ' ';
2590 tfp_sprintf(buff + 15, "%4d", (int)lrintf(nav_pids->pos[Z].output_constrained * 100));
2591 buff[19] = '\0';
2592 break;
2595 case OSD_POWER:
2597 bool kiloWatt = osdFormatCentiNumber(buff, getPower(), 1000, 2, 2, 3);
2598 buff[3] = kiloWatt ? SYM_KILOWATT : SYM_WATT;
2599 buff[4] = '\0';
2601 uint8_t current_alarm = osdConfig()->current_alarm;
2602 if ((current_alarm > 0) && ((getAmperage() / 100.0f) > current_alarm)) {
2603 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2605 break;
2608 case OSD_AIR_SPEED:
2610 #ifdef USE_PITOT
2611 const float airspeed_estimate = getAirspeedEstimate();
2612 buff[0] = SYM_AIR;
2613 osdFormatVelocityStr(buff + 1, airspeed_estimate, false, false);
2615 if ((osdConfig()->airspeed_alarm_min != 0 && airspeed_estimate < osdConfig()->airspeed_alarm_min) ||
2616 (osdConfig()->airspeed_alarm_max != 0 && airspeed_estimate > osdConfig()->airspeed_alarm_max)) {
2617 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2619 #else
2620 return false;
2621 #endif
2622 break;
2625 case OSD_AIR_MAX_SPEED:
2627 #ifdef USE_PITOT
2628 buff[0] = SYM_MAX;
2629 buff[1] = SYM_AIR;
2630 osdFormatVelocityStr(buff + 2, stats.max_air_speed, false, false);
2631 #else
2632 return false;
2633 #endif
2634 break;
2637 case OSD_RTC_TIME:
2639 // RTC not configured will show 00:00
2640 dateTime_t dateTime;
2641 rtcGetDateTimeLocal(&dateTime);
2642 buff[0] = SYM_CLOCK;
2643 tfp_sprintf(buff + 1, "%02u:%02u:%02u", dateTime.hours, dateTime.minutes, dateTime.seconds);
2644 break;
2647 case OSD_MESSAGES:
2649 elemAttr = osdGetSystemMessage(buff, OSD_MESSAGE_LENGTH, true);
2650 break;
2653 case OSD_VERSION:
2655 tfp_sprintf(buff, "INAV %s", FC_VERSION_STRING);
2656 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
2657 break;
2660 case OSD_MAIN_BATT_CELL_VOLTAGE:
2662 osdDisplayBatteryVoltage(elemPosX, elemPosY, getBatteryRawAverageCellVoltage(), 3, 2);
2663 return true;
2666 case OSD_MAIN_BATT_SAG_COMPENSATED_CELL_VOLTAGE:
2668 osdDisplayBatteryVoltage(elemPosX, elemPosY, getBatterySagCompensatedAverageCellVoltage(), 3, 2);
2669 return true;
2672 case OSD_THROTTLE_POS_AUTO_THR:
2674 osdFormatThrottlePosition(buff, true, &elemAttr);
2675 break;
2678 case OSD_HEADING_GRAPH:
2680 if (osdIsHeadingValid()) {
2681 osdDrawHeadingGraph(osdDisplayPort, osdGetDisplayPortCanvas(), OSD_DRAW_POINT_GRID(elemPosX, elemPosY), osdGetHeading());
2682 return true;
2683 } else {
2684 buff[0] = buff[2] = buff[4] = buff[6] = buff[8] = SYM_HEADING_LINE;
2685 buff[1] = buff[3] = buff[5] = buff[7] = SYM_HEADING_DIVIDED_LINE;
2686 buff[OSD_HEADING_GRAPH_WIDTH] = '\0';
2688 break;
2691 case OSD_EFFICIENCY_MAH_PER_KM:
2693 // amperage is in centi amps, speed is in cms/s. We want
2694 // mah/km. Only show when ground speed > 1m/s.
2695 static pt1Filter_t eFilterState;
2696 static timeUs_t efficiencyUpdated = 0;
2697 int32_t value = 0;
2698 bool moreThanAh = false;
2699 timeUs_t currentTimeUs = micros();
2700 timeDelta_t efficiencyTimeDelta = cmpTimeUs(currentTimeUs, efficiencyUpdated);
2701 if (STATE(GPS_FIX) && gpsSol.groundSpeed > 0) {
2702 if (efficiencyTimeDelta >= EFFICIENCY_UPDATE_INTERVAL) {
2703 value = pt1FilterApply4(&eFilterState, ((float)getAmperage() / gpsSol.groundSpeed) / 0.0036f,
2704 1, US2S(efficiencyTimeDelta));
2706 efficiencyUpdated = currentTimeUs;
2707 } else {
2708 value = eFilterState.state;
2711 bool efficiencyValid = (value > 0) && (gpsSol.groundSpeed > 100);
2712 switch (osdConfig()->units) {
2713 case OSD_UNIT_UK:
2714 FALLTHROUGH;
2715 case OSD_UNIT_IMPERIAL:
2716 moreThanAh = osdFormatCentiNumber(buff, value * METERS_PER_MILE / 10, 1000, 0, 2, 3);
2717 if (!moreThanAh) {
2718 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_MI_0, SYM_MAH_MI_1);
2719 } else {
2720 tfp_sprintf(buff, "%s%c", buff, SYM_AH_MI);
2722 if (!efficiencyValid) {
2723 buff[0] = buff[1] = buff[2] = '-';
2724 buff[3] = SYM_MAH_MI_0;
2725 buff[4] = SYM_MAH_MI_1;
2726 buff[5] = '\0';
2728 break;
2729 case OSD_UNIT_GA:
2730 moreThanAh = osdFormatCentiNumber(buff, value * METERS_PER_NAUTICALMILE / 10, 1000, 0, 2, 3);
2731 if (!moreThanAh) {
2732 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_NM_0, SYM_MAH_NM_1);
2733 } else {
2734 tfp_sprintf(buff, "%s%c", buff, SYM_AH_NM);
2736 if (!efficiencyValid) {
2737 buff[0] = buff[1] = buff[2] = '-';
2738 buff[3] = SYM_MAH_NM_0;
2739 buff[4] = SYM_MAH_NM_1;
2740 buff[5] = '\0';
2742 break;
2743 case OSD_UNIT_METRIC_MPH:
2744 FALLTHROUGH;
2745 case OSD_UNIT_METRIC:
2746 moreThanAh = osdFormatCentiNumber(buff, value * 100, 1000, 0, 2, 3);
2747 if (!moreThanAh) {
2748 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_KM_0, SYM_MAH_KM_1);
2749 } else {
2750 tfp_sprintf(buff, "%s%c", buff, SYM_AH_KM);
2752 if (!efficiencyValid) {
2753 buff[0] = buff[1] = buff[2] = '-';
2754 buff[3] = SYM_MAH_KM_0;
2755 buff[4] = SYM_MAH_KM_1;
2756 buff[5] = '\0';
2758 break;
2760 break;
2763 case OSD_EFFICIENCY_WH_PER_KM:
2765 // amperage is in centi amps, speed is in cms/s. We want
2766 // mWh/km. Only show when ground speed > 1m/s.
2767 static pt1Filter_t eFilterState;
2768 static timeUs_t efficiencyUpdated = 0;
2769 int32_t value = 0;
2770 timeUs_t currentTimeUs = micros();
2771 timeDelta_t efficiencyTimeDelta = cmpTimeUs(currentTimeUs, efficiencyUpdated);
2772 if (STATE(GPS_FIX) && gpsSol.groundSpeed > 0) {
2773 if (efficiencyTimeDelta >= EFFICIENCY_UPDATE_INTERVAL) {
2774 value = pt1FilterApply4(&eFilterState, ((float)getPower() / gpsSol.groundSpeed) / 0.0036f,
2775 1, US2S(efficiencyTimeDelta));
2777 efficiencyUpdated = currentTimeUs;
2778 } else {
2779 value = eFilterState.state;
2782 bool efficiencyValid = (value > 0) && (gpsSol.groundSpeed > 100);
2783 switch (osdConfig()->units) {
2784 case OSD_UNIT_UK:
2785 FALLTHROUGH;
2786 case OSD_UNIT_IMPERIAL:
2787 osdFormatCentiNumber(buff, value * METERS_PER_MILE / 10000, 0, 2, 0, 3);
2788 buff[3] = SYM_WH_MI;
2789 break;
2790 case OSD_UNIT_GA:
2791 osdFormatCentiNumber(buff, value * METERS_PER_NAUTICALMILE / 10000, 0, 2, 0, 3);
2792 buff[3] = SYM_WH_NM;
2793 break;
2794 case OSD_UNIT_METRIC_MPH:
2795 FALLTHROUGH;
2796 case OSD_UNIT_METRIC:
2797 osdFormatCentiNumber(buff, value / 10, 0, 2, 0, 3);
2798 buff[3] = SYM_WH_KM;
2799 break;
2801 buff[4] = '\0';
2802 if (!efficiencyValid) {
2803 buff[0] = buff[1] = buff[2] = '-';
2805 break;
2808 case OSD_GFORCE:
2810 buff[0] = SYM_GFORCE;
2811 osdFormatCentiNumber(buff + 1, GForce, 0, 2, 0, 3);
2812 if (GForce > osdConfig()->gforce_alarm * 100) {
2813 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2815 break;
2818 case OSD_GFORCE_X:
2819 case OSD_GFORCE_Y:
2820 case OSD_GFORCE_Z:
2822 float GForceValue = GForceAxis[item - OSD_GFORCE_X];
2823 buff[0] = SYM_GFORCE_X + item - OSD_GFORCE_X;
2824 osdFormatCentiNumber(buff + 1, GForceValue, 0, 2, 0, 4);
2825 if ((GForceValue < osdConfig()->gforce_axis_alarm_min * 100) || (GForceValue > osdConfig()->gforce_axis_alarm_max * 100)) {
2826 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2828 break;
2830 case OSD_DEBUG:
2833 * Longest representable string is -2147483648 does not fit in the screen.
2834 * Only 7 digits for negative and 8 digits for positive values allowed
2836 for (uint8_t bufferIndex = 0; bufferIndex < DEBUG32_VALUE_COUNT; ++elemPosY, bufferIndex += 2) {
2837 tfp_sprintf(
2838 buff,
2839 "[%u]=%8ld [%u]=%8ld",
2840 bufferIndex,
2841 constrain(debug[bufferIndex], -9999999, 99999999),
2842 bufferIndex+1,
2843 constrain(debug[bufferIndex+1], -9999999, 99999999)
2845 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
2847 break;
2850 case OSD_IMU_TEMPERATURE:
2852 int16_t temperature;
2853 const bool valid = getIMUTemperature(&temperature);
2854 osdDisplayTemperature(elemPosX, elemPosY, SYM_IMU_TEMP, NULL, valid, temperature, osdConfig()->imu_temp_alarm_min, osdConfig()->imu_temp_alarm_max);
2855 return true;
2858 case OSD_BARO_TEMPERATURE:
2860 int16_t temperature;
2861 const bool valid = getBaroTemperature(&temperature);
2862 osdDisplayTemperature(elemPosX, elemPosY, SYM_BARO_TEMP, NULL, valid, temperature, osdConfig()->imu_temp_alarm_min, osdConfig()->imu_temp_alarm_max);
2863 return true;
2866 #ifdef USE_TEMPERATURE_SENSOR
2867 case OSD_TEMP_SENSOR_0_TEMPERATURE:
2868 case OSD_TEMP_SENSOR_1_TEMPERATURE:
2869 case OSD_TEMP_SENSOR_2_TEMPERATURE:
2870 case OSD_TEMP_SENSOR_3_TEMPERATURE:
2871 case OSD_TEMP_SENSOR_4_TEMPERATURE:
2872 case OSD_TEMP_SENSOR_5_TEMPERATURE:
2873 case OSD_TEMP_SENSOR_6_TEMPERATURE:
2874 case OSD_TEMP_SENSOR_7_TEMPERATURE:
2876 osdDisplayTemperatureSensor(elemPosX, elemPosY, item - OSD_TEMP_SENSOR_0_TEMPERATURE);
2877 return true;
2879 #endif /* ifdef USE_TEMPERATURE_SENSOR */
2881 case OSD_WIND_SPEED_HORIZONTAL:
2882 #ifdef USE_WIND_ESTIMATOR
2884 bool valid = isEstimatedWindSpeedValid();
2885 float horizontalWindSpeed;
2886 if (valid) {
2887 uint16_t angle;
2888 horizontalWindSpeed = getEstimatedHorizontalWindSpeed(&angle);
2889 int16_t windDirection = osdGetHeadingAngle( CENTIDEGREES_TO_DEGREES((int)angle) - DECIDEGREES_TO_DEGREES(attitude.values.yaw) + 22);
2890 buff[1] = SYM_DIRECTION + (windDirection*2 / 90);
2891 } else {
2892 horizontalWindSpeed = 0;
2893 buff[1] = SYM_BLANK;
2895 buff[0] = SYM_WIND_HORIZONTAL;
2896 osdFormatWindSpeedStr(buff + 2, horizontalWindSpeed, valid);
2897 break;
2899 #else
2900 return false;
2901 #endif
2903 case OSD_WIND_SPEED_VERTICAL:
2904 #ifdef USE_WIND_ESTIMATOR
2906 buff[0] = SYM_WIND_VERTICAL;
2907 buff[1] = SYM_BLANK;
2908 bool valid = isEstimatedWindSpeedValid();
2909 float verticalWindSpeed;
2910 if (valid) {
2911 verticalWindSpeed = -getEstimatedWindSpeed(Z); //from NED to NEU
2912 if (verticalWindSpeed < 0) {
2913 buff[1] = SYM_AH_DECORATION_DOWN;
2914 verticalWindSpeed = -verticalWindSpeed;
2915 } else if (verticalWindSpeed > 0) {
2916 buff[1] = SYM_AH_DECORATION_UP;
2918 } else {
2919 verticalWindSpeed = 0;
2921 osdFormatWindSpeedStr(buff + 2, verticalWindSpeed, valid);
2922 break;
2924 #else
2925 return false;
2926 #endif
2928 case OSD_PLUS_CODE:
2930 STATIC_ASSERT(GPS_DEGREES_DIVIDER == OLC_DEG_MULTIPLIER, invalid_olc_deg_multiplier);
2931 int digits = osdConfig()->plus_code_digits;
2932 int digitsRemoved = osdConfig()->plus_code_short * 2;
2933 if (STATE(GPS_FIX)) {
2934 olc_encode(gpsSol.llh.lat, gpsSol.llh.lon, digits, buff, sizeof(buff));
2935 } else {
2936 // +codes with > 8 digits have a + at the 9th digit
2937 // and we only support 10 and up.
2938 memset(buff, '-', digits + 1);
2939 buff[8] = '+';
2940 buff[digits + 1] = '\0';
2942 // Optionally trim digits from the left
2943 memmove(buff, buff+digitsRemoved, strlen(buff) + digitsRemoved);
2944 buff[digits + 1 - digitsRemoved] = '\0';
2945 break;
2948 case OSD_AZIMUTH:
2951 buff[0] = SYM_AZIMUTH;
2952 if (osdIsHeadingValid()) {
2953 int16_t h = GPS_directionToHome;
2954 if (h < 0) {
2955 h += 360;
2957 if(h >= 180)
2958 h = h - 180;
2959 else
2960 h = h + 180;
2962 tfp_sprintf(&buff[1], "%3d", h);
2963 } else {
2964 buff[1] = buff[2] = buff[3] = '-';
2966 buff[4] = SYM_DEGREES;
2967 buff[5] = '\0';
2968 break;
2971 case OSD_MAP_SCALE:
2973 float scaleToUnit;
2974 int scaleUnitDivisor;
2975 char symUnscaled;
2976 char symScaled;
2977 int maxDecimals;
2979 switch (osdConfig()->units) {
2980 case OSD_UNIT_UK:
2981 FALLTHROUGH;
2982 case OSD_UNIT_IMPERIAL:
2983 scaleToUnit = 100 / 1609.3440f; // scale to 0.01mi for osdFormatCentiNumber()
2984 scaleUnitDivisor = 0;
2985 symUnscaled = SYM_MI;
2986 symScaled = SYM_MI;
2987 maxDecimals = 2;
2988 break;
2989 case OSD_UNIT_GA:
2990 scaleToUnit = 100 / 1852.0010f; // scale to 0.01mi for osdFormatCentiNumber()
2991 scaleUnitDivisor = 0;
2992 symUnscaled = SYM_NM;
2993 symScaled = SYM_NM;
2994 maxDecimals = 2;
2995 break;
2996 default:
2997 case OSD_UNIT_METRIC_MPH:
2998 FALLTHROUGH;
2999 case OSD_UNIT_METRIC:
3000 scaleToUnit = 100; // scale to cm for osdFormatCentiNumber()
3001 scaleUnitDivisor = 1000; // Convert to km when scale gets bigger than 999m
3002 symUnscaled = SYM_M;
3003 symScaled = SYM_KM;
3004 maxDecimals = 0;
3005 break;
3007 buff[0] = SYM_SCALE;
3008 if (osdMapData.scale > 0) {
3009 bool scaled = osdFormatCentiNumber(&buff[1], osdMapData.scale * scaleToUnit, scaleUnitDivisor, maxDecimals, 2, 3);
3010 buff[4] = scaled ? symScaled : symUnscaled;
3011 // Make sure this is cleared if the map stops being drawn
3012 osdMapData.scale = 0;
3013 } else {
3014 memset(&buff[1], '-', 4);
3016 buff[5] = '\0';
3017 break;
3019 case OSD_MAP_REFERENCE:
3021 char referenceSymbol;
3022 if (osdMapData.referenceSymbol) {
3023 referenceSymbol = osdMapData.referenceSymbol;
3024 // Make sure this is cleared if the map stops being drawn
3025 osdMapData.referenceSymbol = 0;
3026 } else {
3027 referenceSymbol = '-';
3029 displayWriteChar(osdDisplayPort, elemPosX, elemPosY, SYM_DIRECTION);
3030 displayWriteChar(osdDisplayPort, elemPosX, elemPosY + 1, referenceSymbol);
3031 return true;
3034 case OSD_GVAR_0:
3036 osdFormatGVar(buff, 0);
3037 break;
3039 case OSD_GVAR_1:
3041 osdFormatGVar(buff, 1);
3042 break;
3044 case OSD_GVAR_2:
3046 osdFormatGVar(buff, 2);
3047 break;
3049 case OSD_GVAR_3:
3051 osdFormatGVar(buff, 3);
3052 break;
3055 #if defined(USE_RX_MSP) && defined(USE_MSP_RC_OVERRIDE)
3056 case OSD_RC_SOURCE:
3058 const char *source_text = IS_RC_MODE_ACTIVE(BOXMSPRCOVERRIDE) && !mspOverrideIsInFailsafe() ? "MSP" : "STD";
3059 if (IS_RC_MODE_ACTIVE(BOXMSPRCOVERRIDE) && mspOverrideIsInFailsafe()) TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
3060 displayWriteWithAttr(osdDisplayPort, elemPosX, elemPosY, source_text, elemAttr);
3061 return true;
3063 #endif
3065 #if defined(USE_ESC_SENSOR)
3066 case OSD_ESC_RPM:
3068 escSensorData_t * escSensor = escSensorGetData();
3069 if (escSensor && escSensor->dataAge <= ESC_DATA_MAX_AGE) {
3070 osdFormatRpm(buff, escSensor->rpm);
3072 else {
3073 osdFormatRpm(buff, 0);
3075 break;
3077 case OSD_ESC_TEMPERATURE:
3079 escSensorData_t * escSensor = escSensorGetData();
3080 bool escTemperatureValid = escSensor && escSensor->dataAge <= ESC_DATA_MAX_AGE;
3081 osdDisplayTemperature(elemPosX, elemPosY, SYM_ESC_TEMP, NULL, escTemperatureValid, (escSensor->temperature)*10, osdConfig()->esc_temp_alarm_min, osdConfig()->esc_temp_alarm_max);
3082 return true;
3084 #endif
3085 case OSD_TPA:
3087 char buff[4];
3088 textAttributes_t attr;
3090 displayWrite(osdDisplayPort, elemPosX, elemPosY, "TPA");
3091 attr = TEXT_ATTRIBUTES_NONE;
3092 tfp_sprintf(buff, "%3d", currentControlRateProfile->throttle.dynPID);
3093 if (isAdjustmentFunctionSelected(ADJUSTMENT_TPA)) {
3094 TEXT_ATTRIBUTES_ADD_BLINK(attr);
3096 displayWriteWithAttr(osdDisplayPort, elemPosX + 5, elemPosY, buff, attr);
3098 displayWrite(osdDisplayPort, elemPosX, elemPosY + 1, "BP");
3099 attr = TEXT_ATTRIBUTES_NONE;
3100 tfp_sprintf(buff, "%4d", currentControlRateProfile->throttle.pa_breakpoint);
3101 if (isAdjustmentFunctionSelected(ADJUSTMENT_TPA_BREAKPOINT)) {
3102 TEXT_ATTRIBUTES_ADD_BLINK(attr);
3104 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY + 1, buff, attr);
3106 return true;
3108 case OSD_TPA_TIME_CONSTANT:
3110 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "TPA TC", 0, currentControlRateProfile->throttle.fixedWingTauMs, 4, 0, ADJUSTMENT_FW_TPA_TIME_CONSTANT);
3111 return true;
3113 case OSD_FW_LEVEL_TRIM:
3115 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "LEVEL", 0, pidProfileMutable()->fixedWingLevelTrim, 3, 1, ADJUSTMENT_FW_LEVEL_TRIM);
3116 return true;
3119 case OSD_NAV_FW_CONTROL_SMOOTHNESS:
3121 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "CTL S", 0, navConfig()->fw.control_smoothness, 1, 0, ADJUSTMENT_NAV_FW_CONTROL_SMOOTHNESS);
3122 return true;
3124 #ifdef USE_MULTI_MISSION
3125 case OSD_NAV_WP_MULTI_MISSION_INDEX:
3127 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "WP NO", 0, navConfig()->general.waypoint_multi_mission_index, 1, 0, ADJUSTMENT_NAV_WP_MULTI_MISSION_INDEX);
3128 return true;
3130 #endif
3131 case OSD_MISSION:
3133 if (IS_RC_MODE_ACTIVE(BOXPLANWPMISSION)) {
3134 char buf[5];
3135 switch (posControl.wpMissionPlannerStatus) {
3136 case WP_PLAN_WAIT:
3137 strcpy(buf, "WAIT");
3138 break;
3139 case WP_PLAN_SAVE:
3140 strcpy(buf, "SAVE");
3141 break;
3142 case WP_PLAN_OK:
3143 strcpy(buf, " OK ");
3144 break;
3145 case WP_PLAN_FULL:
3146 strcpy(buf, "FULL");
3148 tfp_sprintf(buff, "%s>%2uWP", buf, posControl.wpPlannerActiveWPIndex);
3149 } else if (posControl.wpPlannerActiveWPIndex){
3150 tfp_sprintf(buff, "PLAN>%2uWP", posControl.waypointCount); // mission planner mision active
3152 #ifdef USE_MULTI_MISSION
3153 else {
3154 if (ARMING_FLAG(ARMED) && !(IS_RC_MODE_ACTIVE(BOXCHANGEMISSION) && posControl.multiMissionCount > 1)){
3155 // Limit field size when Armed, only show selected mission
3156 tfp_sprintf(buff, "M%u ", posControl.loadedMultiMissionIndex);
3157 } else if (posControl.multiMissionCount) {
3158 if (navConfig()->general.waypoint_multi_mission_index != posControl.loadedMultiMissionIndex) {
3159 tfp_sprintf(buff, "M%u/%u>LOAD", navConfig()->general.waypoint_multi_mission_index, posControl.multiMissionCount);
3160 } else {
3161 if (posControl.waypointListValid && posControl.waypointCount > 0) {
3162 tfp_sprintf(buff, "M%u/%u>%2uWP", posControl.loadedMultiMissionIndex, posControl.multiMissionCount, posControl.waypointCount);
3163 } else {
3164 tfp_sprintf(buff, "M0/%u> 0WP", posControl.multiMissionCount);
3167 } else { // no multi mission loaded - show active WP count from other source
3168 tfp_sprintf(buff, "WP CNT>%2u", posControl.waypointCount);
3171 #endif
3172 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
3173 return true;
3176 #ifdef USE_POWER_LIMITS
3177 case OSD_PLIMIT_REMAINING_BURST_TIME:
3178 osdFormatCentiNumber(buff, powerLimiterGetRemainingBurstTime() * 100, 0, 1, 0, 3);
3179 buff[3] = 'S';
3180 buff[4] = '\0';
3181 break;
3183 case OSD_PLIMIT_ACTIVE_CURRENT_LIMIT:
3184 if (currentBatteryProfile->powerLimits.continuousCurrent) {
3185 osdFormatCentiNumber(buff, powerLimiterGetActiveCurrentLimit(), 0, 2, 0, 3);
3186 buff[3] = SYM_AMP;
3187 buff[4] = '\0';
3189 if (powerLimiterIsLimitingCurrent()) {
3190 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
3193 break;
3195 #ifdef USE_ADC
3196 case OSD_PLIMIT_ACTIVE_POWER_LIMIT:
3198 if (currentBatteryProfile->powerLimits.continuousPower) {
3199 bool kiloWatt = osdFormatCentiNumber(buff, powerLimiterGetActivePowerLimit(), 1000, 2, 2, 3);
3200 buff[3] = kiloWatt ? SYM_KILOWATT : SYM_WATT;
3201 buff[4] = '\0';
3203 if (powerLimiterIsLimitingPower()) {
3204 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
3207 break;
3209 #endif // USE_ADC
3210 #endif // USE_POWER_LIMITS
3212 default:
3213 return false;
3216 displayWriteWithAttr(osdDisplayPort, elemPosX, elemPosY, buff, elemAttr);
3217 return true;
3220 uint8_t osdIncElementIndex(uint8_t elementIndex)
3222 ++elementIndex;
3224 if (elementIndex == OSD_ARTIFICIAL_HORIZON)
3225 ++elementIndex;
3227 #ifndef USE_TEMPERATURE_SENSOR
3228 if (elementIndex == OSD_TEMP_SENSOR_0_TEMPERATURE)
3229 elementIndex = OSD_ALTITUDE_MSL;
3230 #endif
3232 if (!sensors(SENSOR_ACC)) {
3233 if (elementIndex == OSD_CROSSHAIRS) {
3234 elementIndex = OSD_ONTIME;
3238 if (!feature(FEATURE_VBAT)) {
3239 if (elementIndex == OSD_SAG_COMPENSATED_MAIN_BATT_VOLTAGE) {
3240 elementIndex = OSD_LEVEL_PIDS;
3244 if (!feature(FEATURE_CURRENT_METER)) {
3245 if (elementIndex == OSD_CURRENT_DRAW) {
3246 elementIndex = OSD_GPS_SPEED;
3248 if (elementIndex == OSD_EFFICIENCY_MAH_PER_KM) {
3249 elementIndex = OSD_TRIP_DIST;
3251 if (elementIndex == OSD_REMAINING_FLIGHT_TIME_BEFORE_RTH) {
3252 elementIndex = OSD_HOME_HEADING_ERROR;
3254 if (elementIndex == OSD_SAG_COMPENSATED_MAIN_BATT_VOLTAGE) {
3255 elementIndex = OSD_LEVEL_PIDS;
3259 if (!feature(FEATURE_GPS)) {
3260 if (elementIndex == OSD_GPS_SPEED) {
3261 elementIndex = OSD_ALTITUDE;
3263 if (elementIndex == OSD_GPS_LON) {
3264 elementIndex = OSD_VARIO;
3266 if (elementIndex == OSD_GPS_HDOP) {
3267 elementIndex = OSD_MAIN_BATT_CELL_VOLTAGE;
3269 if (elementIndex == OSD_TRIP_DIST) {
3270 elementIndex = OSD_ATTITUDE_PITCH;
3272 if (elementIndex == OSD_WIND_SPEED_HORIZONTAL) {
3273 elementIndex = OSD_SAG_COMPENSATED_MAIN_BATT_VOLTAGE;
3275 if (elementIndex == OSD_3D_SPEED) {
3276 elementIndex++;
3280 if (!STATE(ESC_SENSOR_ENABLED)) {
3281 if (elementIndex == OSD_ESC_RPM) {
3282 elementIndex++;
3286 #ifndef USE_POWER_LIMITS
3287 if (elementIndex == OSD_NAV_FW_CONTROL_SMOOTHNESS) {
3288 elementIndex = OSD_ITEM_COUNT;
3290 #endif
3292 if (elementIndex == OSD_ITEM_COUNT) {
3293 elementIndex = 0;
3295 return elementIndex;
3298 void osdDrawNextElement(void)
3300 static uint8_t elementIndex = 0;
3301 // Prevent infinite loop when no elements are enabled
3302 uint8_t index = elementIndex;
3303 do {
3304 elementIndex = osdIncElementIndex(elementIndex);
3305 } while(!osdDrawSingleElement(elementIndex) && index != elementIndex);
3307 // Draw artificial horizon + tracking telemtry last
3308 osdDrawSingleElement(OSD_ARTIFICIAL_HORIZON);
3309 if (osdConfig()->telemetry>0){
3310 osdDisplayTelemetry();
3314 PG_RESET_TEMPLATE(osdConfig_t, osdConfig,
3315 .rssi_alarm = SETTING_OSD_RSSI_ALARM_DEFAULT,
3316 .time_alarm = SETTING_OSD_TIME_ALARM_DEFAULT,
3317 .alt_alarm = SETTING_OSD_ALT_ALARM_DEFAULT,
3318 .dist_alarm = SETTING_OSD_DIST_ALARM_DEFAULT,
3319 .neg_alt_alarm = SETTING_OSD_NEG_ALT_ALARM_DEFAULT,
3320 .current_alarm = SETTING_OSD_CURRENT_ALARM_DEFAULT,
3321 .imu_temp_alarm_min = SETTING_OSD_IMU_TEMP_ALARM_MIN_DEFAULT,
3322 .imu_temp_alarm_max = SETTING_OSD_IMU_TEMP_ALARM_MAX_DEFAULT,
3323 .esc_temp_alarm_min = SETTING_OSD_ESC_TEMP_ALARM_MIN_DEFAULT,
3324 .esc_temp_alarm_max = SETTING_OSD_ESC_TEMP_ALARM_MAX_DEFAULT,
3325 .gforce_alarm = SETTING_OSD_GFORCE_ALARM_DEFAULT,
3326 .gforce_axis_alarm_min = SETTING_OSD_GFORCE_AXIS_ALARM_MIN_DEFAULT,
3327 .gforce_axis_alarm_max = SETTING_OSD_GFORCE_AXIS_ALARM_MAX_DEFAULT,
3328 #ifdef USE_BARO
3329 .baro_temp_alarm_min = SETTING_OSD_BARO_TEMP_ALARM_MIN_DEFAULT,
3330 .baro_temp_alarm_max = SETTING_OSD_BARO_TEMP_ALARM_MAX_DEFAULT,
3331 #endif
3332 #ifdef USE_SERIALRX_CRSF
3333 .snr_alarm = SETTING_OSD_SNR_ALARM_DEFAULT,
3334 .crsf_lq_format = SETTING_OSD_CRSF_LQ_FORMAT_DEFAULT,
3335 .link_quality_alarm = SETTING_OSD_LINK_QUALITY_ALARM_DEFAULT,
3336 .rssi_dbm_alarm = SETTING_OSD_RSSI_DBM_ALARM_DEFAULT,
3337 .rssi_dbm_max = SETTING_OSD_RSSI_DBM_MAX_DEFAULT,
3338 .rssi_dbm_min = SETTING_OSD_RSSI_DBM_MIN_DEFAULT,
3339 #endif
3340 #ifdef USE_TEMPERATURE_SENSOR
3341 .temp_label_align = SETTING_OSD_TEMP_LABEL_ALIGN_DEFAULT,
3342 #endif
3343 #ifdef USE_PITOT
3344 .airspeed_alarm_min = SETTING_OSD_AIRSPEED_ALARM_MIN_DEFAULT,
3345 .airspeed_alarm_max = SETTING_OSD_AIRSPEED_ALARM_MAX_DEFAULT,
3346 #endif
3348 .video_system = SETTING_OSD_VIDEO_SYSTEM_DEFAULT,
3349 .row_shiftdown = SETTING_OSD_ROW_SHIFTDOWN_DEFAULT,
3350 .msp_displayport_pframe_interval = SETTING_OSD_MSP_DISPLAYPORT_PFRAME_INTERVAL_DEFAULT,
3352 .ahi_reverse_roll = SETTING_OSD_AHI_REVERSE_ROLL_DEFAULT,
3353 .ahi_max_pitch = SETTING_OSD_AHI_MAX_PITCH_DEFAULT,
3354 .crosshairs_style = SETTING_OSD_CROSSHAIRS_STYLE_DEFAULT,
3355 .horizon_offset = SETTING_OSD_HORIZON_OFFSET_DEFAULT,
3356 .camera_uptilt = SETTING_OSD_CAMERA_UPTILT_DEFAULT,
3357 .ahi_camera_uptilt_comp = SETTING_OSD_AHI_CAMERA_UPTILT_COMP_DEFAULT,
3358 .camera_fov_h = SETTING_OSD_CAMERA_FOV_H_DEFAULT,
3359 .camera_fov_v = SETTING_OSD_CAMERA_FOV_V_DEFAULT,
3360 .hud_margin_h = SETTING_OSD_HUD_MARGIN_H_DEFAULT,
3361 .hud_margin_v = SETTING_OSD_HUD_MARGIN_V_DEFAULT,
3362 .hud_homing = SETTING_OSD_HUD_HOMING_DEFAULT,
3363 .hud_homepoint = SETTING_OSD_HUD_HOMEPOINT_DEFAULT,
3364 .hud_radar_disp = SETTING_OSD_HUD_RADAR_DISP_DEFAULT,
3365 .hud_radar_range_min = SETTING_OSD_HUD_RADAR_RANGE_MIN_DEFAULT,
3366 .hud_radar_range_max = SETTING_OSD_HUD_RADAR_RANGE_MAX_DEFAULT,
3367 .hud_radar_alt_difference_display_time = SETTING_OSD_HUD_RADAR_ALT_DIFFERENCE_DISPLAY_TIME_DEFAULT,
3368 .hud_radar_distance_display_time = SETTING_OSD_HUD_RADAR_DISTANCE_DISPLAY_TIME_DEFAULT,
3369 .hud_wp_disp = SETTING_OSD_HUD_WP_DISP_DEFAULT,
3370 .left_sidebar_scroll = SETTING_OSD_LEFT_SIDEBAR_SCROLL_DEFAULT,
3371 .right_sidebar_scroll = SETTING_OSD_RIGHT_SIDEBAR_SCROLL_DEFAULT,
3372 .sidebar_scroll_arrows = SETTING_OSD_SIDEBAR_SCROLL_ARROWS_DEFAULT,
3373 .sidebar_horizontal_offset = SETTING_OSD_SIDEBAR_HORIZONTAL_OFFSET_DEFAULT,
3374 .left_sidebar_scroll_step = SETTING_OSD_LEFT_SIDEBAR_SCROLL_STEP_DEFAULT,
3375 .right_sidebar_scroll_step = SETTING_OSD_RIGHT_SIDEBAR_SCROLL_STEP_DEFAULT,
3376 .sidebar_height = SETTING_OSD_SIDEBAR_HEIGHT_DEFAULT,
3377 .osd_home_position_arm_screen = SETTING_OSD_HOME_POSITION_ARM_SCREEN_DEFAULT,
3378 .pan_servo_index = SETTING_OSD_PAN_SERVO_INDEX_DEFAULT,
3379 .pan_servo_pwm2centideg = SETTING_OSD_PAN_SERVO_PWM2CENTIDEG_DEFAULT,
3380 .esc_rpm_precision = SETTING_OSD_ESC_RPM_PRECISION_DEFAULT,
3381 .mAh_used_precision = SETTING_OSD_MAH_USED_PRECISION_DEFAULT,
3382 .osd_switch_indicator0_name = SETTING_OSD_SWITCH_INDICATOR_ZERO_NAME_DEFAULT,
3383 .osd_switch_indicator0_channel = SETTING_OSD_SWITCH_INDICATOR_ZERO_CHANNEL_DEFAULT,
3384 .osd_switch_indicator1_name = SETTING_OSD_SWITCH_INDICATOR_ONE_NAME_DEFAULT,
3385 .osd_switch_indicator1_channel = SETTING_OSD_SWITCH_INDICATOR_ONE_CHANNEL_DEFAULT,
3386 .osd_switch_indicator2_name = SETTING_OSD_SWITCH_INDICATOR_TWO_NAME_DEFAULT,
3387 .osd_switch_indicator2_channel = SETTING_OSD_SWITCH_INDICATOR_TWO_CHANNEL_DEFAULT,
3388 .osd_switch_indicator3_name = SETTING_OSD_SWITCH_INDICATOR_THREE_NAME_DEFAULT,
3389 .osd_switch_indicator3_channel = SETTING_OSD_SWITCH_INDICATOR_THREE_CHANNEL_DEFAULT,
3390 .osd_switch_indicators_align_left = SETTING_OSD_SWITCH_INDICATORS_ALIGN_LEFT_DEFAULT,
3391 .system_msg_display_time = SETTING_OSD_SYSTEM_MSG_DISPLAY_TIME_DEFAULT,
3392 .units = SETTING_OSD_UNITS_DEFAULT,
3393 .main_voltage_decimals = SETTING_OSD_MAIN_VOLTAGE_DECIMALS_DEFAULT,
3395 #ifdef USE_WIND_ESTIMATOR
3396 .estimations_wind_compensation = SETTING_OSD_ESTIMATIONS_WIND_COMPENSATION_DEFAULT,
3397 #endif
3399 .coordinate_digits = SETTING_OSD_COORDINATE_DIGITS_DEFAULT,
3401 .osd_failsafe_switch_layout = SETTING_OSD_FAILSAFE_SWITCH_LAYOUT_DEFAULT,
3403 .plus_code_digits = SETTING_OSD_PLUS_CODE_DIGITS_DEFAULT,
3404 .plus_code_short = SETTING_OSD_PLUS_CODE_SHORT_DEFAULT,
3406 .ahi_width = SETTING_OSD_AHI_WIDTH_DEFAULT,
3407 .ahi_height = SETTING_OSD_AHI_HEIGHT_DEFAULT,
3408 .ahi_vertical_offset = SETTING_OSD_AHI_VERTICAL_OFFSET_DEFAULT,
3409 .ahi_bordered = SETTING_OSD_AHI_BORDERED_DEFAULT,
3410 .ahi_style = SETTING_OSD_AHI_STYLE_DEFAULT,
3412 .force_grid = SETTING_OSD_FORCE_GRID_DEFAULT,
3414 .stats_energy_unit = SETTING_OSD_STATS_ENERGY_UNIT_DEFAULT,
3415 .stats_min_voltage_unit = SETTING_OSD_STATS_MIN_VOLTAGE_UNIT_DEFAULT,
3416 .stats_page_auto_swap_time = SETTING_OSD_STATS_PAGE_AUTO_SWAP_TIME_DEFAULT
3419 void pgResetFn_osdLayoutsConfig(osdLayoutsConfig_t *osdLayoutsConfig)
3421 osdLayoutsConfig->item_pos[0][OSD_ALTITUDE] = OSD_POS(1, 0) | OSD_VISIBLE_FLAG;
3422 osdLayoutsConfig->item_pos[0][OSD_MAIN_BATT_VOLTAGE] = OSD_POS(12, 0) | OSD_VISIBLE_FLAG;
3423 osdLayoutsConfig->item_pos[0][OSD_SAG_COMPENSATED_MAIN_BATT_VOLTAGE] = OSD_POS(12, 1);
3425 osdLayoutsConfig->item_pos[0][OSD_RSSI_VALUE] = OSD_POS(23, 0) | OSD_VISIBLE_FLAG;
3426 //line 2
3427 osdLayoutsConfig->item_pos[0][OSD_HOME_DIST] = OSD_POS(1, 1);
3428 osdLayoutsConfig->item_pos[0][OSD_TRIP_DIST] = OSD_POS(1, 2);
3429 osdLayoutsConfig->item_pos[0][OSD_MAIN_BATT_CELL_VOLTAGE] = OSD_POS(12, 1);
3430 osdLayoutsConfig->item_pos[0][OSD_MAIN_BATT_SAG_COMPENSATED_CELL_VOLTAGE] = OSD_POS(12, 1);
3431 osdLayoutsConfig->item_pos[0][OSD_GPS_SPEED] = OSD_POS(23, 1);
3432 osdLayoutsConfig->item_pos[0][OSD_3D_SPEED] = OSD_POS(23, 1);
3433 osdLayoutsConfig->item_pos[0][OSD_GLIDESLOPE] = OSD_POS(23, 2);
3435 osdLayoutsConfig->item_pos[0][OSD_THROTTLE_POS] = OSD_POS(1, 2) | OSD_VISIBLE_FLAG;
3436 osdLayoutsConfig->item_pos[0][OSD_THROTTLE_POS_AUTO_THR] = OSD_POS(6, 2);
3437 osdLayoutsConfig->item_pos[0][OSD_HEADING] = OSD_POS(12, 2);
3438 osdLayoutsConfig->item_pos[0][OSD_COURSE_HOLD_ERROR] = OSD_POS(12, 2);
3439 osdLayoutsConfig->item_pos[0][OSD_COURSE_HOLD_ADJUSTMENT] = OSD_POS(12, 2);
3440 osdLayoutsConfig->item_pos[0][OSD_HEADING_GRAPH] = OSD_POS(18, 2);
3441 osdLayoutsConfig->item_pos[0][OSD_CURRENT_DRAW] = OSD_POS(2, 3) | OSD_VISIBLE_FLAG;
3442 osdLayoutsConfig->item_pos[0][OSD_MAH_DRAWN] = OSD_POS(1, 4) | OSD_VISIBLE_FLAG;
3443 osdLayoutsConfig->item_pos[0][OSD_WH_DRAWN] = OSD_POS(1, 5);
3444 osdLayoutsConfig->item_pos[0][OSD_BATTERY_REMAINING_CAPACITY] = OSD_POS(1, 6);
3445 osdLayoutsConfig->item_pos[0][OSD_BATTERY_REMAINING_PERCENT] = OSD_POS(1, 7);
3446 osdLayoutsConfig->item_pos[0][OSD_POWER_SUPPLY_IMPEDANCE] = OSD_POS(1, 8);
3448 osdLayoutsConfig->item_pos[0][OSD_EFFICIENCY_MAH_PER_KM] = OSD_POS(1, 5);
3449 osdLayoutsConfig->item_pos[0][OSD_EFFICIENCY_WH_PER_KM] = OSD_POS(1, 5);
3451 osdLayoutsConfig->item_pos[0][OSD_ATTITUDE_ROLL] = OSD_POS(1, 7);
3452 osdLayoutsConfig->item_pos[0][OSD_ATTITUDE_PITCH] = OSD_POS(1, 8);
3454 // avoid OSD_VARIO under OSD_CROSSHAIRS
3455 osdLayoutsConfig->item_pos[0][OSD_VARIO] = OSD_POS(23, 5);
3456 // OSD_VARIO_NUM at the right of OSD_VARIO
3457 osdLayoutsConfig->item_pos[0][OSD_VARIO_NUM] = OSD_POS(24, 7);
3458 osdLayoutsConfig->item_pos[0][OSD_HOME_DIR] = OSD_POS(14, 11);
3459 osdLayoutsConfig->item_pos[0][OSD_ARTIFICIAL_HORIZON] = OSD_POS(8, 6);
3460 osdLayoutsConfig->item_pos[0][OSD_HORIZON_SIDEBARS] = OSD_POS(8, 6);
3462 osdLayoutsConfig->item_pos[0][OSD_CRAFT_NAME] = OSD_POS(20, 2);
3463 osdLayoutsConfig->item_pos[0][OSD_VTX_CHANNEL] = OSD_POS(8, 6);
3465 #ifdef USE_SERIALRX_CRSF
3466 osdLayoutsConfig->item_pos[0][OSD_CRSF_RSSI_DBM] = OSD_POS(23, 12);
3467 osdLayoutsConfig->item_pos[0][OSD_CRSF_LQ] = OSD_POS(23, 11);
3468 osdLayoutsConfig->item_pos[0][OSD_CRSF_SNR_DB] = OSD_POS(24, 9);
3469 osdLayoutsConfig->item_pos[0][OSD_CRSF_TX_POWER] = OSD_POS(24, 10);
3470 #endif
3472 osdLayoutsConfig->item_pos[0][OSD_ONTIME] = OSD_POS(23, 8);
3473 osdLayoutsConfig->item_pos[0][OSD_FLYTIME] = OSD_POS(23, 9);
3474 osdLayoutsConfig->item_pos[0][OSD_ONTIME_FLYTIME] = OSD_POS(23, 11) | OSD_VISIBLE_FLAG;
3475 osdLayoutsConfig->item_pos[0][OSD_RTC_TIME] = OSD_POS(23, 12);
3476 osdLayoutsConfig->item_pos[0][OSD_REMAINING_FLIGHT_TIME_BEFORE_RTH] = OSD_POS(23, 7);
3477 osdLayoutsConfig->item_pos[0][OSD_REMAINING_DISTANCE_BEFORE_RTH] = OSD_POS(23, 6);
3479 osdLayoutsConfig->item_pos[0][OSD_MISSION] = OSD_POS(0, 10);
3480 osdLayoutsConfig->item_pos[0][OSD_GPS_SATS] = OSD_POS(0, 11) | OSD_VISIBLE_FLAG;
3481 osdLayoutsConfig->item_pos[0][OSD_GPS_HDOP] = OSD_POS(0, 10);
3483 osdLayoutsConfig->item_pos[0][OSD_GPS_LAT] = OSD_POS(0, 12);
3484 // Put this on top of the latitude, since it's very unlikely
3485 // that users will want to use both at the same time.
3486 osdLayoutsConfig->item_pos[0][OSD_PLUS_CODE] = OSD_POS(0, 12);
3487 osdLayoutsConfig->item_pos[0][OSD_FLYMODE] = OSD_POS(13, 12) | OSD_VISIBLE_FLAG;
3488 osdLayoutsConfig->item_pos[0][OSD_GPS_LON] = OSD_POS(18, 12);
3490 osdLayoutsConfig->item_pos[0][OSD_AZIMUTH] = OSD_POS(2, 12);
3492 osdLayoutsConfig->item_pos[0][OSD_ROLL_PIDS] = OSD_POS(2, 10);
3493 osdLayoutsConfig->item_pos[0][OSD_PITCH_PIDS] = OSD_POS(2, 11);
3494 osdLayoutsConfig->item_pos[0][OSD_YAW_PIDS] = OSD_POS(2, 12);
3495 osdLayoutsConfig->item_pos[0][OSD_LEVEL_PIDS] = OSD_POS(2, 12);
3496 osdLayoutsConfig->item_pos[0][OSD_POS_XY_PIDS] = OSD_POS(2, 12);
3497 osdLayoutsConfig->item_pos[0][OSD_POS_Z_PIDS] = OSD_POS(2, 12);
3498 osdLayoutsConfig->item_pos[0][OSD_VEL_XY_PIDS] = OSD_POS(2, 12);
3499 osdLayoutsConfig->item_pos[0][OSD_VEL_Z_PIDS] = OSD_POS(2, 12);
3500 osdLayoutsConfig->item_pos[0][OSD_HEADING_P] = OSD_POS(2, 12);
3501 osdLayoutsConfig->item_pos[0][OSD_BOARD_ALIGN_ROLL] = OSD_POS(2, 10);
3502 osdLayoutsConfig->item_pos[0][OSD_BOARD_ALIGN_PITCH] = OSD_POS(2, 11);
3503 osdLayoutsConfig->item_pos[0][OSD_RC_EXPO] = OSD_POS(2, 12);
3504 osdLayoutsConfig->item_pos[0][OSD_RC_YAW_EXPO] = OSD_POS(2, 12);
3505 osdLayoutsConfig->item_pos[0][OSD_THROTTLE_EXPO] = OSD_POS(2, 12);
3506 osdLayoutsConfig->item_pos[0][OSD_PITCH_RATE] = OSD_POS(2, 12);
3507 osdLayoutsConfig->item_pos[0][OSD_ROLL_RATE] = OSD_POS(2, 12);
3508 osdLayoutsConfig->item_pos[0][OSD_YAW_RATE] = OSD_POS(2, 12);
3509 osdLayoutsConfig->item_pos[0][OSD_MANUAL_RC_EXPO] = OSD_POS(2, 12);
3510 osdLayoutsConfig->item_pos[0][OSD_MANUAL_RC_YAW_EXPO] = OSD_POS(2, 12);
3511 osdLayoutsConfig->item_pos[0][OSD_MANUAL_PITCH_RATE] = OSD_POS(2, 12);
3512 osdLayoutsConfig->item_pos[0][OSD_MANUAL_ROLL_RATE] = OSD_POS(2, 12);
3513 osdLayoutsConfig->item_pos[0][OSD_MANUAL_YAW_RATE] = OSD_POS(2, 12);
3514 osdLayoutsConfig->item_pos[0][OSD_NAV_FW_CRUISE_THR] = OSD_POS(2, 12);
3515 osdLayoutsConfig->item_pos[0][OSD_NAV_FW_PITCH2THR] = OSD_POS(2, 12);
3516 osdLayoutsConfig->item_pos[0][OSD_FW_MIN_THROTTLE_DOWN_PITCH_ANGLE] = OSD_POS(2, 12);
3517 osdLayoutsConfig->item_pos[0][OSD_FW_ALT_PID_OUTPUTS] = OSD_POS(2, 12);
3518 osdLayoutsConfig->item_pos[0][OSD_FW_POS_PID_OUTPUTS] = OSD_POS(2, 12);
3519 osdLayoutsConfig->item_pos[0][OSD_MC_VEL_X_PID_OUTPUTS] = OSD_POS(2, 12);
3520 osdLayoutsConfig->item_pos[0][OSD_MC_VEL_Y_PID_OUTPUTS] = OSD_POS(2, 12);
3521 osdLayoutsConfig->item_pos[0][OSD_MC_VEL_Z_PID_OUTPUTS] = OSD_POS(2, 12);
3522 osdLayoutsConfig->item_pos[0][OSD_MC_POS_XYZ_P_OUTPUTS] = OSD_POS(2, 12);
3524 osdLayoutsConfig->item_pos[0][OSD_POWER] = OSD_POS(15, 1);
3526 osdLayoutsConfig->item_pos[0][OSD_IMU_TEMPERATURE] = OSD_POS(19, 2);
3527 osdLayoutsConfig->item_pos[0][OSD_BARO_TEMPERATURE] = OSD_POS(19, 3);
3528 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_0_TEMPERATURE] = OSD_POS(19, 4);
3529 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_1_TEMPERATURE] = OSD_POS(19, 5);
3530 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_2_TEMPERATURE] = OSD_POS(19, 6);
3531 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_3_TEMPERATURE] = OSD_POS(19, 7);
3532 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_4_TEMPERATURE] = OSD_POS(19, 8);
3533 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_5_TEMPERATURE] = OSD_POS(19, 9);
3534 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_6_TEMPERATURE] = OSD_POS(19, 10);
3535 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_7_TEMPERATURE] = OSD_POS(19, 11);
3537 osdLayoutsConfig->item_pos[0][OSD_AIR_SPEED] = OSD_POS(3, 5);
3538 osdLayoutsConfig->item_pos[0][OSD_WIND_SPEED_HORIZONTAL] = OSD_POS(3, 6);
3539 osdLayoutsConfig->item_pos[0][OSD_WIND_SPEED_VERTICAL] = OSD_POS(3, 7);
3541 osdLayoutsConfig->item_pos[0][OSD_GFORCE] = OSD_POS(12, 4);
3542 osdLayoutsConfig->item_pos[0][OSD_GFORCE_X] = OSD_POS(12, 5);
3543 osdLayoutsConfig->item_pos[0][OSD_GFORCE_Y] = OSD_POS(12, 6);
3544 osdLayoutsConfig->item_pos[0][OSD_GFORCE_Z] = OSD_POS(12, 7);
3546 osdLayoutsConfig->item_pos[0][OSD_VTX_POWER] = OSD_POS(3, 5);
3548 osdLayoutsConfig->item_pos[0][OSD_GVAR_0] = OSD_POS(1, 1);
3549 osdLayoutsConfig->item_pos[0][OSD_GVAR_1] = OSD_POS(1, 2);
3550 osdLayoutsConfig->item_pos[0][OSD_GVAR_2] = OSD_POS(1, 3);
3551 osdLayoutsConfig->item_pos[0][OSD_GVAR_3] = OSD_POS(1, 4);
3553 osdLayoutsConfig->item_pos[0][OSD_SWITCH_INDICATOR_0] = OSD_POS(2, 7);
3554 osdLayoutsConfig->item_pos[0][OSD_SWITCH_INDICATOR_1] = OSD_POS(2, 8);
3555 osdLayoutsConfig->item_pos[0][OSD_SWITCH_INDICATOR_2] = OSD_POS(2, 9);
3556 osdLayoutsConfig->item_pos[0][OSD_SWITCH_INDICATOR_3] = OSD_POS(2, 10);
3558 #if defined(USE_ESC_SENSOR)
3559 osdLayoutsConfig->item_pos[0][OSD_ESC_RPM] = OSD_POS(1, 2);
3560 osdLayoutsConfig->item_pos[0][OSD_ESC_TEMPERATURE] = OSD_POS(1, 3);
3561 #endif
3563 #if defined(USE_RX_MSP) && defined(USE_MSP_RC_OVERRIDE)
3564 osdLayoutsConfig->item_pos[0][OSD_RC_SOURCE] = OSD_POS(3, 4);
3565 #endif
3567 #ifdef USE_POWER_LIMITS
3568 osdLayoutsConfig->item_pos[0][OSD_PLIMIT_REMAINING_BURST_TIME] = OSD_POS(3, 4);
3569 osdLayoutsConfig->item_pos[0][OSD_PLIMIT_ACTIVE_CURRENT_LIMIT] = OSD_POS(3, 5);
3570 osdLayoutsConfig->item_pos[0][OSD_PLIMIT_ACTIVE_POWER_LIMIT] = OSD_POS(3, 6);
3571 #endif
3573 // Under OSD_FLYMODE. TODO: Might not be visible on NTSC?
3574 osdLayoutsConfig->item_pos[0][OSD_MESSAGES] = OSD_POS(1, 13) | OSD_VISIBLE_FLAG;
3576 for (unsigned ii = 1; ii < OSD_LAYOUT_COUNT; ii++) {
3577 for (unsigned jj = 0; jj < ARRAYLEN(osdLayoutsConfig->item_pos[0]); jj++) {
3578 osdLayoutsConfig->item_pos[ii][jj] = osdLayoutsConfig->item_pos[0][jj] & ~OSD_VISIBLE_FLAG;
3583 static void osdSetNextRefreshIn(uint32_t timeMs) {
3584 resumeRefreshAt = micros() + timeMs * 1000;
3585 refreshWaitForResumeCmdRelease = true;
3588 static void osdCompleteAsyncInitialization(void)
3590 if (!displayIsReady(osdDisplayPort)) {
3591 // Update the display.
3592 // XXX: Rename displayDrawScreen() and associated functions
3593 // to displayUpdate()
3594 displayDrawScreen(osdDisplayPort);
3595 return;
3598 osdDisplayIsReady = true;
3600 #if defined(USE_CANVAS)
3601 if (osdConfig()->force_grid) {
3602 osdDisplayHasCanvas = false;
3603 } else {
3604 osdDisplayHasCanvas = displayGetCanvas(&osdCanvas, osdDisplayPort);
3606 #endif
3608 displayBeginTransaction(osdDisplayPort, DISPLAY_TRANSACTION_OPT_RESET_DRAWING);
3609 displayClearScreen(osdDisplayPort);
3611 uint8_t y = 1;
3612 displayFontMetadata_t metadata;
3613 bool fontHasMetadata = displayGetFontMetadata(&metadata, osdDisplayPort);
3614 LOG_DEBUG(OSD, "Font metadata version %s: %u (%u chars)",
3615 fontHasMetadata ? "Y" : "N", metadata.version, metadata.charCount);
3617 if (fontHasMetadata && metadata.charCount > 256) {
3618 hasExtendedFont = true;
3619 unsigned logo_c = SYM_LOGO_START;
3620 unsigned logo_x = OSD_CENTER_LEN(SYM_LOGO_WIDTH);
3621 for (unsigned ii = 0; ii < SYM_LOGO_HEIGHT; ii++) {
3622 for (unsigned jj = 0; jj < SYM_LOGO_WIDTH; jj++) {
3623 displayWriteChar(osdDisplayPort, logo_x + jj, y, logo_c++);
3625 y++;
3627 y++;
3628 } else if (!fontHasMetadata) {
3629 const char *m = "INVALID FONT";
3630 displayWrite(osdDisplayPort, OSD_CENTER_S(m), 3, m);
3631 y = 4;
3634 if (fontHasMetadata && metadata.version < OSD_MIN_FONT_VERSION) {
3635 const char *m = "INVALID FONT VERSION";
3636 displayWrite(osdDisplayPort, OSD_CENTER_S(m), y++, m);
3639 char string_buffer[30];
3640 tfp_sprintf(string_buffer, "INAV VERSION: %s", FC_VERSION_STRING);
3641 uint8_t xPos = osdDisplayIsHD() ? 15 : 5;
3642 displayWrite(osdDisplayPort, xPos, y++, string_buffer);
3643 #ifdef USE_CMS
3644 displayWrite(osdDisplayPort, xPos+2, y++, CMS_STARTUP_HELP_TEXT1);
3645 displayWrite(osdDisplayPort, xPos+6, y++, CMS_STARTUP_HELP_TEXT2);
3646 displayWrite(osdDisplayPort, xPos+6, y++, CMS_STARTUP_HELP_TEXT3);
3647 #endif
3648 #ifdef USE_STATS
3651 uint8_t statNameX = osdDisplayIsHD() ? 14 : 4;
3652 uint8_t statValueX = osdDisplayIsHD() ? 34 : 24;
3654 if (statsConfig()->stats_enabled) {
3655 displayWrite(osdDisplayPort, statNameX, ++y, "ODOMETER:");
3656 switch (osdConfig()->units) {
3657 case OSD_UNIT_UK:
3658 FALLTHROUGH;
3659 case OSD_UNIT_IMPERIAL:
3660 tfp_sprintf(string_buffer, "%5d", (int)(statsConfig()->stats_total_dist / METERS_PER_MILE));
3661 string_buffer[5] = SYM_MI;
3662 break;
3663 default:
3664 case OSD_UNIT_GA:
3665 tfp_sprintf(string_buffer, "%5d", (int)(statsConfig()->stats_total_dist / METERS_PER_NAUTICALMILE));
3666 string_buffer[5] = SYM_NM;
3667 break;
3668 case OSD_UNIT_METRIC_MPH:
3669 FALLTHROUGH;
3670 case OSD_UNIT_METRIC:
3671 tfp_sprintf(string_buffer, "%5d", (int)(statsConfig()->stats_total_dist / METERS_PER_KILOMETER));
3672 string_buffer[5] = SYM_KM;
3673 break;
3675 string_buffer[6] = '\0';
3676 displayWrite(osdDisplayPort, statValueX-5, y, string_buffer);
3678 displayWrite(osdDisplayPort, statNameX, ++y, "TOTAL TIME:");
3679 uint32_t tot_mins = statsConfig()->stats_total_time / 60;
3680 tfp_sprintf(string_buffer, "%2d:%02dHM", (int)(tot_mins / 60), (int)(tot_mins % 60));
3681 displayWrite(osdDisplayPort, statValueX-5, y, string_buffer);
3683 #ifdef USE_ADC
3684 if (feature(FEATURE_VBAT) && feature(FEATURE_CURRENT_METER)) {
3685 displayWrite(osdDisplayPort, statNameX, ++y, "TOTAL ENERGY:");
3686 osdFormatCentiNumber(string_buffer, statsConfig()->stats_total_energy / 10, 0, 2, 0, 4);
3687 strcat(string_buffer, "\xAB"); // SYM_WH
3688 displayWrite(osdDisplayPort, statValueX-4, y, string_buffer);
3690 displayWrite(osdDisplayPort, statNameX, ++y, "AVG EFFICIENCY:");
3691 if (statsConfig()->stats_total_dist) {
3692 uint32_t avg_efficiency = statsConfig()->stats_total_energy / (statsConfig()->stats_total_dist / METERS_PER_KILOMETER); // mWh/km
3693 switch (osdConfig()->units) {
3694 case OSD_UNIT_UK:
3695 FALLTHROUGH;
3696 case OSD_UNIT_IMPERIAL:
3697 osdFormatCentiNumber(string_buffer, avg_efficiency / 10, 0, 2, 0, 3);
3698 string_buffer[3] = SYM_WH_MI;
3699 break;
3700 case OSD_UNIT_GA:
3701 osdFormatCentiNumber(string_buffer, avg_efficiency / 10, 0, 2, 0, 3);
3702 string_buffer[3] = SYM_WH_NM;
3703 break;
3704 default:
3705 case OSD_UNIT_METRIC_MPH:
3706 FALLTHROUGH;
3707 case OSD_UNIT_METRIC:
3708 osdFormatCentiNumber(string_buffer, avg_efficiency / 10000 * METERS_PER_MILE, 0, 2, 0, 3);
3709 string_buffer[3] = SYM_WH_KM;
3710 break;
3712 } else {
3713 string_buffer[0] = string_buffer[1] = string_buffer[2] = '-';
3715 string_buffer[4] = '\0';
3716 displayWrite(osdDisplayPort, statValueX-3, y, string_buffer);
3718 #endif // USE_ADC
3720 #endif
3722 displayCommitTransaction(osdDisplayPort);
3723 displayResync(osdDisplayPort);
3724 osdSetNextRefreshIn(SPLASH_SCREEN_DISPLAY_TIME);
3727 void osdInit(displayPort_t *osdDisplayPortToUse)
3729 if (!osdDisplayPortToUse)
3730 return;
3732 BUILD_BUG_ON(OSD_POS_MAX != OSD_POS(63,63));
3734 osdDisplayPort = osdDisplayPortToUse;
3736 #ifdef USE_CMS
3737 cmsDisplayPortRegister(osdDisplayPort);
3738 #endif
3740 armState = ARMING_FLAG(ARMED);
3741 osdCompleteAsyncInitialization();
3744 static void osdResetStats(void)
3746 stats.max_current = 0;
3747 stats.max_power = 0;
3748 stats.max_speed = 0;
3749 stats.max_3D_speed = 0;
3750 stats.max_air_speed = 0;
3751 stats.min_voltage = 5000;
3752 stats.min_rssi = 99;
3753 stats.min_lq = 300;
3754 stats.min_rssi_dbm = 0;
3755 stats.max_altitude = 0;
3758 static void osdUpdateStats(void)
3760 int32_t value;
3762 if (feature(FEATURE_GPS)) {
3763 value = osdGet3DSpeed();
3764 const float airspeed_estimate = getAirspeedEstimate();
3766 if (stats.max_3D_speed < value)
3767 stats.max_3D_speed = value;
3769 if (stats.max_speed < gpsSol.groundSpeed)
3770 stats.max_speed = gpsSol.groundSpeed;
3772 if (stats.max_air_speed < airspeed_estimate)
3773 stats.max_air_speed = airspeed_estimate;
3775 if (stats.max_distance < GPS_distanceToHome)
3776 stats.max_distance = GPS_distanceToHome;
3779 value = getBatteryVoltage();
3780 if (stats.min_voltage > value)
3781 stats.min_voltage = value;
3783 value = abs(getAmperage());
3784 if (stats.max_current < value)
3785 stats.max_current = value;
3787 value = labs(getPower());
3788 if (stats.max_power < value)
3789 stats.max_power = value;
3791 value = osdConvertRSSI();
3792 if (stats.min_rssi > value)
3793 stats.min_rssi = value;
3795 value = osdGetCrsfLQ();
3796 if (stats.min_lq > value)
3797 stats.min_lq = value;
3799 if (!failsafeIsReceivingRxData())
3800 stats.min_lq = 0;
3802 value = osdGetCrsfdBm();
3803 if (stats.min_rssi_dbm > value)
3804 stats.min_rssi_dbm = value;
3806 stats.max_altitude = MAX(stats.max_altitude, osdGetAltitude());
3809 static void osdShowStatsPage1(void)
3811 const char * disarmReasonStr[DISARM_REASON_COUNT] = { "UNKNOWN", "TIMEOUT", "STICKS", "SWITCH", "SWITCH", "KILLSW", "FAILSAFE", "NAV SYS", "LANDING"};
3812 uint8_t top = 1; /* first fully visible line */
3813 const uint8_t statNameX = osdDisplayIsHD() ? 11 : 1;
3814 const uint8_t statValuesX = osdDisplayIsHD() ? 30 : 20;
3815 char buff[10];
3816 statsPagesCheck = 1;
3818 displayBeginTransaction(osdDisplayPort, DISPLAY_TRANSACTION_OPT_RESET_DRAWING);
3819 displayClearScreen(osdDisplayPort);
3821 displayWrite(osdDisplayPort, statNameX, top++, "--- STATS --- 1/2 ->");
3823 if (feature(FEATURE_GPS)) {
3824 displayWrite(osdDisplayPort, statNameX, top, "MAX SPEED :");
3825 osdFormatVelocityStr(buff, stats.max_3D_speed, true, false);
3826 osdLeftAlignString(buff);
3827 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3829 displayWrite(osdDisplayPort, statNameX, top, "AVG SPEED :");
3830 osdGenerateAverageVelocityStr(buff);
3831 osdLeftAlignString(buff);
3832 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3834 displayWrite(osdDisplayPort, statNameX, top, "MAX DISTANCE :");
3835 osdFormatDistanceStr(buff, stats.max_distance*100);
3836 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3838 displayWrite(osdDisplayPort, statNameX, top, "TRAVELED DISTANCE:");
3839 osdFormatDistanceStr(buff, getTotalTravelDistance());
3840 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3843 displayWrite(osdDisplayPort, statNameX, top, "MAX ALTITUDE :");
3844 osdFormatAltitudeStr(buff, stats.max_altitude);
3845 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3847 switch (rxConfig()->serialrx_provider) {
3848 case SERIALRX_CRSF:
3849 displayWrite(osdDisplayPort, statNameX, top, "MIN RSSI % :");
3850 itoa(stats.min_rssi, buff, 10);
3851 strcat(buff, "%");
3852 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3854 displayWrite(osdDisplayPort, statNameX, top, "MIN RSSI DBM :");
3855 itoa(stats.min_rssi_dbm, buff, 10);
3856 tfp_sprintf(buff, "%s%c", buff, SYM_DBM);
3857 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3859 displayWrite(osdDisplayPort, statNameX, top, "MIN LQ :");
3860 itoa(stats.min_lq, buff, 10);
3861 strcat(buff, "%");
3862 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3863 break;
3864 default:
3865 displayWrite(osdDisplayPort, statNameX, top, "MIN RSSI :");
3866 itoa(stats.min_rssi, buff, 10);
3867 strcat(buff, "%");
3868 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3871 displayWrite(osdDisplayPort, statNameX, top, "FLY TIME :");
3872 uint16_t flySeconds = getFlightTime();
3873 uint16_t flyMinutes = flySeconds / 60;
3874 flySeconds %= 60;
3875 uint16_t flyHours = flyMinutes / 60;
3876 flyMinutes %= 60;
3877 tfp_sprintf(buff, "%02u:%02u:%02u", flyHours, flyMinutes, flySeconds);
3878 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3880 displayWrite(osdDisplayPort, statNameX, top, "DISARMED BY :");
3881 displayWrite(osdDisplayPort, statValuesX, top++, disarmReasonStr[getDisarmReason()]);
3882 displayCommitTransaction(osdDisplayPort);
3885 static void osdShowStatsPage2(void)
3887 uint8_t top = 1; /* first fully visible line */
3888 const uint8_t statNameX = osdDisplayIsHD() ? 11 : 1;
3889 const uint8_t statValuesX = osdDisplayIsHD() ? 30 : 20;
3890 char buff[10];
3891 statsPagesCheck = 1;
3893 displayBeginTransaction(osdDisplayPort, DISPLAY_TRANSACTION_OPT_RESET_DRAWING);
3894 displayClearScreen(osdDisplayPort);
3896 displayWrite(osdDisplayPort, statNameX, top++, "--- STATS --- <- 2/2");
3898 if (osdConfig()->stats_min_voltage_unit == OSD_STATS_MIN_VOLTAGE_UNIT_BATTERY) {
3899 displayWrite(osdDisplayPort, statNameX, top, "MIN BATTERY VOLT :");
3900 osdFormatCentiNumber(buff, stats.min_voltage, 0, osdConfig()->main_voltage_decimals, 0, osdConfig()->main_voltage_decimals + 2);
3901 } else {
3902 displayWrite(osdDisplayPort, statNameX, top, "MIN CELL VOLTAGE :");
3903 osdFormatCentiNumber(buff, stats.min_voltage/getBatteryCellCount(), 0, 2, 0, 3);
3905 tfp_sprintf(buff, "%s%c", buff, SYM_VOLT);
3906 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3908 if (feature(FEATURE_CURRENT_METER)) {
3909 displayWrite(osdDisplayPort, statNameX, top, "MAX CURRENT :");
3910 osdFormatCentiNumber(buff, stats.max_current, 0, 2, 0, 3);
3911 tfp_sprintf(buff, "%s%c", buff, SYM_AMP);
3912 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3914 displayWrite(osdDisplayPort, statNameX, top, "MAX POWER :");
3915 bool kiloWatt = osdFormatCentiNumber(buff, stats.max_power, 1000, 2, 2, 3);
3916 buff[3] = kiloWatt ? SYM_KILOWATT : SYM_WATT;
3917 buff[4] = '\0';
3918 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3920 displayWrite(osdDisplayPort, statNameX, top, "USED CAPACITY :");
3921 if (osdConfig()->stats_energy_unit == OSD_STATS_ENERGY_UNIT_MAH) {
3922 tfp_sprintf(buff, "%d%c", (int)getMAhDrawn(), SYM_MAH);
3923 } else {
3924 osdFormatCentiNumber(buff, getMWhDrawn() / 10, 0, 2, 0, 3);
3925 tfp_sprintf(buff, "%s%c", buff, SYM_WH);
3927 displayWrite(osdDisplayPort, statValuesX, top++, buff);
3929 int32_t totalDistance = getTotalTravelDistance();
3930 bool moreThanAh = false;
3931 bool efficiencyValid = totalDistance >= 10000;
3932 if (feature(FEATURE_GPS)) {
3933 displayWrite(osdDisplayPort, statNameX, top, "AVG EFFICIENCY :");
3934 switch (osdConfig()->units) {
3935 case OSD_UNIT_UK:
3936 FALLTHROUGH;
3937 case OSD_UNIT_IMPERIAL:
3938 if (osdConfig()->stats_energy_unit == OSD_STATS_ENERGY_UNIT_MAH) {
3939 moreThanAh = osdFormatCentiNumber(buff, (int32_t)(getMAhDrawn() * 10000.0f * METERS_PER_MILE / totalDistance), 1000, 0, 2, 3);
3940 if (!moreThanAh) {
3941 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_MI_0, SYM_MAH_MI_1);
3942 } else {
3943 tfp_sprintf(buff, "%s%c", buff, SYM_AH_MI);
3945 if (!efficiencyValid) {
3946 buff[0] = buff[1] = buff[2] = '-';
3947 buff[3] = SYM_MAH_MI_0;
3948 buff[4] = SYM_MAH_MI_1;
3949 buff[5] = '\0';
3951 } else {
3952 osdFormatCentiNumber(buff, (int32_t)(getMWhDrawn() * 10.0f * METERS_PER_MILE / totalDistance), 0, 2, 0, 3);
3953 tfp_sprintf(buff, "%s%c", buff, SYM_WH_MI);
3954 if (!efficiencyValid) {
3955 buff[0] = buff[1] = buff[2] = '-';
3958 break;
3959 case OSD_UNIT_GA:
3960 if (osdConfig()->stats_energy_unit == OSD_STATS_ENERGY_UNIT_MAH) {
3961 moreThanAh = osdFormatCentiNumber(buff, (int32_t)(getMAhDrawn() * 10000.0f * METERS_PER_NAUTICALMILE / totalDistance), 1000, 0, 2, 3);
3962 if (!moreThanAh) {
3963 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_NM_0, SYM_MAH_NM_1);
3964 } else {
3965 tfp_sprintf(buff, "%s%c", buff, SYM_AH_NM);
3967 if (!efficiencyValid) {
3968 buff[0] = buff[1] = buff[2] = '-';
3969 buff[3] = SYM_MAH_NM_0;
3970 buff[4] = SYM_MAH_NM_1;
3971 buff[5] = '\0';
3973 } else {
3974 osdFormatCentiNumber(buff, (int32_t)(getMWhDrawn() * 10.0f * METERS_PER_NAUTICALMILE / totalDistance), 0, 2, 0, 3);
3975 tfp_sprintf(buff, "%s%c", buff, SYM_WH_NM);
3976 if (!efficiencyValid) {
3977 buff[0] = buff[1] = buff[2] = '-';
3980 break;
3981 case OSD_UNIT_METRIC_MPH:
3982 FALLTHROUGH;
3983 case OSD_UNIT_METRIC:
3984 if (osdConfig()->stats_energy_unit == OSD_STATS_ENERGY_UNIT_MAH) {
3985 moreThanAh = osdFormatCentiNumber(buff, (int32_t)(getMAhDrawn() * 10000000.0f / totalDistance), 1000, 0, 2, 3);
3986 if (!moreThanAh) {
3987 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_KM_0, SYM_MAH_KM_1);
3988 } else {
3989 tfp_sprintf(buff, "%s%c", buff, SYM_AH_KM);
3991 if (!efficiencyValid) {
3992 buff[0] = buff[1] = buff[2] = '-';
3993 buff[3] = SYM_MAH_KM_0;
3994 buff[4] = SYM_MAH_KM_1;
3995 buff[5] = '\0';
3997 } else {
3998 osdFormatCentiNumber(buff, (int32_t)(getMWhDrawn() * 10000.0f / totalDistance), 0, 2, 0, 3);
3999 tfp_sprintf(buff, "%s%c", buff, SYM_WH_KM);
4000 if (!efficiencyValid) {
4001 buff[0] = buff[1] = buff[2] = '-';
4004 break;
4006 osdLeftAlignString(buff);
4007 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4011 const float max_gforce = accGetMeasuredMaxG();
4012 displayWrite(osdDisplayPort, statNameX, top, "MAX G-FORCE :");
4013 osdFormatCentiNumber(buff, max_gforce * 100, 0, 2, 0, 3);
4014 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4016 const acc_extremes_t *acc_extremes = accGetMeasuredExtremes();
4017 displayWrite(osdDisplayPort, statNameX, top, "MIN/MAX Z G-FORCE:");
4018 osdFormatCentiNumber(buff, acc_extremes[Z].min * 100, 0, 2, 0, 4);
4019 strcat(buff,"/");
4020 displayWrite(osdDisplayPort, statValuesX - 1, top, buff);
4021 osdFormatCentiNumber(buff, acc_extremes[Z].max * 100, 0, 2, 0, 3);
4022 displayWrite(osdDisplayPort, statValuesX + 4, top++, buff);
4023 displayCommitTransaction(osdDisplayPort);
4026 // called when motors armed
4027 static void osdShowArmed(void)
4029 dateTime_t dt;
4030 char buf[MAX(32, FORMATTED_DATE_TIME_BUFSIZE)];
4031 char craftNameBuf[MAX_NAME_LENGTH];
4032 char versionBuf[30];
4033 char *date;
4034 char *time;
4035 // We need 12 visible rows, start row never < first fully visible row 1
4036 uint8_t y = osdDisplayPort->rows > 13 ? (osdDisplayPort->rows - 12) / 2 : 1;
4038 displayClearScreen(osdDisplayPort);
4039 strcpy(buf, "ARMED");
4040 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y, buf);
4041 y += 2;
4043 if (strlen(systemConfig()->name) > 0) {
4044 osdFormatCraftName(craftNameBuf);
4045 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(systemConfig() -> name)) / 2, y, craftNameBuf );
4046 y += 1;
4048 if (posControl.waypointListValid && posControl.waypointCount > 0) {
4049 #ifdef USE_MULTI_MISSION
4050 tfp_sprintf(buf, "MISSION %u/%u (%u WP)", posControl.loadedMultiMissionIndex, posControl.multiMissionCount, posControl.waypointCount);
4051 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y, buf);
4052 #else
4053 strcpy(buf, "*MISSION LOADED*");
4054 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y, buf);
4055 #endif
4057 y += 1;
4059 #if defined(USE_GPS)
4060 if (feature(FEATURE_GPS)) {
4061 if (STATE(GPS_FIX_HOME)) {
4062 if (osdConfig()->osd_home_position_arm_screen){
4063 osdFormatCoordinate(buf, SYM_LAT, GPS_home.lat);
4064 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y, buf);
4065 osdFormatCoordinate(buf, SYM_LON, GPS_home.lon);
4066 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y + 1, buf);
4067 int digits = osdConfig()->plus_code_digits;
4068 olc_encode(GPS_home.lat, GPS_home.lon, digits, buf, sizeof(buf));
4069 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y + 2, buf);
4071 y += 4;
4072 #if defined (USE_SAFE_HOME)
4073 if (safehome_distance) { // safehome found during arming
4074 if (navConfig()->general.flags.safehome_usage_mode == SAFEHOME_USAGE_OFF) {
4075 strcpy(buf, "SAFEHOME FOUND; MODE OFF");
4076 } else {
4077 char buf2[12]; // format the distance first
4078 osdFormatDistanceStr(buf2, safehome_distance);
4079 tfp_sprintf(buf, "%c - %s -> SAFEHOME %u", SYM_HOME, buf2, safehome_index);
4081 textAttributes_t elemAttr = _TEXT_ATTRIBUTES_BLINK_BIT;
4082 // write this message above the ARMED message to make it obvious
4083 displayWriteWithAttr(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y - 8, buf, elemAttr);
4085 #endif
4086 } else {
4087 strcpy(buf, "!NO HOME POSITION!");
4088 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y, buf);
4089 y += 1;
4092 #endif
4094 if (rtcGetDateTime(&dt)) {
4095 dateTimeFormatLocal(buf, &dt);
4096 dateTimeSplitFormatted(buf, &date, &time);
4098 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(date)) / 2, y, date);
4099 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(time)) / 2, y + 1, time);
4100 y += 3;
4103 tfp_sprintf(versionBuf, "INAV VERSION: %s", FC_VERSION_STRING);
4104 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(versionBuf)) / 2, y, versionBuf);
4107 static void osdFilterData(timeUs_t currentTimeUs) {
4108 static timeUs_t lastRefresh = 0;
4109 float refresh_dT = US2S(cmpTimeUs(currentTimeUs, lastRefresh));
4111 GForce = fast_fsqrtf(vectorNormSquared(&imuMeasuredAccelBF)) / GRAVITY_MSS;
4112 for (uint8_t axis = 0; axis < XYZ_AXIS_COUNT; ++axis) GForceAxis[axis] = imuMeasuredAccelBF.v[axis] / GRAVITY_MSS;
4114 if (lastRefresh) {
4115 GForce = pt1FilterApply3(&GForceFilter, GForce, refresh_dT);
4116 for (uint8_t axis = 0; axis < XYZ_AXIS_COUNT; ++axis) pt1FilterApply3(GForceFilterAxis + axis, GForceAxis[axis], refresh_dT);
4117 } else {
4118 pt1FilterInitRC(&GForceFilter, GFORCE_FILTER_TC, 0);
4119 pt1FilterReset(&GForceFilter, GForce);
4121 for (uint8_t axis = 0; axis < XYZ_AXIS_COUNT; ++axis) {
4122 pt1FilterInitRC(GForceFilterAxis + axis, GFORCE_FILTER_TC, 0);
4123 pt1FilterReset(GForceFilterAxis + axis, GForceAxis[axis]);
4127 lastRefresh = currentTimeUs;
4130 static void osdRefresh(timeUs_t currentTimeUs)
4132 osdFilterData(currentTimeUs);
4134 #ifdef USE_CMS
4135 if (IS_RC_MODE_ACTIVE(BOXOSD) && (!cmsInMenu) && !(osdConfig()->osd_failsafe_switch_layout && FLIGHT_MODE(FAILSAFE_MODE))) {
4136 #else
4137 if (IS_RC_MODE_ACTIVE(BOXOSD) && !(osdConfig()->osd_failsafe_switch_layout && FLIGHT_MODE(FAILSAFE_MODE))) {
4138 #endif
4139 displayClearScreen(osdDisplayPort);
4140 armState = ARMING_FLAG(ARMED);
4141 return;
4144 // detect arm/disarm
4145 static uint8_t statsPageAutoSwapCntl = 2;
4146 if (armState != ARMING_FLAG(ARMED)) {
4147 if (ARMING_FLAG(ARMED)) {
4148 osdResetStats();
4149 statsPageAutoSwapCntl = 2;
4150 osdShowArmed(); // reset statistic etc
4151 uint32_t delay = ARMED_SCREEN_DISPLAY_TIME;
4152 statsPagesCheck = 0;
4153 #if defined(USE_SAFE_HOME)
4154 if (safehome_distance)
4155 delay *= 3;
4156 #endif
4157 osdSetNextRefreshIn(delay);
4158 } else {
4159 osdShowStatsPage1(); // show first page of statistics
4160 osdSetNextRefreshIn(STATS_SCREEN_DISPLAY_TIME);
4161 statsPageAutoSwapCntl = osdConfig()->stats_page_auto_swap_time > 0 ? 0 : 2; // disable swapping pages when time = 0
4164 armState = ARMING_FLAG(ARMED);
4167 if (resumeRefreshAt) {
4168 // If we already reached he time for the next refresh,
4169 // or THR is high or PITCH is high, resume refreshing.
4170 // Clear the screen first to erase other elements which
4171 // might have been drawn while the OSD wasn't refreshing.
4173 // auto swap stats pages when first shown
4174 // auto swap cancelled using roll stick
4175 if (statsPageAutoSwapCntl != 2) {
4176 if (STATS_PAGE1 || STATS_PAGE2) {
4177 statsPageAutoSwapCntl = 2;
4178 } else {
4179 if (OSD_ALTERNATING_CHOICES((osdConfig()->stats_page_auto_swap_time * 1000), 2)) {
4180 if (statsPageAutoSwapCntl == 0) {
4181 osdShowStatsPage1();
4182 statsPageAutoSwapCntl = 1;
4184 } else {
4185 if (statsPageAutoSwapCntl == 1) {
4186 osdShowStatsPage2();
4187 statsPageAutoSwapCntl = 0;
4193 if (!DELAYED_REFRESH_RESUME_COMMAND)
4194 refreshWaitForResumeCmdRelease = false;
4196 if ((currentTimeUs > resumeRefreshAt) || ((!refreshWaitForResumeCmdRelease) && DELAYED_REFRESH_RESUME_COMMAND)) {
4197 displayClearScreen(osdDisplayPort);
4198 resumeRefreshAt = 0;
4199 } else if ((currentTimeUs > resumeRefreshAt) || ((!refreshWaitForResumeCmdRelease) && STATS_PAGE1)) {
4200 if (statsPagesCheck == 1) {
4201 osdShowStatsPage1();
4203 } else if ((currentTimeUs > resumeRefreshAt) || ((!refreshWaitForResumeCmdRelease) && STATS_PAGE2)) {
4204 if (statsPagesCheck == 1) {
4205 osdShowStatsPage2();
4207 } else {
4208 displayHeartbeat(osdDisplayPort);
4210 return;
4213 #ifdef USE_CMS
4214 if (!displayIsGrabbed(osdDisplayPort)) {
4215 displayBeginTransaction(osdDisplayPort, DISPLAY_TRANSACTION_OPT_RESET_DRAWING);
4216 if (fullRedraw) {
4217 displayClearScreen(osdDisplayPort);
4218 fullRedraw = false;
4220 osdDrawNextElement();
4221 displayHeartbeat(osdDisplayPort);
4222 displayCommitTransaction(osdDisplayPort);
4223 #ifdef OSD_CALLS_CMS
4224 } else {
4225 cmsUpdate(currentTimeUs);
4226 #endif
4228 #endif
4232 * Called periodically by the scheduler
4234 void osdUpdate(timeUs_t currentTimeUs)
4236 static uint32_t counter = 0;
4238 // don't touch buffers if DMA transaction is in progress
4239 if (displayIsTransferInProgress(osdDisplayPort)) {
4240 return;
4243 if (!osdDisplayIsReady) {
4244 osdCompleteAsyncInitialization();
4245 return;
4248 #if defined(OSD_ALTERNATE_LAYOUT_COUNT) && OSD_ALTERNATE_LAYOUT_COUNT > 0
4249 // Check if the layout has changed. Higher numbered
4250 // boxes take priority.
4251 unsigned activeLayout;
4252 if (layoutOverride >= 0) {
4253 activeLayout = layoutOverride;
4254 // Check for timed override, it will go into effect on
4255 // the next OSD iteration
4256 if (layoutOverrideUntil > 0 && millis() > layoutOverrideUntil) {
4257 layoutOverrideUntil = 0;
4258 layoutOverride = -1;
4260 } else if (osdConfig()->osd_failsafe_switch_layout && FLIGHT_MODE(FAILSAFE_MODE)) {
4261 activeLayout = 0;
4262 } else {
4263 #if OSD_ALTERNATE_LAYOUT_COUNT > 2
4264 if (IS_RC_MODE_ACTIVE(BOXOSDALT3))
4265 activeLayout = 3;
4266 else
4267 #endif
4268 #if OSD_ALTERNATE_LAYOUT_COUNT > 1
4269 if (IS_RC_MODE_ACTIVE(BOXOSDALT2))
4270 activeLayout = 2;
4271 else
4272 #endif
4273 if (IS_RC_MODE_ACTIVE(BOXOSDALT1))
4274 activeLayout = 1;
4275 else
4276 #ifdef USE_PROGRAMMING_FRAMEWORK
4277 if (LOGIC_CONDITION_GLOBAL_FLAG(LOGIC_CONDITION_GLOBAL_FLAG_OVERRIDE_OSD_LAYOUT))
4278 activeLayout = constrain(logicConditionValuesByType[LOGIC_CONDITION_SET_OSD_LAYOUT], 0, OSD_ALTERNATE_LAYOUT_COUNT);
4279 else
4280 #endif
4281 activeLayout = 0;
4283 if (currentLayout != activeLayout) {
4284 currentLayout = activeLayout;
4285 osdStartFullRedraw();
4287 #endif
4289 #define DRAW_FREQ_DENOM 4
4290 #define STATS_FREQ_DENOM 50
4291 counter++;
4293 if ((counter % STATS_FREQ_DENOM) == 0) {
4294 osdUpdateStats();
4297 if ((counter % DRAW_FREQ_DENOM) == 0) {
4298 // redraw values in buffer
4299 osdRefresh(currentTimeUs);
4300 } else {
4301 // rest of time redraw screen
4302 displayDrawScreen(osdDisplayPort);
4305 #ifdef USE_CMS
4306 // do not allow ARM if we are in menu
4307 if (displayIsGrabbed(osdDisplayPort)) {
4308 ENABLE_ARMING_FLAG(ARMING_DISABLED_OSD_MENU);
4309 } else {
4310 DISABLE_ARMING_FLAG(ARMING_DISABLED_OSD_MENU);
4312 #endif
4315 void osdStartFullRedraw(void)
4317 fullRedraw = true;
4320 void osdOverrideLayout(int layout, timeMs_t duration)
4322 layoutOverride = constrain(layout, -1, ARRAYLEN(osdLayoutsConfig()->item_pos) - 1);
4323 if (layoutOverride >= 0 && duration > 0) {
4324 layoutOverrideUntil = millis() + duration;
4325 } else {
4326 layoutOverrideUntil = 0;
4330 int osdGetActiveLayout(bool *overridden)
4332 if (overridden) {
4333 *overridden = layoutOverride >= 0;
4335 return currentLayout;
4338 bool osdItemIsFixed(osd_items_e item)
4340 return item == OSD_CROSSHAIRS ||
4341 item == OSD_ARTIFICIAL_HORIZON ||
4342 item == OSD_HORIZON_SIDEBARS;
4345 displayPort_t *osdGetDisplayPort(void)
4347 return osdDisplayPort;
4350 displayCanvas_t *osdGetDisplayPortCanvas(void)
4352 #if defined(USE_CANVAS)
4353 if (osdDisplayHasCanvas) {
4354 return &osdCanvas;
4356 #endif
4357 return NULL;
4360 timeMs_t systemMessageCycleTime(unsigned messageCount, const char **messages){
4361 uint8_t i = 0;
4362 float factor = 1.0f;
4363 while (i < messageCount) {
4364 if ((float)strlen(messages[i]) / 15.0f > factor) {
4365 factor = (float)strlen(messages[i]) / 15.0f;
4367 i++;
4369 return osdConfig()->system_msg_display_time * factor;
4372 textAttributes_t osdGetSystemMessage(char *buff, size_t buff_size, bool isCenteredText)
4374 textAttributes_t elemAttr = TEXT_ATTRIBUTES_NONE;
4376 if (buff != NULL) {
4377 const char *message = NULL;
4378 char messageBuf[MAX(SETTING_MAX_NAME_LENGTH, OSD_MESSAGE_LENGTH+1)];
4379 // We might have up to 5 messages to show.
4380 const char *messages[5];
4381 unsigned messageCount = 0;
4382 const char *failsafeInfoMessage = NULL;
4383 const char *invertedInfoMessage = NULL;
4385 if (ARMING_FLAG(ARMED)) {
4386 if (FLIGHT_MODE(FAILSAFE_MODE) || FLIGHT_MODE(NAV_RTH_MODE) || FLIGHT_MODE(NAV_WP_MODE) || navigationIsExecutingAnEmergencyLanding()) {
4387 if (isWaypointMissionRTHActive()) {
4388 // if RTH activated whilst WP mode selected, remind pilot to cancel WP mode to exit RTH
4389 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_WP_RTH_CANCEL);
4391 if (navGetCurrentStateFlags() & NAV_AUTO_WP_DONE) {
4392 messages[messageCount++] = STATE(LANDING_DETECTED) ? OSD_MESSAGE_STR(OSD_MSG_WP_LANDED) : OSD_MESSAGE_STR(OSD_MSG_WP_FINISHED);
4393 } else if (NAV_Status.state == MW_NAV_STATE_WP_ENROUTE) {
4394 // Countdown display for remaining Waypoints
4395 char buf[6];
4396 osdFormatDistanceSymbol(buf, posControl.wpDistance, 0);
4397 tfp_sprintf(messageBuf, "TO WP %u/%u (%s)", getGeoWaypointNumber(posControl.activeWaypointIndex), posControl.geoWaypointCount, buf);
4398 messages[messageCount++] = messageBuf;
4399 } else if (NAV_Status.state == MW_NAV_STATE_HOLD_TIMED) {
4400 if (navConfig()->general.waypoint_enforce_altitude && !posControl.wpAltitudeReached) {
4401 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_ADJUSTING_WP_ALT);
4402 } else {
4403 // WP hold time countdown in seconds
4404 timeMs_t currentTime = millis();
4405 int holdTimeRemaining = posControl.waypointList[posControl.activeWaypointIndex].p1 - (int)(MS2S(currentTime - posControl.wpReachedTime));
4406 holdTimeRemaining = holdTimeRemaining >= 0 ? holdTimeRemaining : 0;
4408 tfp_sprintf(messageBuf, "HOLDING WP FOR %2u S", holdTimeRemaining);
4410 messages[messageCount++] = messageBuf;
4412 } else {
4413 const char *navStateMessage = navigationStateMessage();
4414 if (navStateMessage) {
4415 messages[messageCount++] = navStateMessage;
4418 #if defined(USE_SAFE_HOME)
4419 const char *safehomeMessage = divertingToSafehomeMessage();
4420 if (safehomeMessage) {
4421 messages[messageCount++] = safehomeMessage;
4423 #endif
4424 if (FLIGHT_MODE(FAILSAFE_MODE)) {
4425 // In FS mode while being armed too
4426 const char *failsafePhaseMessage = osdFailsafePhaseMessage();
4427 failsafeInfoMessage = osdFailsafeInfoMessage();
4429 if (failsafePhaseMessage) {
4430 messages[messageCount++] = failsafePhaseMessage;
4432 if (failsafeInfoMessage) {
4433 messages[messageCount++] = failsafeInfoMessage;
4436 } else { /* messages shown only when Failsafe, WP, RTH or Emergency Landing not active */
4437 if (STATE(FIXED_WING_LEGACY) && (navGetCurrentStateFlags() & NAV_CTL_LAUNCH)) {
4438 messages[messageCount++] = navConfig()->fw.launch_manual_throttle ? OSD_MESSAGE_STR(OSD_MSG_AUTOLAUNCH_MANUAL) :
4439 OSD_MESSAGE_STR(OSD_MSG_AUTOLAUNCH);
4440 const char *launchStateMessage = fixedWingLaunchStateMessage();
4441 if (launchStateMessage) {
4442 messages[messageCount++] = launchStateMessage;
4444 } else {
4445 if (FLIGHT_MODE(NAV_ALTHOLD_MODE) && !navigationRequiresAngleMode()) {
4446 // ALTHOLD might be enabled alongside ANGLE/HORIZON/ACRO
4447 // when it doesn't require ANGLE mode (required only in FW
4448 // right now). If if requires ANGLE, its display is handled
4449 // by OSD_FLYMODE.
4450 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_ALTITUDE_HOLD);
4452 if (IS_RC_MODE_ACTIVE(BOXAUTOTRIM) && !feature(FEATURE_FW_AUTOTRIM)) {
4453 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_AUTOTRIM);
4455 if (IS_RC_MODE_ACTIVE(BOXAUTOTUNE)) {
4456 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_AUTOTUNE);
4457 if (FLIGHT_MODE(MANUAL_MODE)) {
4458 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_AUTOTUNE_ACRO);
4461 if (FLIGHT_MODE(HEADFREE_MODE)) {
4462 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_HEADFREE);
4464 if (FLIGHT_MODE(SOARING_MODE)) {
4465 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_NAV_SOARING);
4467 if (posControl.flags.wpMissionPlannerActive) {
4468 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_MISSION_PLANNER);
4470 if (STATE(LANDING_DETECTED)) {
4471 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_LANDED);
4475 } else if (ARMING_FLAG(ARMING_DISABLED_ALL_FLAGS)) {
4476 unsigned invalidIndex;
4478 // Check if we're unable to arm for some reason
4479 if (ARMING_FLAG(ARMING_DISABLED_INVALID_SETTING) && !settingsValidate(&invalidIndex)) {
4481 const setting_t *setting = settingGet(invalidIndex);
4482 settingGetName(setting, messageBuf);
4483 for (int ii = 0; messageBuf[ii]; ii++) {
4484 messageBuf[ii] = sl_toupper(messageBuf[ii]);
4486 invertedInfoMessage = messageBuf;
4487 messages[messageCount++] = invertedInfoMessage;
4489 invertedInfoMessage = OSD_MESSAGE_STR(OSD_MSG_INVALID_SETTING);
4490 messages[messageCount++] = invertedInfoMessage;
4492 } else {
4494 invertedInfoMessage = OSD_MESSAGE_STR(OSD_MSG_UNABLE_ARM);
4495 messages[messageCount++] = invertedInfoMessage;
4497 // Show the reason for not arming
4498 messages[messageCount++] = osdArmingDisabledReasonMessage();
4501 } else if (!ARMING_FLAG(ARMED)) {
4502 if (isWaypointListValid()) {
4503 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_WP_MISSION_LOADED);
4507 /* Messages that are shown regardless of Arming state */
4509 #ifdef USE_DEV_TOOLS
4510 if (systemConfig()->groundTestMode) {
4511 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_GRD_TEST_MODE);
4513 #endif
4515 if (messageCount > 0) {
4516 message = messages[OSD_ALTERNATING_CHOICES(systemMessageCycleTime(messageCount, messages), messageCount)];
4517 if (message == failsafeInfoMessage) {
4518 // failsafeInfoMessage is not useful for recovering
4519 // a lost model, but might help avoiding a crash.
4520 // Blink to grab user attention.
4521 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
4522 } else if (message == invertedInfoMessage) {
4523 TEXT_ATTRIBUTES_ADD_INVERTED(elemAttr);
4525 // We're shoing either failsafePhaseMessage or
4526 // navStateMessage. Don't BLINK here since
4527 // having this text available might be crucial
4528 // during a lost aircraft recovery and blinking
4529 // will cause it to be missing from some frames.
4532 osdFormatMessage(buff, buff_size, message, isCenteredText);
4534 return elemAttr;
4537 #endif // OSD