Problem with values in own library


I’m new in programming arduino, but in programming not so, but I have a little problem I can’t recognize what happens.

I’m trying to create a spider with 4 legs, and move it.
I have created a class named “Spider” and a class named “Leg”, when creating new Spider, it will create 4 Legs, for I can move them separately by Leg classes.

In Leg class I have some values, like: updateInterval, isMoving, lastPosition, etc. All legs have 3 servo motors.

So my problem is, when the program is starting, I’m setting the lastPosition to 90, and now while testing, if I write a command to move Forward or Backward, the value of position is are curious, sometimes 350, sometimes 427, and other curious values.
At the start it must be 90, and if moving forward then +10, if backward then -10. I don’t know where those values come from… So frustrating thing…

I’m testing the new values, if bigger then 180 than will be 180, if lesser then 0, than will be 0 for secure.

After I start the program and giving a command to move forward I got:

Trying to move forward
old value:
new value:
Moving →

Moving Back:
Trying to move backward
old value:
new value:
Moving ←

Attached the program codes, please help me.

Leg.cpp (2.46 KB)

Spider.cpp (1.38 KB)

spider.ino (942 Bytes)

I'm trying to create a spider with 4 legs, and move it.

Well, the first problem is spiders have 8 legs.

The second problem is the code you posted won't compile because you did not include the associated .h files for your classes.

When you create 'newLegLeftFront' you are creating it as a local variable. When the CreateLegs() function is done, the memory containing that variable is available for other things. You are keeping only a pointer to memory that is going to get overwritten.

You could change "Leg newLegLeftFront( 15, 3, 4 );" to "static Leg newLegLeftFront( 15, 3, 4 );" and that would work for the first Spider. If you make a second Spider it will use the same Legs.

I think the proper way is to make the Legs members of the Spider, not just pointers to the Legs. If the Legs require data for their construction you will have to have that data handy in the constructor of the Spider.