跳转至

开关

通过外接开关控制外接LED亮灭

外接开关

接线要求

  • GND连接开发板GND

  • K0连接开发板GPIO 07

项目编写

  1. applications/genkipi/app 下新建 switch_led 文件夹
  2. switch_led 下新建 main.c 文件
  3. switch_led 下新建 BUILD.gn文件

代码部分

main.c 文件内容

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "ohos_init.h"

#include "iot_gpio.h"
#include "iot_io.h"
#include "genki_pin.h"

static void start(void) {
    //开关初始化
    IoTIoSetFunc(IOT_IO_NAME_7,IOT_IO_FUNC_7_GPIO);
    IoTGpioSetDir(IOT_IO_NAME_7,IOT_GPIO_DIR_IN);
    //LED初始化
    IoTIoSetFunc(IOT_IO_NAME_14,IOT_IO_FUNC_14_GPIO);
    IoTGpioSetDir(IOT_IO_NAME_14,IOT_GPIO_DIR_OUT);

    //led是否已经打开标志
    int flag = 0;
    //状态
    int status = 0;

    //读取开关数据
    while(1){
        int val = -1;
        IoTGpioGetInputVal(IOT_IO_NAME_7,&val);

        if(val==0){
            //改变状态
            status=1;
            continue;
        } else{
            printf("val值:%d \r\n",val);
        }
        if(status!=1){
            continue;
        }
        status = 0;
        if (flag==0){
            //打开
            IoTGpioSetOutputVal(IOT_IO_NAME_14,IOT_GPIO_VALUE1);
            flag = 1;
        } else{
            //关闭
            IoTGpioSetOutputVal(IOT_IO_NAME_14,IOT_GPIO_VALUE0);
            flag = 0;
        }
    }
}

APP_FEATURE_INIT(start);
//SYS_RUN(start);

项目Build.gn

switch_led 目录下 BUILD.gn 内容为

static_library("switch_led") {
    sources = [
        "main.c"
    ]

    include_dirs = [
        "//utils/native/lite/include",
        "//base/iot_hardware/peripheral/interfaces/kits",
        "//device/itcast/genkipi/interfaces/kits"
    ]
}

外部Build.gn

switch_led文件夹上一级目录下BUILD.gn内容为

import("//build/lite/config/component/lite_component.gni")

lite_component("app") {
    features = [
        "switch_led"
    ]
}