I am creating an Arduino library to retrieve ranging data from the LV-MaxSonar-EZ1. The data can be gotten using Pulse Width, Analog, and Serial (inverted RS232). The library will create a connection to the sensor based on the constructor parameters. I am using SofwareSerial to make the serial connection, and it works, but I would like to not instantiate a SoftwareSerial object if the library is being used in the Pulse Width or Analog modes.
The following code will get the serial data successfully:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(7, 11, true);
void setup() {
Serial.begin(57600);
while (!Serial) { ; }
mySerial.begin(9600);
while (!mySerial.isListening()) { ; }
}
void loop() {
if (mySerial.available())
Serial.write(mySerial.read());
if (Serial.available())
mySerial.write(Serial.read());
}
This returns the serial ranging data of the form Rxxx, where xxx is the range in inches:
I was trying to use a pointer for later instantiation of SoftwareSerial, but it only returns white space in the console, here is the code:
#include <SoftwareSerial.h>
SoftwareSerial* mySerial;
void setup() {
Serial.begin(57600);
while (!Serial) { ; }
mySerial = &SoftwareSerial(7, 11, true);
mySerial->begin(9600);
while (!mySerial->isListening()) { ; }
}
void loop() {
if (mySerial->available())
Serial.write(mySerial->read());
if (Serial.available())
mySerial->write(Serial.read());
}
I have tried in my library to use a static variable, a null pointer, and several other fruitless methods. What other way can I have the SoftwareSerial object be created only when using the serial mode?
I don't think this is the way to test if the serial port is available. If the Serial object was created successfully (should be the case), it does nothing. If it wasn't, it could be an infinite loop.
For the dynamic creation of an object, use the new keyword instead of a &. New will return a pointer to an object.
Be aware that using dynamic memory allocation in a system with very little RAM can lead to the system running out of RAM. Memory use can become inefficient.In a lot of cases, you are better off using static allocation.
By the way, if you want to make the decision at compile time, you can use #define and #ifdef
Thank you both for your help. The following code now brings back MaxSonar-EZ1 data via serial, while initializing SoftwareSerial after instantiation. My library still has a lot of kinks to work out, but the proof of concept sketch works.
#include <SoftwareSerial.h>
SoftwareSerial* mySerial;
void setup() {
Serial.begin(57600);
while (!Serial) { ; }
mySerial = new SoftwareSerial(7, 11, true);
mySerial->begin(9600);
while (!mySerial->isListening()) { ; }
}
void loop() {
if (mySerial->available())
Serial.write(mySerial->read());
if (Serial.available())
mySerial->write(Serial.read());
}