Skip to content

Functions

Use the Function blocks to create functions that structure specific tasks.

Example 1: Simple function

Programmers use functions to store repeatable tasks and make code easier to read. In this example, a function named setRandomLED sets the //code.Node RGB LED to a random color. By putting this code in a separate function, the main code block is easier to read.

Example 2: Passing variables into a function

Let's take Example 1 a step further by also creating a function to play a musical note. In order to play a note, we need to place a value in the function so the program knows which note to play. To accomplish this, select properties on the function block and add the input name block to the function.

In the loop, the code stores the note frequency in the i variable, which gets its value from the notesList variable. The function called playNote takes an input called noteFreq. The code passes the i variable into this function. The function turns off the speaker and then plays each note in the list for 0.5 seconds.

Example 3: Returning values from a function

Functions can also return a value. In this example, a function called getNoteFrequency looks up a character i from the notesList list and returns the note letter's frequency. This value is then set to noteFreq, which the code passes to the playNote function to play the note.