1

I need a PWM signal of 25KHz and duty cicle 0-100%. It must be "hardware" becase I don't want to bother the CPU with that. The ony way I found to do that in Python is by using ppigpio library. But I never used before and I don't know how to set it up. As far as I understand there is true hardware pwm and hardware-timed pwm. But I don't know which instructions stars on type and which starts the other. Can you show me a basic example ?

Edit: is this the right way to do it ?

import pigpio
import time

Set the GPIO pin for PWM

gpio_pin = 18

Set the PWM frequency (25 kHz)

pwm_frequency = 25000

Set the PWM duty cycle (75%)

pwm_duty_cycle = 750000 # 75% of the range (0-1000000)

Initialize the pigpio library

pi = pigpio.pi()

if not pi.connected: print("Unable to connect to pigpio daemon. Exiting.") exit()

try: # Set the PWM frequency and duty cycle using hardware_PWM pi.hardware_PWM(gpio_pin, pwm_frequency, pwm_duty_cycle)

# Run the PWM for a certain duration (e.g., 10 seconds)
time.sleep(10)

finally: # Stop PWM and cleanup pi.hardware_PWM(gpio_pin, 0, 0) # Set duty cycle to 0 to stop PWM pi.stop()

Edit2: I also tried this, but it says "bad PWM frequency":

from gpiozero import PWMOutputDevice
import time

PWM_PIN = 18 # Change this to the GPIO pin you want to use PWM_FREQUENCY = 25000 # 25 kHz PWM_DUTY_CYCLE = 0.5 # 50%

pwm = PWMOutputDevice(PWM_PIN, frequency=PWM_FREQUENCY)

try: while True: print('Speed: 100 %') pwm.value = 1 time.sleep(20)

print('Speed: 50 %')
pwm.value = 0.5
time.sleep(20)

except KeyboardInterrupt: pass

finally: pwm.value = 0 # Set PWM duty cycle to 0 print("\nProgram terminated by user. PWM stopped.")

Marus Gradinaru
  • 131
  • 1
  • 6

1 Answers1

1

There are several hardware PWM implementations (although it is doubtful that they will work on a Pi5). All that I am aware of directly manipulate the system registers.

There is a kernel overlay for PWM although it is poorly documented. I have written code to use this. See https://raspberrypi.stackexchange.com/a/143644/8697

I have recently been tidying up the code for more general usage. See https://raspberrypi.stackexchange.com/a/145068/8697

Milliways
  • 62,573
  • 32
  • 113
  • 225