2 * This file is part of INAV Project.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
6 * You can obtain one at http://mozilla.org/MPL/2.0/.
8 * Alternatively, the contents of this file may be used under the terms
9 * of the GNU General Public License Version 3, as described below:
11 * This file is free software: you may copy, redistribute and/or modify
12 * it under the terms of the GNU General Public License as published by the
13 * Free Software Foundation, either version 3 of the License, or (at your
14 * option) any later version.
16 * This file is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
19 * Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see http://www.gnu.org/licenses/.
30 #include "io/serial.h"
31 #include "drivers/time.h"
33 #if defined(USE_RANGEFINDER_USD1_V0)
34 #include "drivers/rangefinder/rangefinder_virtual.h"
36 #define USD1_HDR_V0 72 // Header Byte for beta V0 of USD1_Serial (0x48)
38 #define USD1_PACKET_SIZE 3
39 #define USD1_KEEP_DATA_TIMEOUT 2000 // 2s
42 static serialPort_t
* serialPort
= NULL
;
43 static serialPortConfig_t
* portConfig
;
45 static bool hasNewData
= false;
46 static bool hasEverData
= false;
47 static uint8_t lineBuf
[USD1_PACKET_SIZE
];
48 static int32_t sensorData
= RANGEFINDER_NO_NEW_DATA
;
49 static timeMs_t lastProtocolActivityMs
;
51 static bool usd1RangefinderDetect(void)
53 portConfig
= findSerialPortConfig(FUNCTION_RANGEFINDER
);
61 static void usd1RangefinderInit(void)
67 serialPort
= openSerialPort(portConfig
->identifier
, FUNCTION_RANGEFINDER
, NULL
, NULL
, 115200, MODE_RXTX
, SERIAL_NOT_INVERTED
);
72 lastProtocolActivityMs
= 0;
75 static void usd1RangefinderUpdate(void)
81 while (serialRxBytesWaiting(serialPort
) > 0) {
82 uint8_t c
= serialRead(serialPort
);
84 if (c
== USD1_HDR_V0
&& index
== 0) {
95 sum
+= (float)((lineBuf
[2]&0x7F) * 128 + (lineBuf
[1]&0x7F));
107 lastProtocolActivityMs
= millis();
108 sensorData
= (int32_t)(2.5f
* sum
/ (float)count
);
111 static int32_t usd1RangefinderGetDistance(void)
113 int32_t altitude
= (sensorData
> 0) ? (sensorData
) : RANGEFINDER_OUT_OF_RANGE
;
120 //keep last value for timeout, because radar sends data only if change
121 if ((millis() - lastProtocolActivityMs
) < USD1_KEEP_DATA_TIMEOUT
) {
125 return hasEverData
? RANGEFINDER_OUT_OF_RANGE
: RANGEFINDER_NO_NEW_DATA
;
129 virtualRangefinderVTable_t rangefinderUSD1Vtable
= {
130 .detect
= usd1RangefinderDetect
,
131 .init
= usd1RangefinderInit
,
132 .update
= usd1RangefinderUpdate
,
133 .read
= usd1RangefinderGetDistance