SparkFun Forums 

Where electronics enthusiasts find answers.

Have questions about a SparkFun product or board? This is the place to be.
By angelsix
#125652
Pretty simple requirement with same issue I keep coming across.

I create libraries in another shared folder for functions and libraries such as LCD screens, SPI, I2C etc... which contain .h and .c files in a library folder. These create the functions that are generic for use across projects, so for a simple example think of an SPI.c file that needs to know the pin to use as a CS pin. This would be done as

#define CS _LATB14

for example. Now if this was in the main.c file (main code file), and the main code file has an include to the SPI.h file, and then calls the SPI function within spi.c file that looks for a CS defined, then when you compile the spi.c file cannot find any definition for CS.

How would I get around it so I don't have to constantly copy/paste the library files and modify defines within those files directly.

spi.h
==============
void SPIFunction();

spi.c
==============
void SPIFunction()
{
CS = 1;
}

main.c
==============
#define CS _LATB14
#include "spi.h"

int main()
{
SPIFunction();

return 0;
}
By Polux rsv
#125654
To be completely configurable, you should use a #define for your register and the bit of CS
In main.c
#define CSRegister directportregister
#define CSbit portCSbit

In spi.c
extern typereg CSRegister;
extern typebit CSbit ;

CSRegister &= ~1<<CSbit ; // set CS to low to select device
CSRegister |= 1<<CSbit ; // set CS to high to deselect device

typereg and typebit are the type of your CS register and bit, depending of your uC and compiler.


Angelo

P.S. not sure it is 100% ok, but you get the idea
User avatar
By viskr
#125666
Usually you would #include "spi.h" in the spi.c file. Register definitions can be there, but its more customary to have a device specific register header like "LPC1756.h"

And also why to avoid multiple define warnings you do this in the headers

spi.h file

#ifndef SPI_HEADER
#define SPI_HEADER

... whatever is in the spi.h file

#endif