Menu
CoddyTech

Return Values

Part of the Inputs section of Coddy's Arduino journey. Lesson 21 of 22.

A function can also hand a value back. Write the type of the value in place of void, and end with return and the value:

int readPercent() {
  int reading = analogRead(A0);
  return map(reading, 0, 1023, 0, 100);
}

The call then stands for that value, like analogRead() does. You can store it, print it or compare it:

int percent = readPercent();
if (readPercent() > 50) {
  // ...
}

return also ends the function at once: lines after it do not run. Variables made inside a function, like reading here, exist only while it runs; the returned value is how the result gets out.

challenge icon

Challenge

Easy

The knob is on A0 and the LED on pin 13:

  • write int readPercent() that reads A0 and returns it mapped to 0 to 100
  • in loop(), store readPercent() in a variable and print it
  • light the LED when the percent is above 50, otherwise turn it off; wait 100 ms

Press Run, turn the knob, then Check.

Try it yourself

const int ledPin = 13;

// write int readPercent() here

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // int percent = readPercent();
  // print it, light the LED above 50, wait 100 ms
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Inputs

Practice on your own: Arduino playground