Arduino Forum

General Category => General Discussion => Topic started by: PaulMurrayCbr on Dec 28, 2015, 05:21 am

Title: Arduino the Object Oriented way
Post by: PaulMurrayCbr on Dec 28, 2015, 05:21 am
I response to many and various threads on this programming boards, I have done a bit of a write-up on how to go about doing Arduino projects by treating the components of your sketch as objects.

The write-up is here on github.

ArduinoTheOOWay.html (http://paulmurraycbr.github.io/ArduinoTheOOWay.html)

Don't know if it's any use to anyone, but I'd like to hope so.
Title: Re: Arduino the Object Oriented way
Post by: TomGeorge on Dec 28, 2015, 05:40 am
Hi,

Thanks mate, have just copied it , will do some holiday reading  and experimenting.
Looks good on just a quick scan.

Tom.... :)
Title: Re: Arduino the Object Oriented way
Post by: CrossRoads on Dec 28, 2015, 05:59 am
Couple of nit comments:

Why int here and not byte?

const int BUTTON_PIN = 7;

Same with state, prevState, pin. variables that are only 0/1 don't need to be ints, and there are no pins above 255, so they also don't need to be int. You have int's all thru the example that could be byte instead.

I like the explanation you provide.  This looks like stuff I just code inline in my sketches. MrsCrsossRoads ridicules me for it, but I figure I'm saving processing time by  not jumping back & forth in &  out of functions, just performing the simple digitalWrite of whatever is starting the class. Also I don't want to take the time to create all that stuff every time, nor can I remember how every class created over the years is used. Basically sounds like I'm a lazy, not too bright coder! I think having to figure that stuff out every so often helps me to keep thinking about what's really going on tho.
My fencing scoring machine is 25 pages long of code - no functions except setup() and loop(). No classes, etc. The code acts like it tho with a couple of flags to indicate between sections that something needs performing - when a score is updated for example, the score variable is updated, a displayUpdate flag is set - the updateScore test gets its shot and checks the flag and updates the display as needed, clearing the flag.
All the code is inline, and if you read it it's basically what someone might write as 3 functions:
void loop(){
checkRFinput();
checkTouchInput();
updateTimeScoreDisplay();
}
However, I also don't like jumping back and forth in a sketch trying to find a section that is referenced, which also leads to my preference for inline code.
Chalk it up to poor programming preferences by a hardware designer looking for speed over code niceness.

Title: Re: Arduino the Object Oriented way
Post by: PaulMurrayCbr on Dec 28, 2015, 06:43 am
Couple of nit comments:

Why int here and not byte?

const int BUTTON_PIN = 7;

Same with state, prevState, pin. variables that are only 0/1 don't need to be ints, and there are no pins above 255, so they also don't need to be int. You have int's all thru the example that could be byte instead.
I use an int because the pinMode and digitalWrite functions take ints.

In justification: the arduino is a 16-bit processor, so it's all just one bus read anyway. Using ints means that things wind up on even byte boundaries, which might be a good thing (It was a thing back in the day on x86 processors). If your sketch is just one byte short of being able to fit into ram, you probably need a mega.

If you have big arrays then that's a different story, agreed.

I like the explanation you provide.  This looks like stuff I just code inline in my sketches.
Absolutely. Classes just provide a way of organising your code. The difference between using classes and not using them is like the diference between using block-structured code and using gotos. Block-structured languages happened because people started noticing that coders followed consistent idioms when writing loops, ifs, and all the rest. Classes are the same - they are formal support in the language for things that people are doing anyway.

MrsCrsossRoads ridicules me for it, but I figure I'm saving processing time by  not jumping back & forth in &  out of functions,
Yeah, there are inefficiencies doing it this way because class methods can't assume an absolute location for your variables. In fact, the memory address of the instance is passed invisibly to every method. If you need hand-tuned speed, working this way won't do the job. But, it's not that bad. At a guess, the instance address goes into a register, and the generated code uses register-relative addresses.

If microseconds matter then this pattern is not suitable, and for some microcontroller projects, microseconds do matter. The really high-speed arduino stuff with be working with interrupts and ports. Even then, however, it can make sense to use classes to do things that operate at human speed - manual switches, blinky lights.

The main benefit is that you can code up complex things that mostly work first time, without burning out your brain keeping track of all the possible permutations of state in your system.
Title: Re: Arduino the Object Oriented way
Post by: CrossRoads on Dec 28, 2015, 07:03 am
"I use an int because the pinMode and digitalWrite functions take ints."
" Using ints means that things wind up on even byte boundaries, which might be a good thing "

In the datasheet 8.3 SRAM Data Memory shows the SRAM Memory as 2048 x 8 in Figure 8-3. Data Memory Map, which would seem to be in disagreement with the latter statement.

And this also says to me that ints are not required to use SRAM bytes directly:
 "The direct addressing reaches the entire data space.
The Indirect with Displacement mode reaches 63 address locations from the base address given by the Y- or Zregister.
When using register indirect addressing modes with automatic pre-decrement and post-increment, the address
registers X, Y, and Z are decremented or incremented."








Title: Re: Arduino the Object Oriented way
Post by: PaulMurrayCbr on Dec 28, 2015, 07:09 am
In the datasheet 8.3 SRAM Data Memory shows the SRAM Memory as 2048 x 8 in Figure 8-3. Data Memory Map, which would seem to be in disagreement with the latter statement.
Ok. Use bytes, then.
Title: Re: Arduino the Object Oriented way
Post by: RayLivingston on Dec 28, 2015, 07:11 am
I use an int because the pinMode and digitalWrite functions take ints.

In justification: the arduino is a 16-bit processor, so it's all just one bus read anyway. Using ints means that things wind up on even byte boundaries, which might be a good thing (It was a thing back in the day on x86 processors). If your sketch is just one byte short of being able to fit into ram, you probably need a mega.
All of which is neither here nor there.  If the value will fit into a byte, there is no benefit whatsoever to putting it into an int.  The compiler will cast it to an int when passed to a function that takes an int.  And worrying about byte alignment is equally pointless.  The compiler will automatically enforce any memory alignment requirements imposed by the processor architecture.  You don't need to "help" it.  

Bottom line, you're wasting RAM, without getting anything whatsoever in return.

Regards,
Ray L.
Title: Re: Arduino the Object Oriented way
Post by: PaulMurrayCbr on Dec 28, 2015, 08:08 am
I cant help feeling that people responding on this thread are missing the point a little.
Title: Re: Arduino the Object Oriented way
Post by: Camel on Dec 28, 2015, 08:18 am
I cant help feeling that people responding on this thread are missing the point a little.
I feel ya buddy  :) It's a good write up.
Title: Re: Arduino the Object Oriented way
Post by: Robin2 on Dec 28, 2015, 10:03 am
I have bookmarked your link - thank you for taking the time to write a clear and simple tutotial.

That said, I always have the feeling that OOP is bolted onto C as an afterthought. It is constantly in my mind "I don't actually need all this s**t"

Whereas, in Ruby EVERYTHING is an object and you can't NOT use objects. However that does not require you to create classes just to do simple things with Ruby. If you create variables that "appear" to be outside any class they are actually part of a class (forget what it is called). This makes it very easy (in the Arduino sense of easy) to get started with Ruby.

I gave up Ruby in favour of Python because Python is more widespread (at least in the Arduino community) and because Python is better integrated with its environment (e.g. there is only one pySerial that works on all platforms). But OOP in Python has the same "bolted-on afterwards" feel as it has in C/C++.

The best example I know of how OOP can kill the will to live is Java - even though I think the JVM is excellent. I wonder how many people have given up programming completely because their first exposure was to Java.

...R
Title: Re: Arduino the Object Oriented way
Post by: pYro_65 on Dec 28, 2015, 10:49 am
Yes Robin, we have all heard many times how you prefer doing things with out classes etc... (sometimes the hard way, just because code is inside a class and may not expose a newbie to every concept used inside it).

Your very biased attitude towards interfaces and objects is most probably what is holding you back. It seems you gave up on them before learning enough to see the real benefit in using them for what they are.

Being able to encapsulate a few features like shown in these examples is only scraping the surface. The C++ type system is built around having the ability to extend it.

If you need a feature/type that is not provided in the standard, you can make it. By using operators correctly you can create new types which leave your top level code (sketch) looking like nothing more than a C program. None of which has anything to do with the object orientated paradigm (that's all it is, an idea, a method of using classes a certain way, not a requirement).

The more you learn, the more you'll see their benefit (the learning curve isn't really a reason to hide it from newbies either).
Title: Re: Arduino the Object Oriented way
Post by: combie on Dec 28, 2015, 11:22 am
Quote
I use an int because the pinMode and digitalWrite functions take ints.
No.

Code: [Select]
void digitalWrite(uint8_t pin, uint8_t val)
.....

void pinMode(uint8_t pin, uint8_t mode)
....

See: wiring_digital.c
Title: Re: Arduino the Object Oriented way
Post by: Robin2 on Dec 28, 2015, 11:26 am
Yes Robin, we have all heard many times how you prefer doing things with out classes etc.
I think my comments are as reasonable as yours are, but I have not made any personal criticisms.

...R
Title: Re: Arduino the Object Oriented way
Post by: pYro_65 on Dec 28, 2015, 12:16 pm
I think my comments are as reasonable as yours are, but I have not made any personal criticisms.

...R
You're opinions are just as valid as the next persons.

I'm not criticising you personally, I'm criticising your opinions you openly voice regularly on the forum regarding classes/objects. Refuting an opinion is not an attack on the person voicing the opinion.

I'm sorry if you feel like I'm attacking you, It just seems like you constantly argue your opinion against a topic which is well and truly proven beneficial by millions of programmers. So I feel it appropriate to argue against it... Fair?

And many times I've seen posts with people offering new ideas or concepts using classes only to have their work criticised because what it offers can be done without a class. And sometimes it has ended up with you mentioning that you do not fully understand the concepts being used. Which is fine, but still a biased influence.
Title: Re: Arduino the Object Oriented way
Post by: PaulMurrayCbr on Dec 28, 2015, 12:37 pm
No.

Code: [Select]
void digitalWrite(uint8_t pin, uint8_t val)
.....

void pinMode(uint8_t pin, uint8_t mode)
....

See: wiring_digital.c
Well, that's different then. I have modified the page.
Title: Re: Arduino the Object Oriented way
Post by: PaulMurrayCbr on Dec 28, 2015, 12:46 pm
That said, I always have the feeling that OOP is bolted onto C as an afterthought.
You are absolutely right - it was. C++ was originally a preprocessor that generated C, back in the day. I learned C back in '85 from the K&R blue book - no fancy objects and constructors back then. Likewise, closures and streams are bolt-ons to Java. Things change.
Title: Re: Arduino the Object Oriented way
Post by: Camel on Dec 28, 2015, 01:10 pm
C++ is certainly not 'C with extras' any more. Modern C++ features such as ranged loops, lambda functions, auto type deduction and so on really make C++ a high-level language without really sacrificing much, if anything, in terms of performance.
Title: Re: Arduino the Object Oriented way
Post by: Robin2 on Dec 28, 2015, 03:22 pm
You're opinions are just as valid as the next persons.

I'm not criticising you personally,
When you use the words "Yes Robin, we have all heard many times" and "Your very biased attitude" it is hard to escape the feeling that the comments are personal, and will be seen as such by others.

It would not have been difficult to say "I disagree with XX and I prefer to do things YYY"

I am quite happy to accept that there is no personal animosity.

...R
Title: Re: Arduino the Object Oriented way
Post by: westfw on Dec 29, 2015, 05:12 am
Quote
In justification: the arduino is a 16-bit processor
No, it's an 8 bit processor (except for the ones that are 32bit processors.)



Quote
Modern C++ features such as ranged loops, lambda functions, auto type deduction and so on really make C++ a high-level language without really sacrificing much, if anything, in terms of performance.
I'd like to see an Arduino example using one or more of those.  An awful lot of the time, for C++ programmers, "no performance sacrifice" means "if your actual data was 1MB, encapsulating it all in a useful and elegant C++ container only adds another 100k, and obviously 10% is not very significant" rather than "the object overhead fits in 2k with plenty of room for actual data."

Title: Re: Arduino the Object Oriented way
Post by: msssltd on Dec 29, 2015, 11:46 am
Don't know if it's any use to anyone, but I'd like to hope so.
As an OOP tutorial held up to novices, the article is highly opinionated, dubious even, in places.

Especially.


"The problem is that there are then two places [where a click is started]"
The redundancy can be reduced logically, by sticking to a read/modify/write pattern.

I see no tangible benefit in the Runnable class.  As such, the class adds unnecessary complexity, consuming RAM and clock cycles needlessly.

Personally I would not call simple inheritance polymorphism, even with virtual functions - It's simply, inheritance.   Multiple inheritance and overriding methods, would be examples of polymorphism, to my mind.

"It's called 'time-slicing'"
No, not really.  Time-slicing is an established term, which implies pre-empting, by a scheduler.


As a set of notes documeting your thought process, I think the article is great.

"Writing this stuff is much quicker and easier than writing about it."
On which, we are in full agreement.


Title: Re: Arduino the Object Oriented way
Post by: pYro_65 on Dec 29, 2015, 05:46 pm
Personally I would not call simple inheritance polymorphism, even with virtual functions - It's simply, inheritance.   Multiple inheritance and overriding methods, would be examples of polymorphism, to my mind.
Using virtual functions is by definition polymorphic behavior. The derived class is overriding the virtual functions declared in the base.

If you were simply extending another class by using it as a base and adding further functionality in the derived class, then its just simple inheritance.

The write up is not bad, but I think the examples could be far simpler. The functionality inside the classes is going to draw attention away from the actual points the article is trying to explain.
Title: Re: Arduino the Object Oriented way
Post by: PaulMurrayCbr on Dec 30, 2015, 09:07 am
As an OOP tutorial held up to novices, the article is highly opinionated, dubious even, in places.
Agreed. It's my opinion, it's the way I write things, it's a specific way I use OO with arduino (specifically: giving everything a setup and a loop). Maybe I should put a caveat to that effect towards the beginning.

Especially.
  • Neglecting to mention the cost of OOP.
  • Overuse of private properties
  • brightnessClicker 'should' [not] be a property of headlamp - Breaks the MVC pattern.
  • Calling millis() repeatedly
  • Blocking a refresh method for 800,000 clock cycles.

I don't see what's wrong with making things private.

And it doesn't make sense to complain that OOP is expensive, and to be peevish that I don't use MVC everywhere. Yes, you can do make event queues and whatnot that malloc space for event objects. Not worth it. And in any case, I state repeatedly that this sort of stuff is not suitable for anything where cycles are important.

As to not making brightness clicker part of headlamp by direct composition - I just disagree. It's a fine way to do (some) things. Direct composition doesn't in itself break MVC. If this sort of composition does break MVC and composition by reference doesn't, isn't it a little odd that the syntax and method calls you need to make are otherwise identical?

Not sure that calling millis() repeatedly is a problem. How much work is it, compared to passing it around on the stack or leaving it in a sketch-scoped variable? I would have thought that millis() talks pretty directly to the chip somewhere, straight to a hardware port.

I used to take millis() once and pass it into the loop() for everyone, but eventually decided that the whole point is that these things shouldn't need to synchronize.

Quote
"The problem is that there are then two places [where a click is started]"
The redundancy can be reduced logically, by sticking to a read/modify/write pattern.
Yes, my code doesn't strictly adhere to a pattern. I like using an enum for states and having a loop that is strictly that switch statement and nothing else.

Maybe I should pull out and make explicit that some methods are smalltalk-style 'messages' intended to be called by other things, that they comprise an interface to the object.

Quote
I see no tangible benefit in the Runnable class.  As such, the class adds unnecessary complexity, consuming RAM and clock cycles needlessly.
Well, there are intangible benefits to it. Helps clarify what you are doing, I think. Actually, the real reason is that Runnable and its automatically-populated queue in effect provide a higher-level framework than the sturdy old setup() and loop() methods on their own.

Quote
Personally I would not call simple inheritance polymorphism, even with virtual functions - It's simply, inheritance.   Multiple inheritance and overriding methods, would be examples of polymorphism, to my mind.
Perhaps I need to point out that the benefit of the polymorphic button class is that you could write a class that does something different on a long click and short click, and that you wouldn't need to rewrite the "debounce/short/long click" logic again.

Quote
"It's called 'time-slicing'"
No, not really.  Time-slicing is an established term, which implies pre-empting, by a scheduler.
Wikipedia agrees. What do you call multitasking by way of yielding control, then? Actually, I'll ask wikipedia. … Hmm, "co-operative multitasking" seems to be the thing to call it.

Title: Re: Arduino the Object Oriented way
Post by: westfw on Dec 30, 2015, 11:30 am
Quote
"co-operative multitasking" seems to be the thing to call it.
Also "Run to completion scheduler."

Title: Re: Arduino the Object Oriented way
Post by: Robin2 on Dec 30, 2015, 11:53 am
I have been a fan of OOP ever since I came across Smalltalk many many years ago - at a time when I could not afford the compiler.

Alas IMHO this discussion has evolved to neatly illustrate a big problem. The people who know OOP can't resist talking about it in technical terms that make it completely inaccessible to beginners.

I do realize that (for example) the engineers who design a motor car need to know a great deal of technical stuff that the average car owner does not even know exists. But the beauty of cars is that their user-interface is easily understood and is the ONLY thing that 99% of the users are aware of.

I also realize that this Forum is used by programmers (the equivalent of the car design engineers) and it is natural that they should converse among themselves in technical jargon.

What is missing here, however, is the layer provided by the marketing system in the motor industry which effectively isolates the user from the engineering jargon.

If @PaulMurrayCbr's contribution is to be useful for newcomers (as I think was the original intention - at least, for newcomers to OOP) then it seems to me there needs to be scope to present it separately from the technical discussion that has been taking place in this Thread.

...R
Title: Re: Arduino the Object Oriented way
Post by: msssltd on Dec 30, 2015, 01:10 pm
@pYro_65
Using virtual functions is by definition polymorphic behavior.
Fair comment.

Quote
The write up is not bad,
It's not bad but it's not good either.

Quote
I think the examples could be far simpler.
Agreed.  I started skimming when I got to the tail light.  I think few would read so far, unless they were building exactly the same project.

@Robin2
Quote from: Robin2
The people you know OOP can't resist talking about it in technical terms that make it completely inaccessible to beginners.
When someone says, this is how it should be done, when in truth, this is how it could be done, you are going to end up with a technical discussion.

Quote
What is missing here, however, is the layer provided by the marketing system in the motor industry which effectively isolates the user from the engineering jargon.
Disagree.  What is missing here is technical critique and peer review.




Title: Re: Arduino the Object Oriented way
Post by: msssltd on Dec 30, 2015, 03:25 pm
Agreed. It's my opinion, it's the way I write things, it's a specific way I use OO with arduino (specifically: giving everything a setup and a loop). Maybe I should put a caveat to that effect towards the beginning.
What you do is not a million miles from what I do.  A caveat is an excellent idea.

Quote
I don't see what's wrong with making things private.
As you say in your comments,
    // make these slow for testing
If you can think of a need to change the values, the properties should not be private.  Further, private properties block inheritance and code reuse, which can be very frustrating.

Quote
And it doesn't make sense to complain that OOP is expensive,
I'm not complaining.  Abstraction costs RAM and clock cycles, it's a fact.

Quote
As to not making brightness clicker part of headlamp by direct composition - I just disagree. It's a fine way to do (some) things. Direct composition doesn't in itself break MVC. If this sort of composition does break MVC and composition by reference doesn't, isn't it a little odd that the syntax and method calls you need to make are otherwise identical?
I think it odd that a second instance of headlamp comes with a second instance of brightnessClicker - That would be the proof of MVC being broken.

Quote
Not sure that calling millis() repeatedly is a problem.
Concurrency is, or could be, the problem.

Quote
Yes, my code doesn't strictly adhere to a pattern.
I don't have a problem with your code.  I am contending your use of 'should' and 'of course.'  MVC is about the most common hardware control rationale out there.  OOP can make MVC implementation much easier.  The onus would be on you to explain why MVC 'should' be ignored.  Alternatively, you could mention it exists and point out your example is too trivial to warrant strict adherence.

Quote
Well, there are intangible benefits to it [the runnable class].
On an 8 bit micro?  No, I don't think there are any benefits, intangible or otherwise.  Art for art's sake.  Complication for complication sake, in my opinion.

Quote
Hmm, "co-operative multitasking" seems to be the thing to call it.
I almost called it co-operative tasking.  I very deliberately did not call it multitasking, of any kind.


Title: Re: Arduino the Object Oriented way
Post by: Robin2 on Dec 30, 2015, 05:33 pm
Quote
What is missing here, however, is the layer provided by the marketing system in the motor industry which effectively isolates the user from the engineering jargon.
Disagree.  What is missing here is technical critique and peer review.
Disagree. What you have said is correct. But it is quite different from the needed separation between users and developers - for the benefit and convenience of users.

In my experience it can be very difficult to get developers (in any field) to appreciate the very different perspective of users.

...R
Title: Re: Arduino the Object Oriented way
Post by: msssltd on Dec 31, 2015, 11:58 am
Disagree. What you have said is correct. But it is quite different from the needed separation between users and developers - for the benefit and convenience of users.
Reading the article infers one is, or wishes to be, a developer.  Hence, I believe the issue is one of education and not separation.  My point would be, materials offered up as being educational, need to be technically correct.  Matters of opinion maybe unavoidable but they should be clearly delineated, from matters of fact and established, expert consensus.

I completely agree the conceptual language, which sometimes obscures OOP, should be kept to a minimum within introductory tutorials.  However, I see no reason to avoid the terminology, during review of such articles.  I am aware of the, not in front the children, school of thought but I do not agree with it.

Quote
In my experience it can be very difficult to get developers (in any field) to appreciate the very different perspective of users.
Careful with that stereotype, Eugene ;)


Title: Re: Arduino the Object Oriented way
Post by: pYro_65 on Dec 31, 2015, 12:27 pm
Modern C++ features such as ranged loops, lambda functions, auto type deduction and so on really make C++ a high-level language...
I'd like to see an Arduino example using one or more of those.  An awful lot of the time, for C++ programmers, "no performance sacrifice" means "if your actual data was 1MB, encapsulating it all in a useful and elegant C++ container only adds another 100k, and obviously 10% is not very significant" rather than "the object overhead fits in 2k with plenty of room for actual data."
The items mentioned by Camel have little to do with container classes. They are just features in C++11, that containers can of course use.

Here is an Arduino based example that contains a ranged loop and auto type deduction. It also uses one of my 'container' classes called BitBool (in library manager).

This example provides a more efficient method printing binary than provided by the core. And it can be used to print 64bit binary which is not even implemented in the core (max 32bits).

The code to use it is very simple, and its quite efficient.

Code: [Select]

#include <BitBool.h>

void setup() {

  uint64_t data = 0xAABBCCDD00112233;

  Serial.begin(9600);
  Serial.print( "Printed as binary: " );

  auto &bits = toBitBool<REVERSE_BOTH>(data);

  for( auto bit : bits ){
    Serial.write( '0' + (bit ? 1 : 0) );
  }
}

void loop() {}


As for lambdas, they can be viewed as simply functions that you can declare inline, or inside another function.
Title: Re: Arduino the Object Oriented way
Post by: Robin2 on Dec 31, 2015, 02:50 pm
Careful with that stereotype, Eugene ;)
Genuinely don't know what you had in mind when you wrote that.

...R
Title: Re: Arduino the Object Oriented way
Post by: PaulMurrayCbr on Jan 01, 2016, 03:46 am
Some changes made. I have a couple of annoying writing ticks: overuse of 'of course', saying "note that X" rather than simply saying "X". And I included a link to a relevant wikipedia page.
Title: Re: Arduino the Object Oriented way
Post by: msssltd on Jan 03, 2016, 11:23 am
Genuinely don't know what you had in mind when you wrote that.
"Careful with that axe, Eugene(!)" Is a lengthy instrumental number by Pink Floyd.  The track was later reworked and re-named, "Come in number 51. Your time is up!"  Both titles refer to self indulgence.

What I had in mind was the irony, of attributing prejudices to stereotypes.

Title: Re: Arduino the Object Oriented way
Post by: Robin2 on Jan 03, 2016, 01:49 pm
Apologies for my musical ignorance. I may recognize it if I heard it - but I am very poor at titles.

...R
Title: Re: Arduino the Object Oriented way
Post by: lennarthennigs on Nov 04, 2017, 02:36 pm
Hey Paul,
thx for the article. I read through it and found it really helpful. I've been rewriting some of my Arduino files and created my first few classes.

I have a question though on constructor vs setup() use. Could you please give me some more details/examples on what can be put inside the constructor of a class and what should be part of a setup() method?

Cheers
Lennart
Title: Re: Arduino the Object Oriented way
Post by: PaulMurrayCbr on Oct 07, 2019, 08:02 am
I have a question though on constructor vs setup() use. Could you please give me some more details/examples on what can be put inside the constructor of a class and what should be part of a setup() method?
setup() for anything that calls methods from the arduino liobrary - anything to do with hardware initalisation. pinMode() is the most common thing.

constuctor for stuff that is "pure" C++. Especially for setting const variables.

The point to remember is that the Arduino environment does quite a bit of work before setup() gets called. I don't know what, exactly, but you can't rely on the hardware state being reasonable until then.

Constructors get called ... actually, I don't know when constructors get called. It may even be the case that thinks like assignments to const variables are pulled out by the compiler and baked into the binary image - they never really get executed at all.

I mean … maybe I'm wrong. Maybe it would all be perfectly ok to put things in constructors. But then again, maybe not.

For example, it's common for things like the LCD object provided by a library to have a constructor to assign the pins, but a separate initialize() method to be called in setup().
Title: Re: Arduino the Object Oriented way
Post by: Coding Badly on Oct 08, 2019, 08:07 am
Constructors get called ... actually, I don't know when constructors get called.
Early.  Well before anything Arduino has run.

For example, it's common for things like the LCD object provided by a library to have a constructor to assign the pins, but a separate initialize() method to be called in setup().
Correct design.

Title: Re: Arduino the Object Oriented way
Post by: westfw on Oct 08, 2019, 08:37 am
Quote
Quote
Constructors get called ... actually, I don't know when constructors get called.
Early.  Well before anything Arduino has run.
In the compiler-added startup code, after "initialized data" is copied from flash into RAM and uninitialized data is cleared, and before main() is called.
Title: Re: Arduino the Object Oriented way
Post by: PaulMurrayCbr on Oct 13, 2019, 02:10 pm
Early.  Well before anything Arduino has run.
In the compiler-added startup code, after "initialized data" is copied from flash into RAM and uninitialized data is cleared, and before main() is called.
IIRC, C++ destructor semantics are difficult to navigate when you have multiple virtual inheritance and things like that. The best practice seems to be not to write things that rely on clever destructor behaviour.