Defining and calling "in code" functions (subroutines)

Hi all,

My question is a basic one regarding coding. I am trying to define a function/subroutine. What would the syntax of that be?

I want to use it to turn on a specific series of WS2812 LEDS. I thought If I could define a piece of code that would just switch them on I could call it in my main programme whenever I wanted.

Would this be defined in the Setup area?

Thank you.

You define a function outside of the setup and loop functions - the syntax is exactly the same as the build in setup and loop. For example, to define a new function turnOnLEDs

void turnOnLEDs() {
   // turn on leds
   digitalWrite(D0, HIGH); // etc..

Breaking this down:

  • void tells the compiler this function doesn’t return a result
  • turnOnLEDs is the name of the function
  • () means the function doesn’t need any parameters passing to it
  • { and } enclose the body of the function - the code executed when the function is called.

You then call that function when needed in loop - e.g. to turn the LEDs on after 1 minute:

void loop() {
    if (millis()>60000) {

For more details on functions, C Functions