跳转至

定时器

项目编写

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

代码部分

main.c 文件内容

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

#include "ohos_init.h"
#include "cmsis_os2.h"

static void timer_repeat_callback(void *arg)
{
    (void)arg;
    printf("timer repeat callback!\r\n");
}

static void timer_once_callback(void *arg)
{
    (void)arg;
    printf("timer once callback!\r\n");
}

static void start(void)
{
    osTimerId_t id1, id2;
    uint32_t timerDelay;
    osStatus_t status;

    // repeat timer
    id1 = osTimerNew(timer_repeat_callback, osTimerPeriodic, NULL, NULL);
    if (id1 != NULL)
    {
        // Hi3861 1U=10ms,100U=1S
        timerDelay = 100U;

        status = osTimerStart(id1, timerDelay);
        if (status != osOK)
        {
            // Timer could not be started
            printf("timer repeat start failed\r\n");
        }
    }

    // once timer
    id2 = osTimerNew(timer_once_callback, osTimerOnce, NULL, NULL);
    if (id2 != NULL)
    {
        // Hi3861 1U=10ms,100U=1S
        timerDelay = 100U;

        status = osTimerStart(id2, timerDelay);
        if (status != osOK)
        {
            // Timer could not be started
            printf("timer once start failed\r\n");
        }
    }
}

APP_FEATURE_INIT(start);

项目Build.gn

timer 目录下 BUILD.gn 内容为

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

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

外部Build.gn

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

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

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