Adding a fade to a digital write

I’m new to Arduino, so please excuse if this is a newb question. I’m trying to add a fade time of 4 seconds to this code that I found from Robojax. I like the way that it currently works however, I’d like the would like the LED to fade up in 4 seconds on the first push, and then fade out in 4 seconds when the button is pushed again. Any assistance would be greatly appreciated.

int pbuttonPin = 2;// connect output to push button
int ledPin = 9;// Connected to relay (LED)

int val = 0; // push value from pin 2
int lightON = 0;//light status
int pushed = 0;//push status

void setup() {
  // code and video tutorial for push button ON and OFF
  pinMode(pbuttonPin, INPUT_PULLUP); 
  pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, HIGH);// keep the load OFF at the begining. If you wanted to be ON, change the HIGH to LOW

void loop() {
// code and video tutorial for push button ON and OFF
  val = digitalRead(pbuttonPin);// read the push button value

  if(val == HIGH && lightON == LOW){

    pushed = 1-pushed;

  lightON = val;

      if(pushed == HIGH){
        Serial.println("Light ON");
        digitalWrite(ledPin, LOW); 
        Serial.println("Light OFF");
        digitalWrite(ledPin, HIGH);

// code and video tutorial for push button ON and OFF



There’s a tutorial on the Arduino website for how to fade an LED off and on that can help you understand how to control the brightness level of an LED. The code there uses analogWrite() to adjust the PWM on the LED pin to control its brightness level, which is incremented or decremented with each iteration of the main loop. One way to implement the fading behavior into your code would be to create two functions called fadeIn() and fadeOut() each adjusting the brightness level accordingly and replacing the digitalWrite(ledPin, LOW) and digitalWrite(ledPin, HIGH) to call fadeIn() and fadeOut(), respectively. As for getting the LED to fade in and out within four seconds, you would need to adjust the delay time between each change of the LED’s brightness to ~16 ms (4 seconds / 255).

- Amanda