Using SPI library inside a custom library

Hi All!

I'm writing a library that use a SPI por to control a SPI shift register.

Now when inside my library.cpp project call SPI.begin(), it fails and give me this message:

HRFM.cpp:32: undefined reference to SPI' HRFM.cpp:32: undefined reference toWSPI::begin()' HRFM.cpp:32: undefined reference to `WSPI::begin()' :o

I test too to force the constructor using WSPI SPI; but the error still there.. what i need to do and what will be the best way to include already wroted libraries to a custom library. :P

Best Regards Frank

What include files are included in your sketch? The Arduino compiler only compiles libraries referenced by the sketch. If a library referenced by a sketch references a library not referenced by the sketch, that library will fail to compile (as you've seen happen).

AT .H file:

#ifndef HRFM_h
#define HRFM_h

#include “SPI.h”
#include “WProgram.h”

… class declaration, public functions… etc


At CPP file:

#include “HRFM.h”
#include <string.h>
#include <avr/pgmspace.h>
#include “SPI.h”

Class data…constructor etc.

HRFM::Init(){
SPI.begin();
}


at sketch file:
#include “HRFM.h”

HRFM Radio;
Radio.Init();

at scketch i only inlcude the main .h file and not more else. May be i must copy the SPI.h and SPI.ccp content to my library?.. veeery ugly but it will work! :-/

Best regards
Frank

No, there is no need to copy the SPI.h and SPI.cpp files anywhere. You need to, in the sketch, #include "SPI.h", too.

You can't call Radio.Init() outside of a function, either.

Hi Paul!

Yes now is working! Is my first project designing clases and now i got 2 custom clases working at the same project!

I want to atach a interrupt too at this class and the atachinterrupt function do not like somethig...

Code: attachInterrupt(0, getbuffer , FALLING);


HRFM.cpp: In member function 'void HRFM::Init()': In member function 'void HRFM::Init()'

HRFM.cpp:33: error: argument of type 'void (HRFM::)()' does not match 'void (*)()'

error: argument of type 'void (HRFM::)()' does not match 'void (*)()'


The function to be called is: HRFM::get

I'm not including any interrupt header... i'm testing now that issue..

Best Regards Frank

Just so that you are aware, you can not call a member function in an interrupt handler. If there are multiple instances of the class, which instance's method should be called?

To get around this, you can declare the method to be static (so that it is shared by all instances of the class. This will lead to other issues, though, in that you can not access non-static fields of a class from a static function.

If the ISR must be a member of the class, you have essentially limited the class to being a singleton.