I have been breaking my project into .cpp and .h files. I am a bit confused about instances of objects.
For Instance (pun intended), If I wish to use the SoftwareSerial library in both my .ino main sketch and one of the .cpp files can I share one instance of the SoftwareSerial object? My head says yes, but I can't work out how to do it. I always end up with 'multiple definition of xyz' or ' was not declared in this scope' type errors.
**Example ** 1 instance of the SoftwareSerial object instantiated in hello.ino
// hello.ino
//INCLUDES
#include <SoftwareSerial.h>
#include "Arduino.h"
#include "world.h"
//DEFINES
// VARIABLE |AR. NUM. |PIN NAME |IC PIN |FUNCTION
//-----------------------------------------------------------------------------------------------------------------------
#define Soft_TXD 14 //PA1 17 Software Serial TXD
#define Soft_RXD 15 //PA2 18 Software Serial RXD
// INSTANTIATIONS
SoftwareSerial SoftSerial(Soft_RXD, Soft_TXD); //RX, TX
void setup() {
Serial.begin(9600); // Software Serial start
}
void loop()
{
SoftSerial.print("Hello "); // Print to softwareSerial
world.Print("world!"); // Send to world class to print to SoftwareSerial
}
// world.h
#ifndef _WORLD_h
#define _WORLD_h
class worldclass
{
public:
worldclass();
void Print(String);
};
extern worldclass world;
#endif
// world.cpp
#include "Arduino.h"
#include "world.h"
worldclass::worldclass() {}
void worldclass::Print(String) {
SoftSerial.print("world");
}
////////////////////////////////
worldclass world = worldclass();
RESULTS (which is to be expected)
world.cpp: 12:2: error: 'SoftSerial' was not declared in this scope
SoftSerial.print("world")
I can 'fix' it by creating another instance of the SoftwareSerial in the world.cpp file but then, as far as I understand it, I will have two instances in memory. That just seems wrong and I feel I should be able to use just one.
I think it may be something to do with using Extern in the .cpp file but I can not seem to get it to work with an object instance, only variables.