2

I'm able to write to GPIO pins with sysfs with the standard commands like echo "1" > /sys/class/gpio/gpio6/value, but that only turns the pin on or off.

I tried echo "0.5" > /sys/class/gpio/gpio6/value and echo "50%" > /sys/class/gpio/gpio6/value but those give an Invalid argument error.

I tried looking it up, but couldn't find any examples of sysfs PWM usage for the GPIO interface.

How can I use PWM with sysfs?


(I put together a fan module a couple of years ago and wrote some software to control it as well as to automate it whenever the board gets hot, and that worked fine. But I want to make it so that it's not always blasting 100% when it turns on, I want it to blow according to the temperature. I switched the (two-wire) fan to a PWM pin and can turn it on and off as before, but I need to control its duty-cycle. This is technically an XY-problem for me, so any solution would be great, but one answering this specific question would also help others wondering this for other applications.)

Synetech
  • 131
  • 1
  • 5

4 Answers4

4

To use pwm, you need to use the pwm interface at /sys/class/pwm, not the gpio interface.

Here is the relevant documentation. The startup would be something like export 1 > /sys/class/pwm/pwmchip0/0/export.

PMF
  • 906
  • 7
  • 14
0

I have done this before but I would not recommend doing it this way. sys/class/gpio doesn't support PWM on it's own, you can only write 1 or 0, ie "on" or "off" to a gpio pin using the sysfs gpio interface. PWM means writing on for a certain duration and then off for a certain duration and then repeating. You can implement this yourself with sysfs in software, but there are other more industry standard ways to accomplish this, look into hardware timed pwm interfaces

Dyskord
  • 119
  • 8
0

There is some real paths for work with Pi PWM0 output:

/sys/class/pwm/pwmchip0/export
/sys/class/pwm/pwmchip0/pwm0/enable
/sys/class/pwm/pwmchip0/pwm0/period
/sys/class/pwm/pwmchip0/pwm0/duty_cycle
0

But I think that for to generate PWM by Pi is better to be independent on only 2 PWM predefined ports, especially when multiple different devices are connected to the one Pi bus. There is commented Python code for to use any GPIO port as PWM output and set frequency and duty cycle:

import RPi.GPIO as GPIO     #import the RPi.GPIO library
from time import sleep      #import the sleep from time library
GPIO.setmode(GPIO.BOARD)    #set GPIO PIN number on Pi board
GPIO.setup(7, GPIO.OUT)     #set PIN 7 as Output PIN

pwm_obj = GPIO.PWM(7, 400) #create object pwm_obj (PinNumber, Frequency) while True: pwm_obj.start(40) #start generating signal(Duty cycle = 0-100) pwm_obj.ChangeDutyCycle(10) #change Duty cycle time.sleep(1) #leave the same setting (eg. for 1sec.)