CCCPaste

Controlling LED Brightness using PWM

void setup() {
  // put your setup code here, to run once:
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(2, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  Serial.begin(9600);
}

float pwm    = 50.00; // 50 %
float period = 1000.0; // 1 seconds

void loop() {
  // put your main code here, to run repeatedly:
  int buttonStateDown = digitalRead(4);
  int buttonStateUp   = digitalRead(2);

  if (buttonStateDown == 0) { // Button is pressed
    pwm = pwm - 10;
    if (pwm < 0) pwm = 0.0; 
  }

  if (buttonStateUp == 0) {  // Button is pressed
    pwm = pwm + 10;
    if (pwm > 100) pwm = 100.0; 
  }

  Serial.print("Down:");
  Serial.print(buttonStateDown);
  Serial.print(" - Up:");
  Serial.println(buttonStateUp);

  float on  = pwm / 100 * period;
  float off = (100.0 - pwm) / 100 * period;

  digitalWrite(LED_BUILTIN, HIGH);
  delay(on);
  digitalWrite(LED_BUILTIN, LOW);
  delay(off);

  Serial.print(on);
  Serial.print("/");
  Serial.print(off);
  Serial.print("/");
  Serial.println(pwm);
}