Skip to main content

2. PWM

2. 1 Enabling PWM Interface

  • Use luckfox-config to enable the relevant configuration:
  1. Open the luckfox-config tool in the terminal:

    sudo luckfox-config
  2. Select Interface Options:

  3. Select PWM:

  4. Select the PWM interface you want to enable, here we take PWM9 as an example:

  5. After selecting Enter to confirm, there will be a prompt that UART4 is not available. This is because using the PWM function prevents the simultaneous use of the UART4 interface for serial communication.

  6. View the PWM interface:

    oot@linaro-alip:/home/linaro# ls /sys/class/pwm
    pwmchip0
    root@linaro-alip:/home/linaro# ls -l /sys/class/pwm
    total 0
    lrwxrwxrwx 1 root root 0 66 07:03 pwmchip0 -> ../../devices/platform/fe6f0010.pwm/pwm/pwmchip0
  7. The mapping between PWM controllers and register addresses is as follows:

    PWM ControllerRegister Address
    pwm8fe6f0000
    pwm9fe6f0010
    pwm12fe700000
    pwm13fe700010
    pwm14fe700020
    pwm15fe700030

2. 2 PWM Control (shell)

  1. Ensure that PWM8 has been enabled. The following operations are based on PWM8.

  2. You can observe the phenomenon by connecting an LED to the corresponding pin. The opening process is as follows:

    # Export pwm3 to user space
    echo 0 > /sys/class/pwm/pwmchip1/export

    # Set PWM period in nanoseconds
    echo 1000000 > /sys/class/pwm/pwmchip1/pwm0/period

    # Set duty cycle
    echo 500000 > /sys/class/pwm/pwmchip1/pwm0/duty_cycle

    # Set PWM polarity
    echo "normal" > /sys/class/pwm/pwmchip1/pwm0/polarity

    # Enable PWM
    echo 1 > /sys/class/pwm/pwmchip1/pwm0/enable

    # Unexport pwm3 from user space
    echo 0 > /sys/class/pwm/pwmchip1/unexport

2. 3 Controlling PWM Using python-periphery

  1. Ensure that PWM8 has been enabled. The following operations are based on PWM8.

  2. The sample code for PWM output using the python-periphery library is as follows:

    from periphery import PWM
    import time
    import numpy as np

    # Open PWM chip 0, channel 0 pwm = PWM(0, 0)
    pwm = PWM(0, 0)

    # Set frequency to 100 Hz
    pwm.frequency = 1e2

    #set the PWM’s output polarity
    pwm.polarity = "normal"

    # Set duty cycle to 0
    pwm.duty_cycle = 0

    pwm.enable()

    # Change duty cycle
    for i in np.arange(0.0, 1.0, 0.05):
    pwm.duty_cycle = i
    time.sleep(1)

    pwm.close()
  3. Run the program, and you will see the LED connected to Pin 33 gradually brighten.