(Solved) Can't get class-version working

Hello,

a very simple example based on OneWire library example, which is perfectly working:

#include <OneWire.h>

OneWire iBReader( 7 ); // on pin 7

void setup()
{
  Serial.begin( 9600 );
}

void loop()
{
  byte addr[ 8 ];

  iBReader.reset_search();
  if( iBReader.search( addr ) )
    for( int a = 0; a < 8; Serial.print( addr[ a++ ], HEX ) ); // print data

  delay( 1000 );
}

I need class oriented approach so I wrote this:

#include <OneWire.h>

class testClass
{
public:
  // constructor
  testClass(int pin) {
    testWire = &OneWire( pin );
  }

  // variables
  OneWire *testWire;
};

testClass testObject( 7 ); // on pin 7

void setup()
{
  Serial.begin( 9600 );
}

void loop( void )
{
  byte addr[ 8 ];

  testObject.testWire->reset_search();

  if( testObject.testWire->search( addr )  )
    for( int a = 0; a < 8; Serial.print( addr[ a++ ], HEX ) ); // print data

  delay( 1000 );
}

This does not work at all (no output to serial)! Not sure what is wrong. Is it possible that the scope of declaration “OneWire( pin )” is only the constructor and testWire points to non-existing object?

No compile errors in both versions.

Can you advice please? Thanks.

I think what you're looking for is an initialiser list. Search around the forum and you should find what you need. Basically your testClass constructor needs to look like this:

class testClass
{
public:
  // constructor
  testClass(int pin) : testWire(pin) {
  }

  // variables
  OneWire *testWire;
};

I've read about it on the forum. In Arduino-land the constructors aren't called in the correct order when you call one constructor from another. The initialiser list gets the sequence right.

I hope this fixes it for you. ;)

You may want to look at this one: http://www.arduino.cc/en/Hacking/LibraryTutorial

Because there are a few things wrong with your code, and I believe that you just need to look over the tutorial again.

:)

Prawnhead, it works! Thank you.

InvalidApple, I read that tutorial. Can you be more specific please what is wrong with code above with respect to that tutorial? Thanks.