First let me admit, I couldn't come up with a better subject.
I guess, the overall - more technical - question would be "How can I access identically named methods of objects from different classes?"
But let's stick with the actual problem:
Both hardware serial and software serial share the same methods (or at least the names and use are identical, such as Serial.read() vs mySerial.read or Serial.print("") vs mySerial.print("")
I would like to have a function communicate with me over either "Serial" of "SoftwareSerial", depending on what flag is set during the setup routine or what device I use (Arduino Mega / Uno).
How can I do this without many if's or switch statements - not to mention the compile error when using different microcontrollers?
SoftwareSerial mySerial(9,10);
void some_function(byte number_of_serial_port){
switch number_of_serial_port){
case 0: Serial.print("Serial"); break;
case 1: Serial1.print("Serial1"); break;
...
default: mySerial.print("SoftwareSerial");
}
}
Serial and Software Serial are both derived from Print, so you can use a pointer to either object:
Print *MyConsole;
if (USE_SERIAL)
MyConsole = new Serial(...);
else
MyConsole = new SoftwareSerial(...);
MyConsole->println("hello");
...
Regards,
Ray L.
What you can do is have a class that references the Stream class by what you enter into the constructor.
you can use the Print class too
My .h file.
//SerialServo.h
#ifndef SerialServo_h
#define SerialServo_h
#include <Arduino.h>
class SerialServo
{
Stream & port_; // #include madness - Programming Questions - Arduino Forum Reply #14
public:
// constructor
SerialServo (Stream & port) : port_ (port) { }
// methods
void Number_of_Channels(uint8_t channel = 4);
void Move(uint8_t channel, uint8_t position);
void AdjustLeftRight(uint8_t L, uint8_t R);
void Calibrate();
private:
uint8_t left, right;
unsigned int ServoNum[35];
};
#endif
Sketch setups
Hardware Serial:
#include <SerialServo.h>
SerialServo servo (Serial);
Software Serial:
#include "SerialServo.h"
#include <SoftwareSerial.h>
const byte TX = 5;
SoftwareSerial mySerial (-1, TX, false);
SerialServo servo (mySerial);
SerialServo.zip (2.84 KB)
You can have a direct reference to the Stream class, and make that refer to whatever class is derived from it, that you choose:
#include <Arduino.h>
#define USE_SOFTWARE_SERIAL 1
// choose a serial port
#if USE_SOFTWARE_SERIAL
#include <SoftwareSerial.h>
SoftwareSerial softSerial (3, 4);
Stream & mySerial = softSerial;
#else
Stream & mySerial (Serial);
#endif
void setup ()
{
// set up appropriate serial port
#if USE_SOFTWARE_SERIAL
softSerial.begin (9600);
#else
Serial.begin (115200);
#endif
// use serial port
mySerial.println ("Hello");
mySerial.println (42);
} // end of setup
void loop () { }