# define FREQ_PRINT 10
const int pinLed = 12; // The digital pin to which a led is connected.
unsigned long previousMicros;
unsigned long interval;
int outputState;
int l_time=0;
const int pwmMinimumWidth = 10000; // minimum pulse width in microseconds
int pwmValue = 10;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.setTimeout( 10);
Serial.println( "Enter brightness, 0...100");
pinMode( pinLed, OUTPUT);
}
void loop() {
unsigned long currentMicros = micros();
if( Serial.available() > 0)
{
int brightness = Serial.parseInt(); // get the number
Serial.read(); //Delete the new line char passed after pressing enter
pwmValue = constrain( brightness, 0, 100); // set the new PWM value
}
if( currentMicros - previousMicros >= interval)
{
previousMicros = currentMicros;
if( outputState == LOW && pwmValue != 0)
{
digitalWrite( pinLed, HIGH);
outputState = HIGH;
interval = pwmMinimumWidth * pwmValue; // the time that the signal will be HIGH.
}
else if( outputState == HIGH && pwmValue != 100)
{
digitalWrite( pinLed, LOW);
outputState = LOW;
interval = pwmMinimumWidth * (100 - pwmValue); // the time that the signal will be LOW.
}
}
l_time++;
if (l_time >= FREQ_PRINT){
Serial.print( outputState );
Serial.print("\r\n");
l_time=0;
}
}