GMU:Functions and Classes (Arduino): Difference between revisions

From Medien Wiki
Line 49: Line 49:


It would be ideal to find a way of calling a certain function that only offers the most useful parameters (like setting the speed) and which handles technical details (switching pins on and off) internally.
It would be ideal to find a way of calling a certain function that only offers the most useful parameters (like setting the speed) and which handles technical details (switching pins on and off) internally.
==Possible solution: Data and code in one package „Classes“ and „Objects“==
C++ (and also Arduino) provides a specific feature that can solve our problem: Classes and Objects
A Class predefines common qualities of a group of Objects.
It for instance determines that every motor has the possibility to exert a certain amount of throttle.
The corresponding program could look like this:
''class Motor{
public: // the following qualities and methods are visible from the outside.
void setThrottle(int newThrottle); // every motor has the possibility to exert trottle.
}''
Now the computer knows that there is a class called „Motor“.
This class (class) provides a function called „setThrottle“ that is called as an argument by using a number (int) and that does not return anything (void).
==Classes are Data-types==
We can use our „Motor“ - class the same way we are using other data - types (int, long, float).
The following lines use that quality in order to implement two motors:
''Motor leftMotor; //  declare an object of the type „Motor“ called „leftMotor“
Motor rightMotor; //  declare another object of the type „Motor“ called „rightMotor“
''
==Calling inner functions of a class (Methods)==
Imagine we want to drive the left motor with full throttle whereas the right motor should stop completely.
This can be expressed as follows:
''// the objetcs name „leftMotor“ and the herein implemented function „setThrottle“ are separated by a dot.
leftMotor.setThrottle(255);
rightMotor.setThrottle(0);
''
A positive side effect: your program gains readability by picking distinct names for your Objects and Methods.