Go Down

Topic: How to access Serial or SerialUSB dependent upon a variable? [solved] (Read 611 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

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy