Pages: [1]   Go Down
Author Topic: How to access Serial or SerialUSB dependent upon a variable? [solved]  (Read 440 times)
0 Members and 1 Guest are viewing this topic.
UK
Offline Offline
Jr. Member
**
Karma: 0
Posts: 89
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
« Last Edit: September 26, 2013, 01:35:08 am by Nick Gammon » Logged

France
Offline Offline
God Member
*****
Karma: 34
Posts: 987
Scientia potentia est.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello,

Use type HardwareSerial

Edit: What is SerialUSB?
« Last Edit: August 01, 2013, 09:21:34 am by guix » Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 11
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Perhaps you want this:

Code:
#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:
Stream *stream;

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

Global Moderator
Offline Offline
Brattain Member
*****
Karma: 474
Posts: 18696
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Pass a class derived from Stream by reference:

Code:
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 () { }
Logged

UK
Offline Offline
Jr. Member
**
Karma: 0
Posts: 89
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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  smiley-wink

Regards,

Graham
Logged

Pages: [1]   Go Up
Jump to: