# Hi3861开发板编程光敏电阻控制led灯 参考文章:(https://gitee.com/hihope_iot/hispark-pegasus-sample) 在openharmony源码的applications\sample\wifi-iot\app\iothardware目录下新建adc_demo.c 和 BUILD.gn , 我在openharmony源码的applications\sample\wifi-iot\app目录下新建的文件 ### 1.adc_demo代码 ``` #include #include "ohos_init.h" #include "cmsis_os2.h" #include "wifiiot_gpio.h" #include "wifiiot_gpio_ex.h" #include "wifiiot_adc.h"//定义AdcRead函数 #include "wifiiot_errno.h" //包含 “WIFI_IOT_SUCCESS” #define ADC4 WIFI_IOT_ADC_CHANNEL_4 //GPIO9口是ADC4通道,与ADC4复用,人体红外、红外测距、超声波同理, //ADC的通道有 ADC0 ADC1 ADC2 ADC3 ADC4 ADC5 ADC6 //对应的gpio:gpio12 gpio04 gpio05 gpio07 gpio09 gpio11 gpio13 static void ADCLightTask(void *arg) { (void)arg; GpioInit();//初始化 IoSetFunc(WIFI_IOT_IO_NAME_GPIO_9,WIFI_IOT_IO_FUNC_GPIO_9_GPIO); GpioSetDir(WIFI_IOT_GPIO_IDX_9,WIFI_IOT_GPIO_DIR_OUT);//让gpio9输出电平 while (1) { unsigned short value = 0; if (AdcRead(ADC4, &value, WIFI_IOT_ADC_EQU_MODEL_4, WIFI_IOT_ADC_CUR_BAIS_DEFAULT, 0) == WIFI_IOT_SUCCESS) /*AdcRead函数有5个参数 unsigned int AdcRead(WifiIotAdcChannelIndex channel,//采集通道 unsigned short *data,//ADC值的保存地址 WifiIotAdcEquModelSel equModel,//平均算法模式 WifiIotAdcCurBais curBais,//模拟电源基准模式 unsigned ahort rstCnt)//延时时间,单位334ns,在0-0xff0之间 */ { printf("ADC_VALUE = %d\n", (unsigned int)value);//打印ADC的值。 osDelay(10);//延时 } //光敏传感器控制led灯 if((unsigned int)value > 2100)  GpioSetOutputVal(WIFI_IOT_GPIO_IDX_9,0);//让gpio9输出低电平 else GpioSetOutputVal(WIFI_IOT_GPIO_IDX_9,1);//让gpio9输出高电平     } } static void ADCLightDemo(void) {     osThreadAttr_t attr={0};     attr.name = "ADCLightTask";     attr.stack_size = 4096;     attr.priority = osPriorityNormal;     if (osThreadNew(ADCLightTask, NULL, &attr) == NULL) {         printf("[ADCLightDemo] Falied to create ADCLightTask!\n");     } } APP_FEATURE_INIT(ADCLightDemo); ``` ### 2.创建BUILD.gn文件 ``` static_library("adc_demo") { sources = [ "adc_demo.c", ] include_dirs = [ "//utils/native/lite/include", "//kernel/liteos_m/components/cmsis/2.0", "//base/iot_hardware/interfaces/kits/wifiiot_lite", ] } ``` **修改openharmony源码的applications\sample\wifi-iot\app\BUILD.gn文件,将其中的 features 改为:** ``` features = [ "iothardware:adc_demo", ] ``` 编译 烧录 改变光敏电阻周围环境的光,会发现串口打印的ADCvalue会发生变化; 有光时,串口输出的ADC的值为285左右; 无光时,串口输出的ADC的值为2150左右。