Go Down

### Topic: Organizing Repetitive Maths Heavy Code  (Read 134 times)previous topic - next topic

#### nick1992

##### Apr 21, 2017, 01:39 pm
Hi,

I'm developing some control code for a robot arm and am looking for some guidance in code structuring and layout for easy editing and debugging.

I will be using the same block of code over and over again with each "operation" that i want the arm to complete, but this block of code is mostly maths operations with multiple numerical inputs and even more outputs.

The code will hopefully work like this:
I input the desired coordinates of the end effector for each operation i wish to perform.
The robot movements are calculated through inverse kinematics.
The robot moves to satisfy the first coordinates.
The robot moves on to calculate the movements to reach the next set of coordinates.
The robot moves to satisfy the second set of coordinates.
etc.

I understand how to progress from one operation to the next when the end conditions of the operation are met (using a basic state machine) but I'm not sure how to organise the large chunk of code i will be using in every operation to calculate the robots movement from the coordinates.

I originally thought i could put this code section in a subroutine and call it when its required but i've since learned that I cannot return more than once variable by this method?

#### DrDiettrich

#1
##### Apr 21, 2017, 02:04 pm
You can create a struct, containing all related variables. Then pass that struct to the subroutine, so that it can fill in the computed results.

Later you can extend the struct into a class, by adding computation methods to it, so that it can be used like other objects as e,g, MyCoords.calculate(...). That's not required, but this is how most (Arduino...) libraries are organized nowadays.

#### avr_fred

#2
##### Apr 21, 2017, 03:04 pm
You are correct that you can only return one thing from a subroutine. But, that that does not mean only one number or piece of text. A subroutine can return a pointer to an object or structure which can contain many more structures or objects so that is only a restriction if you make it one.

In the old days, before well structured programs, we'd just manipulate a bunch of global variables and return from a subroutine with the caller having to know what was changed and how. C and C++ allow for much better control over encapsulation of variables which helps reduce or elimate unintended consequences, a.k.a bugs.

Go Up