1 /*
2 * Copyright (C) 2022 HiHope Open Source Organization .
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 *
14 * limitations under the License.
15 */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <memory.h>
20
21 #include "ohos_init.h"
22 #include "cmsis_os2.h"
23 #include "iot_gpio.h"
24 #include "hi_io.h"
25 #include "hi_time.h"
26
27
28 #define GPIO_8 8
29 #define GPIO_7 7
30 #define GPIO_FUNC 0
31
GetDistance(void)32 float GetDistance (void)
33 {
34 static unsigned long start_time = 0, time = 0;
35 float distance = 0.0;
36 IotGpioValue value = IOT_GPIO_VALUE0;
37 unsigned int flag = 0;
38 float pi = 0.034;
39 int l = 2;
40 unsigned int delayTime = 20;
41 IoTWatchDogDisable();
42
43 hi_io_set_func(GPIO_8, GPIO_FUNC);
44 IoTGpioSetDir(GPIO_8, IOT_GPIO_DIR_IN);
45
46 IoTGpioSetDir(GPIO_7, IOT_GPIO_DIR_OUT);
47 IoTGpioSetOutputVal(GPIO_7, IOT_GPIO_VALUE1);
48 hi_udelay(delayTime);
49 IoTGpioSetOutputVal(GPIO_7, IOT_GPIO_VALUE0);
50
51 while (1) {
52 IoTGpioGetInputVal(GPIO_8, &value);
53 if (value == IOT_GPIO_VALUE1 && flag == 0) {
54 start_time = hi_get_us();
55 flag = 1;
56 }
57 if (value == IOT_GPIO_VALUE0 && flag == 1) {
58 time = hi_get_us() - start_time;
59 start_time = 0;
60 break;
61 }
62 }
63 distance = time * pi / l;
64 printf("distance is %f\r\n", distance);
65 return distance;
66 }
67