pi.ino

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc4000/spring2026/notes/nano/code/pi.ino
 
void setup() {
   Serial.begin(9600);

   pinMode(LED_BUILTIN, OUTPUT);

   randomSeed(analogRead(0));
}

const long BIG_RANGE {1000000};
const unsigned long TRIALS{20000};
const double MILLIS_TO_SECONDS{1000.0};

void FindPi() {
     double x, y; 
     unsigned long hits{0};

     unsigned long startTime {millis()};

     for (unsigned long trial = 0; trial < TRIALS; ++trial){
         x = random(BIG_RANGE)/static_cast<long double>(BIG_RANGE);
         y = random(BIG_RANGE)/static_cast<long double>(BIG_RANGE);

         long double place = x*x + y*y;
         
         if (place <= 1){
             ++hits;
         }
      }

      unsigned long endTime{millis()};

      Serial.print("hits = ");
      Serial.print(hits);
      Serial.print(" pi = ");
      double pi = static_cast<double>(hits)/static_cast<double> (TRIALS) *4.0;
      Serial.println(pi, 4);

      Serial.print("Total Time ");

      Serial.print((endTime-startTime) / MILLIS_TO_SECONDS, 5);
      Serial.println(" seconds.");
}

void loop() {
  FindPi();
}