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;
Example Sketch - Circumference
- Enter the Circumference sketch into the Arduino editor and save it.
- Make sure to use the values 0.75 and 2.0. Do not try to use 2 instead of 2.0.
- Upload your sketch to the Arduino and check the results with the Serial Monitor.
// 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. }
Your Turn – Circle Area
The area of a circle is a = π × r2. Hint: r2 can be expressed as simply r × r.
- Save your sketch as CircumferenceArea.
- Add another float variable to store the result of an area calculation, and code to display it. Run the sketch, and test the answer against a calculator.