Here's a duty cycle sketch to play with:
/*
Enter Hz in Serial monitor with h followed by number like this:
h20{ENTER]
Enter percent like:
p50[ENTER]
Or both:
h20,p50[ENTER]
*/
unsigned long cycleStart,
onTime,
cycleTime,
hz;
int val;
const byte powerPin = LED_BUILTIN;
byte percent = 50;
void setup()
{
Serial.begin(9600);
Serial.println(" Hz = 5 Duty Cycle = 50%");
hz = 5;
cycleTime = 1000000UL / hz;
onTime = cycleTime / 2;
pinMode(powerPin,OUTPUT);
}
void loop()
{
digitalWrite(powerPin,micros() - cycleStart < onTime);
if(micros() - cycleStart > cycleTime)
cycleStart += cycleTime;
// if there's any serial available, read it:
if(Serial.available() > 0)
{
val = Serial.read();
if(val == 'h' || val == 'H')
hz = Serial.parseInt();
else if(val == 'p' || val == 'P')
{
percent = Serial.parseInt();
}
else
while(Serial.available() > 0)
Serial.read();
cycleTime = 1000000UL / hz;
percent = constrain(percent, 0, 100);
onTime = cycleTime * 0.01 * percent;
cycleStart = micros();
Serial.print(" Hz = ");
Serial.print(hz);
Serial.print(" Duty Cycle = ");
Serial.print(percent);
Serial.println("%");
}
}