This will be my first post about arduino although not my first program. I waited until I had done some basic stuff and had something interesting to say.

I have done the blink and press button to blink. I decided the one to post about would be my venture into functions.

I needed to be able to call functions to allow for a program that had more flexibility to it. To that end I made what is a simple program to raise and lower the brightness of a led over a flexible period of time. I am going to post the program with what I hope are copious notes to make it understandable. If you have any trouble with it just leave a comment and I will try to clear the fog.

 

Here it is:

/*

Pulse an led on a pin. Go from dark to full bright in a designated interval then back down to dark in the same interval

*/
int ledPin = 11; // led pin used for LED in entire program

int interval = 500; // interval for change in milliseconds, 1000 is one second up and one second down

int waitforit = (interval/255); //delay this much between each increment

void brightup () {

/*

this is the subroutine to raise the brightness from zero to 255 over a specific delay

brightness is declared and initialized in this function

waitforit was declared and initialized for the entire program first
*/

for (int brightness = 0; brightness < 255; brightness ++){

analogWrite(ledPin,brightness); //write the brightness value

delay(waitforit); // delay 1/255 of the interval to maximum brightness

}

}

 

void brightdown () {

/*

this is the subroutine to lower the brightness from zero to 255 over a specific delay

brightness is declared and initialized in this function

waitforit was declared and initialized for the entire program first

*/

for (int brightness = 255; brightness > 0; brightness — ){

analogWrite(ledPin,brightness); //write the brightness value

delay(waitforit); // delay 1/255 of the interval to maximum brightness

}

}

void setup ()  {

pinMode(ledPin, OUTPUT); //initialize ledPin for OUTPUT

}

void loop()    {

brightup();   //call the brightup fuction to raise the led brightness from 0 to 255

brightdown();  //call the brightdown fuction to lower the led brightness from 255 to 0

}

 

This is it working