We have discussed LED blinky and Button interface with Raspberry Pi in previous tutorials. In this Raspberry Pi PWM tutorial we will talk about getting PWM output with Raspberry Pi. PWM stands for ‘Pulse Width Modulation’. PWM is a method used for getting variable voltage out of constant power supply. We will generate PWM signal from Raspberry PI and demonstrate the PWM by varying the Brightness of a LED, connected to Pi.
- Raspberry Pi
- 220 Ohm Resistor
Place the LED with a 270 ohm resistor in series with the GND and GPIO pin of Raspberry Pi (use a breadboard for hassle free connection). Always use a resistor with LEDs to limit the current, else you might end up with a burnt LED ;)
Code - Blocks
Code - Python
Create new python file pwm.py and enter following code. To run the code, open the terminal and go to directory where you code is located and enter the command " sudo python pwm.py " and hit enter.
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(27, GPIO.OUT) pwm1=GPIO.PWM(27,100) pwm1.start(0) while True: val = input("type a number between 0 and 100") pwm1.ChangeDutyCycle(val)