I've been trying, just out of curiosity, to write my own function that generates a PWM signal, just like analogWrite()
, and to make it light up an LED. Here's my attempt so far:
const int pin = 3;
int cycle = 2; // analogWrite() outputs a 498 Hz signal, so each cycle has approximately 2ms
int duty = 0.5; // for a 50% duty cycle
void setup() {
Serial.begin(9600);
pinMode(pin,OUTPUT);
}
void loop() {
digitalWrite(pin,HIGH);
delay(cycle*duty);
digitalWrite(pin,LOW);
delay(cycle*(1-duty));
}
The LED does light up, but very dimly, as shown below:
However, when using analogWrite()
with a 50% duty cycle to achieve the same result, the LED shines much brighter:
Is there something wrong with my code, or is there a special reason why more power is dissipated with analogWrite()
?
cycle
?analogWrite()
. I can't really understand why, though, so I'd really appreciate it if you could provide some clarification. :)