Electronic – arduino – Call Serial.print in a separate tab/header file

arduinoc

I'm writing a program in Arduino 0022.

Calling Serial.println works fine in my main sketch code, but when I attempt to use it in my header file "Menu.h", which is in a separate tab, I get an error:

In file included from AppController.cpp:2:
Menu.h: In constructor 'Menu::Menu()':
Menu.h:15: error: 'Serial' was not declared in this scope

How can I use Serial.println outside of sketch code?

Best Answer

You should not be calling functions from within header files. Header files are for defining pre-processor macros (#define) and references to variables / functions in other files.

You should be creating multiple C files and linking them together at compile time. The header file is used to tell each C file what functions and variables the other C files have.

To use multiple files in the Arduino IDE you require at least 1 header file to describe the functions that are in the other files that you want to share between them. Also, any global variables that you want to use across all files.

These definitions should be qualified with the "external" attribute.

Then you need to add one or more "pde" file which contains the actual code and variable definitions for the functions.

For instance, I have a "mouse.h" file:

extern void mouse_read(char *,char *, char *);
extern void mouse_init();

and a "mouse.pde" file:

#include <ps2.h>

PS2 mouse(6,5);

void mouse_read(char *stat,char *x, char *y)
{
  mouse.write(0xeb);  // give me data!
  mouse.read();      // ignore ack
  *stat = mouse.read();
  *x = mouse.read();
  *y = mouse.read();
}

void mouse_init()
{
  mouse.write(0xff);  // reset
  mouse.read();  // ack byte
  mouse.read();  // blank */
  mouse.read();  // blank */
  mouse.write(0xf0);  // remote mode
  mouse.read();  // ack
  delayMicroseconds(100);
}

Then in my main file I have:

#include "mouse.h"

and I can call the functions that are in "mouse.pde" as if they were in the local file.