For this lesson we will continue as before and learn more about the println and print functions. Copy and paste the following code into your sketchbook and upload it to the Arduino board. We are going to make a calculator.
a2 + b 2 = h 2
h = √(a2 + b2)
If you remember from grade school, if you have a right-triangle, the hypoteneuse h can be calculated from the lengths of the two legs, c1 and c2 (which we'll call a & b)
/* * Math is fun! */ #include "math.h" // include the Math Library int a = 3; int b = 4; int h; void setup() // run once, when the sketch starts { Serial.begin(9600); // set up Serial library at 9600 bps Serial.println("Lets calculate a hypoteneuse"); Serial.print("a = "); Serial.println(a); Serial.print("b = "); Serial.println(b); h = sqrt( a*a + b*b ); Serial.print("h = "); Serial.println(h); } void loop() // we need this to be here even though its empty { }
The first thing that's new here is this line at the very beginning of the sketch:
#include "math.h" // include the Math Library header
Which basically says "We'd like to use the math procedures, which are in a library that requires us to include the file math.h where the sqrt procedure lives". Just ignore it for now, it's not important.
The second thing that's different here is that when we create the variable h we don't assign it a value.
int h;
It turns out that this is totally OK, it just means that we don't know what h is going to store yet, because we're going to calculate it later. Since it's not assigned to a value upon creation, the Arduino just creates the box, the stuff inside is whatever was in left over in memory.
Default values
If you don't assign a value to a variable, it could be any value. Make sure you don't try to use the variable before you assign it a value!
Later on in the sketch, we assign it the value.
h = sqrt( a*a + b*b );
In this line, we square a and b and then add them together, then we call the sqrt() procedure (which does exactly what you may think), to take the square root. Then we assign that to the variable h.
Variable
|
=
|
Value
|
;
|
---|
Whatever was in h before is lost, replaced by the new value.
You can nest procedures and functions all you want, calling a procedure on the return value of another procedure.