Go Down

Topic: Using serial.print to debug a library (Read 1 time) previous topic - next topic

PaulS

Quote
It should look like this:

Really? No need to include MyLibrary.h?

fretless_kb

Thanks I will try these and re-post.  Just a quick response, when I included the MyLibrary.h file in the .cpp file I got duplicate class definitions.  That should have been telling in the first place. but I haven't used C++ in almost 15 years.

PaulS

Quote
Just a quick response, when I included the MyLibrary.h file in the .cpp file I got duplicate class definitions.

The #ifndef/#define/#endif statements prevent multiple inclusions of the same code. That is why the class definition is between the ifndef statement and the endif statement. Moving the endif statement to the top of the file made the guard useless, since it was no longer guarding anything.

fretless_kb

O.k. Got the point on the guard, I actually needed 2 #endif at the end.  I got the code to compile, but it does not print to the serial port. I had to change the baud rate from the previous example to match my current setup:

Here's the final three pieces which compile. 
.ino ( I added a call to test and a delay in the loop)
Code: [Select]
#include "MyLibrary.h"

MyLibrary myLibrary(Serial);

void setup() {

  myLibrary.test();
}
void loop() {
  myLibrary.test();
  delay(1000);
}


.cpp (Corrected, thanks for the corrections, I did need to include MyLibrary.h)
Code: [Select]
#include "MyLibrary.h"
#include "HardwareSerial.h"

    //pass a reference to a Print object
    MyLibrary::MyLibrary( HardwareSerial &print ) {
      printer = &print; //operate on the address of print
      printer->begin(115200);
    }
    void MyLibrary::test() {
      printer->println("Hello library with serial connectivity!");
    }


And Header with the second #endif added to the bottom of the file
Code: [Select]
#ifndef _MYLIBRARY_H
#define _MYLIBRARY_H
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

class MyLibrary {
  public:
    //pass a reference to a Print object
    MyLibrary( HardwareSerial &print );
    void test();
  private:
    HardwareSerial* printer;
};
#endif


Now to try to find out why it doesn't output anything to the port. - Thanks again - Kb

PaulS

Quote
Now to try to find out why it doesn't output anything to the port.

Well, that's easy. When is your class constructor called? When is the HardwareSerial constructor called? You don't know, do you? Therefore, you should not write code that relies on them being called in the correct order.

You need a begin() method in your class. You pass nothing to the constructor. You pass a serial instance to the begin method. You call the begin method in the setup() function.

Go Up