Go Down

Topic: Using a SoftwareSerial port within a library (Read 931 times) previous topic - next topic

yakirg

I am trying to use the OBD library from http://www.arduinodev.com/hardware/obd-kit/#library
The library .cpp file starts with 
Code: [Select]
#ifndef OBDUART
#define OBDUART Serial
#endif

So I assumed that I need to add a #define in my sketch file to say:
Code: [Select]
#define OBDUART mySerial

But it doesn't work. When it compiles the library it doesn't use the #define from the sketch file.

Any idea how I can make the library use the defined serial port from the sketch?

PaulS

Quote
Any idea how I can make the library use the defined serial port from the sketch?

The short answer is that you can't. The sketch and the library are in different compilation units, compiled at different times. A pre-processor directive from one file can not be used in another.

johnwasser

If you want the library to be able to take a pointer to a HardwareSerial or SoftwareSerial you can change the library to use a "pointer to Stream".  Then you can take your serial object (Serial, Serial1, mySerial, etc.) and pass it to the library.  Since  HardwareSerial and SoftwareSerial both derive from Stream the library can use the pointer without knowing which kind of "Stream" it is.
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

yakirg

YeeeHaa!
Got it!!
I passed a pointer to a stream to the Init funciton, and saved it in the class, and it works!!!

10x, all who answered! The short answer would have been enough for me (about 20 years experiance in SW), but the second one made sure I get it done in 2 minutes!

Hi yakirg,

I'm having the same issue as you and was wondering what your exact solution was?

I attempted to do the same workaround as you, wish I had of found this post a few hours ago, but now understand why it won't work.

However as I'm very new to Arduino (started today, but have a reasonable grasp of programming) I just had a couple of questions of how you achieved your solution.

Firstly, I understand a Steam is a base class but I don't understand how you would pass something to it?

When you say you passed it to the Init function, did you have to change the init function to include the OBDUART definition?

Any help you could give me would be fantastic. Also apologies for my lack of knowledge on the subject.

JSSD

Can somebody give me a little bit more information on how to solve this problem? I'm experiencing the same problems... Thanks

Go Up