Archive

Posts Tagged ‘return’

Writing Functions

July 16, 2012 Leave a comment

This is a simple concept so I’m going to get through it quickly. A function is a block of code that has a name and a property and is designed to be easily reusable. When you create a function, you are essentially creating a machine that does a certain job, and you can call upon it at any time to do that job.

A simple function would be one that adds two numbers together:

int sum(int x, int y)
{
	int ans = 0;  //holds the answer
	ans = x + y;  //calculates the sum
	return ans  //returns the answer
}

The first part “int sum(int x, int y)” is the header, and has a name “sum()“, parameters that go in between the parentheses “int x, int y“, and the type of return value desired “int …“.

Within the body of the function (whats between the brackets) is what will be done when the function is called upon. So, say that I called for sum(3,2), looking at the body of the function I can tell that the result will be 5.

We can use this with the Arduino in quite the same way, for example, if we wanted to turn the blink sketch into a function that blinked LED 13 a certain number of times (n) it would look something like this:

int ledPin = 13;
 int blinkVal = 3;
void setup()
 {
 pinMode(ledPin, OUTPUT);
 blinkTimes(blinkVal); //here the function is run once
 }
void loop(){}
void blinkTimes(int n) //function definition
 {
  for (int i = 0; i < n; i++)
  {
  digitalWrite(ledPin,HIGH);
  delay(1000);
  digitalWrite(ledPin,LOW);
  delay(1000);
  }
 }

The function in use is colored blue, the number of blinks is red, the function definition is green, and the defined parameter within the function is bold and black.

Now that you have the function defined you can put it at the bottom of your sketch and forget about it, calling it when ever you need the defined task done. However, the true power of functions comes from the ability to use multiple parameters. Say I want to be able to adjust not only the number of times that it blinks, but also the delay in between. That is easy enough to do, all I need is to add another parameter and modify the body of the function to include it:

void blinkTimes(int n, int d) //function definition
 {
  for (int i = 0; i < n; i++)
  {
  digitalWrite(ledPin,HIGH);
  delay(d);
  digitalWrite(ledPin,LOW);
  delay(d);
  }

So if I call the function blinkTimes(10,500); now it will blink 10 times turning on and off for 500 milliseconds.

Sources: [C4Learn, C4LearnMYCPLUS]