On the Arduino, not all the digital pins can do PWM. As you can see in the photo below, only pins 3, 5, 6, 9, 10 and 11 have PWM capabilities (at least on the Uno).
Duty cycle of a square wave is calculated by the percentage of the period of highs over the total period. This is a chart taken from the Arduino website.
In the Arduino IDE, the PWM function is given by analogWrite(). For example, analogWrite(9, 127) gives a 50% duty cycle wave output at Digital Pin 9.
To demonstrate the effects of PWM, I’m going to use an LED. For every push of a button, the duty cycle will increase, thus making the LED brighter. In the code, I’ve also implemented switch debouncing but it’s quite sketchy and I think it can be improved (I’m still new at this).