PWM Control LED Breathing

This sample code guide is designed to help users easily and comprehensively understand PWM sample. This sample demonstrates how to achieve the effect of breath LED with PWM.

Requirements

For hardware requirements, please refer to the Requirements.

Wiring

On EVB, connect P2_1 to LED1, connect P2_2 to LED2, and connect P2_7 to LED3.

Configurations

  1. The following macros can be configured to modify pin definitions.

    • #define LED_OUT_0       P2_1

    • #define LED_OUT_1       P2_2

    • #define LED_OUT_2       P2_7

    • #define LED_OUT_3       P1_6

    • #define LED_OUT_4       P1_7

    • #define LED_OUT_5       P0_1

  2. The following macros can be configured to modify the number of LEDs.

    • #define LED_DEMO_NUM            3

  3. The following macros can be configured to modify the PWM output count value.

    • #define PWM_OUT_COUNT 10000

  4. The entry function is as follows, call this function in main() to run this sample code. For more details, please refer to the Initialization.

    led_demo_task();
    

Building and Downloading

For building and downloading, please refer to the Building and Downloading.

Experimental Verification

Press the Reset button on the EVB board, LEDs turn from dark to bright and then from bright to dark with the effect of breath light.

Code Overview

This section introduces the code and process description for initialization and corresponding function implementation in the sample.

Source Code Directory

  • For project directory, please refer to Source Code Directory.

  • Source code directory:

    • sdk\src\sample\io_demo\led\led_demo_task.c

    • sdk\src\sample\io_demo\led\sw_led_demo.c

    • sdk\src\sample\io_demo\led\sw_led_demo.h

Initialization

  1. Call os_msg_queue_create to create a message queue instance.

  2. Call app_init_timer to initialize APP timer module.

  3. Call os_task_create() to create a new task and add it to the list of tasks that are ready to run.

  4. Call led_demo_init to initialize LED to breathe mode:

    1. Call led_demo_set_driver_mode to set LED driver to software mode and register a timeout callback function in APP timer module.

    2. Call led_demo_board_led_init to set the LED polarity to active high and set the pin used by the LED to software mode, pull none, and output low.

    1. Call led_demo_load_table to set the LED to breathe mode.

  5. Call led_act_start to start LED:

    1. Call led_demo_config to initialize LED parameters and configure PWM output pin.

    2. Call led_demo_cmd_handle to create PWM, configure PWM output pin, register a timeout callback function to PWM module, and start PWM.

PWM Timeout Callback Handle

When PWM times out, the callback function is executed.

  1. Calculate the high level count value and the low level count value.

  2. Call pwm_change_duty_and_frequency() to change PWM high level count and low level count.