Arithmetic operators are useful for doing calculations in your sketch. In this activity, we’ll focus on the basics: assignment (=), addition (+), subtraction (-), multiplication (*), division(/), and modulus (%, the remainder of a division calculation).
The next example sketch, SimpleMath, adds the variables a and b together and stores the result in c. It also displays the result in the Serial Monitor.
Notice that c is now declared as an int, not a char variable type. Another point, int c = a + b uses the assignment operator (=) to copy the result of the addition operation that adds a to b. The figure below shows the expected result of 89 + 42 = 131 in the Serial Monitor.
// Robotics with the BOE Shield - SimpleMath void setup() { Serial.begin(9600); int a = 89; int b = 42; int c = a + b; Serial.print("a + b = "); Serial.println(c); } void loop() { // Empty, no repeating code. }
Fit your variables to the result values you need to store.
This will use less memory so you can write larger sketches that will execute more efficiently.
If you need to work with decimal point values, use float.
If you are using integer values (counting numbers), choose byte, int, or long.
If your results will always be an unsigned number from 0 to 255, use byte.
If your results will not exceed –32,768 to 32,767, an int variable can store your value.
If you need a larger range of values, try a long variable instead. It can store values from ‑2,147,483,648 to 2,147,483,647.
You still have –, *, /, and % to try out!
Imagine your BOE Shield-Bot will enter a contest where you have to make it travel in a circle, but the radius of the circle will only be announced a few minutes before the contest. In this situation, you’ll have an advantage if your code can calculate the circumference of the circle. The circumference is 2 × π × r, where r is the circle’s radius and π ≈ 3.14159. This calculation would be a lot easier to do with floating point math.
Here is a snippet of code that gets the job done. Notice that it uses PI instead of 3.14159. PI is a built-in C language constant (a named value that does not change throughout the sketch). Also notice that all the values have decimal points. That makes them all floating-point values.
float r = 0.75; float c = 2.0 * PI * r;
// Robotics with the BOE Shield - Circumference void setup() { Serial.begin(9600); float r = 0.75; float c = 2.0 * PI * r; Serial.print("circumference = "); Serial.println(c); } void loop() { // Empty, no repeating code. }
The area of a circle is a = π × r2. Hint: r2 can be expressed as simply r × r.