• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2020 Nanjing Xiaoxiongpai Intelligent Technology Co., Ltd.
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  * limitations under the License.
14  */
15 
16 #include <math.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <unistd.h>
20 
21 #include "cmsis_os2.h"
22 #include "iot_adc.h"
23 #include "iot_errno.h"
24 #include "iot_gpio_ex.h"
25 #include "ohos_init.h"
26 
27 #define ADC_TASK_STACK_SIZE (1024 * 8)
28 #define ADC_TASK_PRIO 24
29 #define ADC_GPIO 11
30 #define ADC_CHANNEL 5
31 #define ADC_TASK_DELAY_1S 1000000
32 
33 #define ADC_VREF_VOL 1.8
34 #define ADC_COEFFICIENT 4
35 #define ADC_RATIO 4096
36 
37 /**
38  * @brief get ADC sampling value and convert it to voltage
39  *
40  */
GetVoltage(void)41 static float GetVoltage(void)
42 {
43     unsigned int ret;
44     unsigned short data;
45 
46     ret = IoTAdcRead(ADC_CHANNEL, &data, IOT_ADC_EQU_MODEL_8, IOT_ADC_CUR_BAIS_DEFAULT, 0xff);
47     if (ret != IOT_SUCCESS) {
48         printf("ADC Read Fail\n");
49     }
50 
51     return (float)data * ADC_VREF_VOL * ADC_COEFFICIENT / ADC_RATIO;
52 }
53 
54 /**
55  * @brief Adc task get adc sampling voltage
56  *
57  */
AdcTask(void)58 static void AdcTask(void)
59 {
60     float voltage;
61 
62     // set GPIO_11 to pull-up mode
63     IoTGpioSetPull(ADC_GPIO, IOT_GPIO_PULL_UP);
64     while (1) {
65         printf("=======================================\r\n");
66         printf("***************ADC_example*************\r\n");
67         printf("=======================================\r\n");
68 
69         // get adc sampling voltage
70         voltage = GetVoltage();
71         printf("vlt:%.3fV\n", voltage);
72 
73         // delay 1s
74         usleep(ADC_TASK_DELAY_1S);
75     }
76 }
77 
78 /**
79  * @brief Main Entry of the Adc Example
80  *
81  */
AdcExampleEntry(void)82 static void AdcExampleEntry(void)
83 {
84     osThreadAttr_t attr;
85 
86     attr.name = "AdcTask";
87     attr.attr_bits = 0U;
88     attr.cb_mem = NULL;
89     attr.cb_size = 0U;
90     attr.stack_mem = NULL;
91     attr.stack_size = ADC_TASK_STACK_SIZE;
92     attr.priority = ADC_TASK_PRIO;
93 
94     if (osThreadNew((osThreadFunc_t)AdcTask, NULL, &attr) == NULL) {
95         printf("Failed to create AdcTask!\n");
96     }
97 }
98 
99 APP_FEATURE_INIT(AdcExampleEntry);