-1

I'm trying to flash a LED at 27kHz for a project and using the general GPIO the fastest I can get is around 3kHz. Any library's that would be suitable for this?

# Import the libraries
import RPi.GPIO as GPIO
import time

Set the GPIO mode

GPIO.setmode(GPIO.BCM)

Set the LED pin as output

LED_PIN = 18 GPIO.setup(LED_PIN, GPIO.OUT)

Create a PWM object

pwm = GPIO.PWM(LED_PIN, 27000) # 27 kHz frequency

Start the PWM with 0 duty cycle

pwm.start(0)

Define a function to read a value from a text file

def read_value(): # Open the file in read mode with open("value.txt", "r") as f: # Read the first line line = f.readline() # Try to convert it to a float try: value = float(line) except ValueError: # If the conversion fails, return None value = None # Return the value return value

Define a loop to flash the LED

def flash_led(): # Get the value from the file value = read_value() # If the value is valid, change the duty cycle if value is not None and 0 <= value <= 100: pwm.ChangeDutyCycle(value) # Wait for 0.01 seconds time.sleep(0.01)

Run the loop until interrupted by keyboard or system

try: while True: flash_led() except (KeyboardInterrupt, SystemExit): # Stop the PWM and clean up the GPIO pwm.stop() GPIO.cleanup()

2 Answers2

0

This is frankly bizarre code which uses RPi.GPIO software PWM which more or less by definition can't do anything "precise" and it unclear what output you are expecting to do with the "value".

It would be possible, using hardware PWM, to generate a precise output (but the actual values possible are constrained by the clock) and you can not get an exact 27kHz signal. (Using the fractional divider may get closer but I have never seen any code using this.)

Most models (pre Pi4) have 19.2MHz clock so a 711 divider would give 27.004kHz. You would have to choose a combination of PWM range and divider to give the output you want. e.g. DIVIDER = 15 & RANGE = 128 gives a 15 * 128 => 1920 divider and thus 10kHz.

For 711 use 9 * 79 or 3 * 237.

My pi-gpio (c) & pi_gpio (python) would permit this.

pigpio has hardware timed PWM and should be able to produce similar but only a small set of pre-defined frequencies, pigpio supports arbitrary waveform generation which may be better for your purpose and can generate fixed frequency clock outputs up to 30MHz.

The kernel pwm overlay may also be a candidate (although I have never tested its ability to generate arbitrary frequencies - it is usually used with much lower frequencies) https://raspberrypi.stackexchange.com/a/143644/8697

Milliways
  • 62,573
  • 32
  • 113
  • 225
0

you'd be better off using a dedicated timer circuit (e.g using a 555 ic or similar) as the Pi isn't suitable for this type of application as the operating system can get busy doing other things.

Bra1n
  • 1,261
  • 7
  • 8