How to create a custom method in Arduino

As the title suggests: How can I create a custom function/method in Arduino C++ using PlatformIO?

Typically (in the Arduino IDE) I would simply write
void myFunction() { \*some code*\ }
outside of the void loop() and void setup() methods and then call it by using myFunction().

However, doing this will result in an error: 'myFunction' was not declared in this scope.

How can I solve this and create/use custom methods in Arduino C++?

I’m using the latest PIO on VSCode.


Other than the Arduino IDE, PlatformIO uses proper C++. Therefore, a function must be declared or defined before it is used the first time. First time refers to processing the C++ file top to bottom.

  • Either move the function before setup() and/or loop().
  • Add a forward declaration, e.g.:
void myFunction();  // forward declartion (no code, just ending with a semi-colon)

void setup {

void loop {
   myFunction();  // use of myFunction()

// definition/implementation of myFunction()
void myFunction() {
   myFunctions' code

Also see FAQ: Redirecting...

1 Like