PWM0 and PWM1 is not working simentensoly

I have sent a mail on above mail id.

1 Like

#!/usr/bin/env python3

import os
import time

PWM0 = "/sys/class/pwm/pwmchip0/pwm0"
PWM1 = "/sys/class/pwm/pwmchip1/pwm0"

PWM0_EXPORT = "/sys/class/pwm/pwmchip0/export"
PWM1_EXPORT = "/sys/class/pwm/pwmchip1/export"

DELAY = 2          # Seconds between frequency changes
DUTY_PERCENT = 50  # Duty cycle


def write(path, value):
    with open(path, "w") as f:
        f.write(str(value))


def read(path):
    with open(path, "r") as f:
        return f.read().strip()


def export_pwm(export_file, pwm_path):
    if os.path.exists(pwm_path):
        print(f"{pwm_path} already exported.")
        return

    print(f"Exporting {pwm_path}...")
    write(export_file, 0)
    time.sleep(0.2)


def disable_pwm(path):
    try:
        write(f"{path}/enable", 0)
        time.sleep(0.02)
    except Exception as e:
        print(f"Disable failed for {path}: {e}")


def safe_zero_duty(path):
    try:
        write(f"{path}/duty_cycle", 0)
    except Exception:
        pass


def set_pwm(path, frequency):
    period = int(1_000_000_000 / frequency)
    duty = int(period * DUTY_PERCENT / 100)

    print("--------------------------------------------")
    print(f"Configuring {path}")
    print(f"Frequency : {frequency} Hz")
    print(f"Period    : {period} ns")
    print(f"Duty      : {duty} ns")

    # Step 1: disable output before reconfiguring
    disable_pwm(path)

    safe_zero_duty(path)

    try:
        # Step 3: set new period (safe now that duty_cycle == 0)
        write(f"{path}/period", period)

        # Step 4: set real duty cycle
        write(f"{path}/duty_cycle", duty)

        print("Kernel reports:")
        print("Period =", read(f"{path}/period"))
        print("Duty   =", read(f"{path}/duty_cycle"))

        # Step 5: enable
        write(f"{path}/enable", 1)

        print("PWM Enabled =", read(f"{path}/enable"))

    except Exception as e:
        print(f"ERROR configuring {path}")
        print(e)

        # Try to leave the channel disabled rather than half-configured
        try:
            write(f"{path}/enable", 0)
        except Exception:
            pass


def cleanup():
    print("\nDisabling PWMs...")

    for pwm in [PWM0, PWM1]:
        try:
            write(f"{pwm}/enable", 0)
        except Exception:
            pass

    print("Done.")


def main():

    export_pwm(PWM0_EXPORT, PWM0)
    export_pwm(PWM1_EXPORT, PWM1)

    print("\nStarting Dual PWM Test")
    print("======================")

    # PWM0 frequencies
    pwm0_freqs = [10000, 11000, 12000, 13000, 14000]

    # PWM1 frequencies
    pwm1_freqs = [16000, 17000, 18000, 19000, 20000]

    try:

        for f0, f1 in zip(pwm0_freqs, pwm1_freqs):

            print("\n============================================")
            print(f"PWM0 -> {f0} Hz")
            print(f"PWM1 -> {f1} Hz")

            set_pwm(PWM0, f0)
            set_pwm(PWM1, f1)

            print(f"\nRunning for {DELAY} seconds...")
            time.sleep(DELAY)

    except KeyboardInterrupt:
        print("\nInterrupted by user.")

    finally:
        cleanup()


if __name__ == "__main__":
    main()
1 Like

As it is solved, going to closed this issue.