1

I am trying to have a header file to handle all my pin definitions and pinmodes.

This is the header:

#ifndef __HEADER_TESTER__
#define __HEADER_TESTER__
#include <SoftwareSerial.h>
const byte rxPin = 2;
const byte txPin = 3;
SoftwareSerial mySerial(rxPin, txPin);
pinMode(LED_BUILTIN, OUTPUT);
#endif

However, when I compile this, I get an error on the pinMode(LED_BUILTIN, OUTPUT); line:

expected constructor, destructor, or type conversion before '(' token
asked Feb 9, 2023 at 15:40
3
  • try including the header file from inside setup() Commented Feb 9, 2023 at 16:03
  • @jsotola I got the same error... Commented Feb 9, 2023 at 16:05
  • 1
    Except for the preprocessor directives, none of this belongs to a header. Commented Feb 9, 2023 at 20:41

1 Answer 1

3

The pinMode() statement is executable code and can not be executed outside of a function - setup(), loop(), or some other function defined by you. One could imagine defining a function in your header (.h) file to set your pin modes but defining code in a header will cause a different kind of problem (multiple definitions) if you ever add another code module, a .cpp file, for instance, that also includes this same .h file.

Pin modes are usually set in the setup() function, once per execution of the sketch. There really isn't much value to having them in the .h file. If it is for documentation purposes, you could #define in the .h file, a symbol that expands to all of the pinMode() calls you need, then write that symbol at the appropriate place in your setup() function where it's expansion will be syntactically correct. This would accomplish the documentation, but at the cost of a reader of your code having to search for the definition of that symbol to find out what code is being executed there. That's pretty roundabout for what seems like little to no gain.

answered Feb 9, 2023 at 17:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.