Arduino Programming – Part 5: User-defined functions ME 120 Mechanical and Materials Engineering Portland State University http://web.cecs.pdx.edu/~me120 User-Defined Function • What is it? A user-defined function is a function that you write yourself. Opposite to Built-in functions such as digitalWrite, delay, etc.. • Why? to simplify and organize your code. • How? Built your function outside of your void loop and void setup. Call it from anywhere. It will be treated like a built-in function. 2 Example: Countdown • You would like to built a countdown from 10 to 0 that you could see on your serial monitor. • Without creating any function, the code is: void setup() { Serial.begin(9600); int i; for (i=10; i>=0; i--){ Serial.println(i); delay(1000); } } //Initialize serial port communication //goes from 10 to 0, decrement of 1 //print the value of i on serial monitor //wait 1 sec between each value void loop() { } 3 Example: Countdown • Let’s built a function that we call “countdown” void setup() { Serial.begin(9600); countdown(); } //Initialize serial port communication // call the function countdown void loop() { } void countdown(){ int i; for (i=10; i>=0; i--){ Serial.println(i); delay(1000); } } // create the function countdown 4 Example: Countdown • Let’s add a parameter: the value of the countdown start void setup() { Serial.begin(9600); countdown(15); } //Initialize serial port communication // call the function countdown void loop() { } void countdown(int start){ int i; for (i=start; i>=0; i--){ Serial.println(i); delay(1000); } } 5 Example: Countdown • Let’s add a second parameter: the value of the time delay between the counts void setup() { Serial.begin(9600); countdown(15, 2000); } //Initialize serial port communication // call the function countdown void loop() { } void countdown(int start, int deltaT){ int i; for (i=start; i>=0; i--){ Serial.println(i); delay(deltaT); } } 6 Example: Countdown • We want to know the sum of all the numbers counted in the countdown. void setup() { Serial.begin(9600); int result; result = countdown(15, 2000); } void loop() { } int countdown(int start, int deltaT){ int i; int sum=0; for (i=start; i>=0; i--){ Serial.println(i); delay(deltaT); sum = sum+i; } return (sum); } 7 Summary of user-defined functions • You chose the name ❖ Make sure the name is not already used • You chose the type of return value • You choose the number and type of inputs ❖ • Input types are declared in the function definition int countdown(int start, int deltaT){…} ❖ Input variables are used in the body of the function • Variables in the function are local ❖ Calling function is not affected by local variables and logic in the function 8