Go Down

Topic: How to access Serial or SerialUSB dependent upon a variable? [solved] (Read 545 times) previous topic - next topic

ghlawrence2000

Aug 01, 2013, 04:15 pm Last Edit: Sep 26, 2013, 08:35 am by Nick Gammon Reason: 1
Hello all,

I don't claim to be proficient at C++ or classes but I want to implement something like this :-

Quote

int serial;
int initserial(int x)
{
 if(!x)
 {
   serial=Serial;
 }
 else
 {
   serial=SerialUSB;
 }
 return serial;
}

void setup()
{
 initserial(0);
 serial.begin (115200);
 while(!serial);
 serial.println ();
 serial.println ();
}



Obviously this gives 100's of errors but could someone point me in the right direction please?

Thankyou.

guix

Hello,

Use type HardwareSerial

Edit: What is SerialUSB?

peebee

Perhaps you want this:

Code: [Select]
#ifdef __SAM3X8E__
#define SERIAL SerialUSB
#else
#define SERIAL Serial
#endif
...

setup()
  SERIAL.begin();
  while (!SERIAL) {}
  SERIAL.println("Hello");


The above doesn't use a variable, and is faster.  If you really want a variable, then
Code: [Select]
Stream *stream;

setup()
{
  if (flag)
    stream = &SerialUSB;
  else
    stream = &Serial;
  stream->println("Hello");
...


Nick Gammon

Pass a class derived from Stream by reference:

Code: [Select]

class myMenu
  {
  private:
    Stream & port_;
  public:
    myMenu (Stream & port) : port_ (port) { }
    void begin ();
  };

void myMenu::begin ()
  {
  port_.println ("Menu initialized.");
  }

myMenu menu (Serial);

void setup ()
  {
  Serial.begin (115200);
  menu.begin ();
  }  // end of setup

void loop () { }
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

ghlawrence2000

Nick, your answer was a little complex for my current knowledge level  :smiley-roll-blue: but thanks anyway! peebee, that was exactly what I was looking for  ;)

Regards,

Graham

Go Up