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 #define TASK_STAK_SIZE    (1024*10)
28 #define GPIO_8 8
29 #define GPIO_7 7
30 #define GPIO_FUNC 0
GetDistance(void)31 float GetDistance  (void)
32 {
33     static unsigned long start_time = 0, time = 0;
34     float distance = 0.0;
35     IotGpioValue value = IOT_GPIO_VALUE0;
36     unsigned int flag = 0;
37     float pi = 0.034;
38     int l = 2;
39     unsigned int delayTime = 20;
40     IoTWatchDogDisable();
41 
42     hi_io_set_func(GPIO_8, GPIO_FUNC);
43     IoTGpioSetDir(GPIO_8, IOT_GPIO_DIR_IN);
44 
45     IoTGpioSetDir(GPIO_7, IOT_GPIO_DIR_OUT);
46     IoTGpioSetOutputVal(GPIO_7, IOT_GPIO_VALUE1);
47     hi_udelay(delayTime);
48     IoTGpioSetOutputVal(GPIO_7, IOT_GPIO_VALUE0);
49 
50     while (1) {
51         IoTGpioGetInputVal(GPIO_8, &value);
52         if (value == IOT_GPIO_VALUE1 && flag == 0) {
53             start_time = hi_get_us();
54             flag = 1;
55         }
56         if (value == IOT_GPIO_VALUE0 && flag == 1) {
57             time = hi_get_us() - start_time;
58             start_time = 0;
59             break;
60         }
61     }
62     distance = time * pi / l;
63     return distance;
64 }
65 
RobotTask(void* parame)66 void RobotTask(void* parame)
67 {
68     (void)parame;
69     printf("start test hcsr04\r\n");
70     unsigned int time = 200;
71     while (1) {
72         float distance = GetDistance();
73         printf("distance is %f\r\n", distance);
74         osDelay(time);
75     }
76 }
77 
78 
RobotDemo(void)79 static void RobotDemo(void)
80 {
81     osThreadAttr_t attr;
82 
83     attr.name = "RobotTask";
84     attr.attr_bits = 0U;
85     attr.cb_mem = NULL;
86     attr.cb_size = 0U;
87     attr.stack_mem = NULL;
88     attr.stack_size = TASK_STAK_SIZE;
89     attr.priority = osPriorityNormal;
90 
91     if (osThreadNew(RobotTask, NULL, &attr) == NULL) {
92         printf("[RobotDemo] Failed to create RobotTask!\n");
93     }
94 }
95 
96 APP_FEATURE_INIT(RobotDemo);
97