Let's learn about helper functions - quasics/quasics-frc-sw-2015 GitHub Wiki
So you've been working on arduino code, and you think you're getting pretty good at it. Now it's time to look at a little thing called the helper function. I've prepared some sample code and a ciruit diagram for you to use. Build the circuit, upload the sample code to it, and see what happens.
Go ahead...
I'll wait
It does exactly what the file says it does. Now let's go over the code. The setup should seem familiar, but the loop function seems way different. However, if you scroll down, you'll see something that's probably unfamiliar:
void breathe(uint32_t pin){ for(int a = 0; a < 255; a++){ analogWrite(pin, a); delay(8); } for(int a = 255; a > 0; a--){ analogWrite(pin, a); delay(8); } }
This is what is called a helper function. You declare it by first saying void (the data type), then adding a space and writing its name, followed by adding two parentheses, and ending it with open and closed braces. But, here's the thing. I lied. If you look at my code there's something inside the parentheses. Look again at that one line
void breathe(uint32_t pin){
What I've done in the parentheses is established an integer that you select a value for every time you call the function. I'll get into this in more detail later.
So, alright, fine, you've made a helper function, but how do you use it? Well, you call it. In my code, my loop is completely made of calling this function.
void loop() { breathe(8); breathe(9); breathe(10); }
The syntax for calling a function is to, quite literally, call its name (followed by the parentheses, and, of course, our glorious leader the semi-colon). And this is where our friend the uint32_t comes back into play. See, when I call the function, I put a number in the place of the integer we coded. For instance, this:
breathe(9);
Turns this:
void breathe(uint32_t pin){ for(int a = 0; a < 255; a++){ analogWrite(pin, a); delay(8); } for(int a = 255; a > 0; a--){ analogWrite(pin, a); delay(8); } }
Into this:
void breathe(){ for(int a = 0; a < 255; a++){ analogWrite(9, a); delay(8); } for(int a = 255; a > 0; a--){ analogWrite(9, a); delay(8); } }
Alright, I know that was a lot of reading, so if you're confused on anything, feel free to ask away. Keep in mind, I'm about to give you some work to do, so again, if you have questions, ask the nearest coder. They'll answer you, or get someone who can.
...We good? Great.
Challenges
Easy mode: Code and wire in more output pins and call the function I wrote to make it work for them.
Normal mode: Write and call a helper function to make all the lights breathe at once.
Hard mode: With the use of a helper function that you wrote, make all the lights "breathe in" (turn on gradually) one after the other, then make them "breathe out" (turn off gradually) one after the other. You may accomplish this however you like.
Remember, we're here to help if you get stuck.