Go Down

Topic: Creating libraries in Arduino sketch folder (Read 661 times) previous topic - next topic

X_Y

I'm creating a few classes for a project, which seems so specific that I don't want to keep in the libraries folder. They're mostly working, however, if I want to call any Arduino functions or consts, it will throw errors "is not declared in this scope".

sketch:

Code: [Select]
#include "MyClass.h"
void setup(){
}
void loop(){
}
MyClass.h

Code: [Select]
class MyClass{
    public:
        MyClass(int inp);
        int myFun();
};
MyClass.cpp

Code: [Select]
#include "MyClass.h"
#include <WProgram.h>

MyClass::MyClass(int inp){
    pinMode(13,HIGH);

}
error:

MyClass.cpp: 'HIGH','pinMode' is not declared in this scope.

It wouldn't happen if I put the libraries in libraries folder though. Wondering if there's a way to include arduino functions into sketch folder libraries?

pYro_65

First upgrade your IDE to 1.0 or above, if done

replace #include <WProgram.h> with
#include <Arduino.h>

X_Y

Thanks @pYro_65, just figured it out after getting stuck somewhere else for a couple of hours :D
I saw someone using the following in his library:
Code: [Select]
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

Which may be a even better solution.
But changing the library name is pretty bad for backwards compatibility though

johncc

On the contrary, this would detect which Arduino version your library is being compiled in, and uses the appropriate Arduino include file. The name of the arduino library changed ( before version 1.0 it was WProgram.h and since 1.0 it is Arduino.h).

If you're expecting to share your library with others and believe/expect/confirm that your library works with previous Arduino versions (e.g. 0023 ), then put the if/then construct there.  If you're not intending to share it with others and/or you're only using 1.0.x and later, it doesn't really matter--you could just use the Arduino.h...

HTH,
John

PaulS

Code: [Select]
MyClass::MyClass(int inp){
    pinMode(13,HIGH);

}

When will your constructor be called? When will init() be called to set up the hardware?

If you can not answer these questions definitively, you should not be doing hardware-related stuff in your constructor.

X_Y

Interesting...
The example is just for showing my problem regarding undeclared functions, so it doesn't have real purpose. However I never thought about the potential problem between constructor and hardware. Thank you for the extra knowledge! :) So what problems can there be?

PaulS

Quote
So what problems can there be?

Your constructor gets called when the object is instantiated. If that happens at global scope, it will happen before init() is called. You set the pin to be an OUTPUT pin. Then, init() gets called, and it KNOWS that pins are to be INPUT, so it changes the pin to an INPUT pin.

Then, your class tries to turn the LED on and off, and it won't be very bright.

Go Up