Having trouble making my code do what I Intend

This is a little bit of code I am struggling with. I am trying to fade an LED without using delay() and it is not working, no matter what I do.

const int led = 9;

int dir = 5;
int val;

unsigned long previousMillis;

void setup(){
  pinMode(led, OUTPUT);
}

void loop(){

  unsigned long currentMillis = millis();
    
  if(currentMillis - previousMillis >= 30){
    previousMillis = currentMillis;

    if((val >= 255) || (val <= 0)){
      dir = dir * -1;
    }

    val = val + dir;

    analogWrite(led, val);
  }
}

I am sort of a beginner when it comes to this, so I don't know what could be causing the problem in the first place; It was hard enough to get it to compile :b.

Do a Serial.print on variables to see what is happening.

.

Thanks that actually helped a lot. :slight_smile:

This might be of interest.

https://forum.arduino.cc/index.php?topic=215334.0

.