Led self dimming and brightening

hello, im very very new to arduino so please be patient.
i just learned for loops so i thought of coding an led that brightens and dims by itself, im able to make it upto the max brightness but cant seem to get it down. i think this will be more achievable with a while loop but i want to see what a for loop can do. heres the code:


int j;

int wait=500;

int mypin=9;

int bright=255;

void setup() {

// put your setup code here, to run once:

Serial.begin(9600);

pinMode(mypin,OUTPUT);

}

void loop() {

// put your main code here, to run repeatedly:

for(j=1;j<=bright;j=j+1){

analogWrite(mypin,j);

delay(wait);

}

for(j=bright;j>=0;j=j-1){

analogWrite(mypin,j);

delay(wait);

}

}

What makes you say that the LED is not dimming ? Do you know how long it takes the LED to reach full brightness before starting to dim ?

Try printing the value of j before writing it to the LED so that you can see what is being written

Change the value of wait from 500 to 50 or 20 and see what happens.

What value of current limiting resistor did you place in series with the LED?

changing wait to 50 is working thanks a lot. is it dependent on the fact that for 1/255 units, half a second is wayy too long? and the resistor is 330 ohms. thanks again!!

youre right. i indeed underestimated the time that it needs to get to 5 volts.

I am glad that you got there

Printing the values as they were used would have given you a big clue as to what was going on

With wait = 500, it takes about 128 seconds, or over two minutes to reach full brightness.

I'll definitely keep that in mind from now on

Idk why I didn't think of applying basic unitary method on this, i thought half a second is fast regardless of where it's used.

That is true, but you used it 255 times !

i started the arduino lessons after doing tons of integration and was soo ready to not use even a ounce of maths but well 1/2 of 256 is still math lol

I think you mean 1/2 times 256

A half of 256 is 128, it's a matter of grammatical phrasing, We're both right.

Next, read about millis() delays.
You’ll thank us later !

I'll work on it, thank you!