Built-in project · Arduino Uno R3

Buffon's needle on an Arduino Uno

Drop thousands of random needles on a floor of lines, count the crossings and watch a 16x2 LCD close in on pi, with no sine, square root or pi in the sketch. The whole build, an Arduino Uno and 4 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.

Teaching? Assign it to your class in one click.

Intermediate About 15 minutes to build and run. Runs in your browser. Free, and no account needed.

The parts retail for about $34. On Mokxi they're free.

Buffon's needle · Arduino Uno R3live0.000 s 0.00x
Watch the estimate settle, and press the button to start again
The circuit itself, running here on the simulator. Press what can be pressed; click anything else to open it in the editor.

What you'll learn

  • Estimating a value by random sampling
  • Probability and the Monte Carlo idea
  • Slow convergence: ten times the drops buys one digit
  • Picking a random direction without sine
  • I2C character LCD output
  • Difficulty: Intermediate
  • Time: About 15 minutes
  • Board: Arduino Uno R3
  • Parts: 6

How it works

The sketch drops virtual needles on a floor of parallel lines. Each drop picks a random distance from the nearest line and a random direction. If the needle reaches the line, it counts as a crossing.

A needle as long as the gap between lines crosses with chance 2 divided by pi. So the Uno estimates pi as twice the drops divided by the crossings, and shows N, H and the estimate on the LCD. The green LED blinks on each crossing, and a button on pin 2 starts over.

Kits that can build it

These 3 starter kits have every part in the circuit. Each kit's page lists what else it can build.

Wiring table

Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.

Part and pinConnects to
Resistor, 220 Ω pin 1Arduino Uno R3 pin 5
Pushbutton pin 1aArduino Uno R3 pin 2
Character LCD with I2C backpack pin VCCArduino Uno R3 pin 5V
Pushbutton pin 2aArduino Uno R3 pin GND
LED, green pin CArduino Uno R3 pin GND
Character LCD with I2C backpack pin GNDArduino Uno R3 pin GND
Character LCD with I2C backpack pin SDAArduino Uno R3 pin A4
Character LCD with I2C backpack pin SCLArduino Uno R3 pin A5
LED, green pin AResistor, 220 Ω pin 2

The code

The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.

sketch.ino · Arduino Uno R3
// Buffon's needle: find pi by dropping needles at random onto a floor of
// parallel lines and counting how many land across one.
//
//   LCD       16x2 with an I2C backpack: SDA -> A4, SCL -> A5
//   button    pin 2 -> button -> GND        (INPUT_PULLUP): start again
//   lamp      pin 5 -> 220 ohms -> LED -> GND: blinks on a crossing
//
// Georges-Louis Leclerc, Comte de Buffon, asked the question in the 1700s.
// Drop a needle as long as the lines are apart. It crosses a line with a
// chance of 2 / pi, so after N drops with H crossings, pi is about 2N / H.
//
// Each drop picks two random things: how far the needle's middle is from the
// nearest line (0 to half the gap), and which way it points. The direction
// comes from a random point inside a circle, thrown away and picked again if
// it lands outside, so every direction is equally likely and the sketch never
// needs pi, sine or a square root to find pi. The needle crosses when
//
//   distance * r  <=  half the needle * |y|
//
// where (x, y) is the point and r its distance from the middle. Both sides
// are squared to keep it in whole numbers.
//
// The estimate wanders and then settles slowly: ten times the drops buys
// about one more correct digit. That slowness is the lesson.
//
// Things to try. Press the button to start again. Watch how far off it is
// after 100 drops, then after 10,000.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

const int BUTTON_PIN = 2;
const int LAMP_PIN = 5;
const long HALF = 1000;   // half the needle, and half the gap between lines

LiquidCrystal_I2C lcd(0x27, 16, 2);

unsigned long drops = 0, hits = 0;
unsigned long nextShow = 0;
unsigned long nextReport = 100;

void reset() {
  drops = 0;
  hits = 0;
  nextReport = 100;
  lcd.clear();
  lcd.print("Dropping needles");
  Serial.println("Buffon's needle: dropping needles");
}

void drop() {
  long distance = random(0, HALF + 1);   // middle to the nearest line
  long x, y, r2;
  do {
    x = random(-HALF, HALF + 1);
    y = random(-HALF, HALF + 1);
    r2 = x * x + y * y;
  } while (r2 > HALF * HALF || r2 == 0);
  drops++;
  // distance * r <= HALF * |y|, squared on both sides; in 64 bits, since the
  // squares of numbers near a million do not fit in 32.
  if ((uint64_t)(distance * distance) * (uint64_t)r2 <= (uint64_t)(HALF * HALF) * (uint64_t)(y * y)) {
    hits++;
    digitalWrite(LAMP_PIN, HIGH);
  } else {
    digitalWrite(LAMP_PIN, LOW);
  }
}

void show() {
  lcd.setCursor(0, 0);
  lcd.print("N ");
  lcd.print(drops);
  lcd.print(" H ");
  lcd.print(hits);
  lcd.print("   ");
  lcd.setCursor(0, 1);
  lcd.print("pi ~ ");
  if (hits > 0) lcd.print(2.0 * drops / hits, 4);
  lcd.print("    ");
}

void setup() {
  Serial.begin(9600);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LAMP_PIN, OUTPUT);
  lcd.init();
  lcd.backlight();
  randomSeed(analogRead(A0));   // a floating pin for a different run each time
  reset();
}

void loop() {
  if (digitalRead(BUTTON_PIN) == LOW) {
    reset();
    while (digitalRead(BUTTON_PIN) == LOW) delay(10);
  }
  drop();
  if (millis() >= nextShow) {
    nextShow = millis() + 250;
    show();
  }
  if (drops == nextReport && hits > 0) {
    Serial.print(drops);
    Serial.print(" drops, ");
    Serial.print(hits);
    Serial.print(" crossings: pi is about ");
    Serial.println(2.0 * drops / hits, 4);
    nextReport *= 10;
  }
}

Code walkthrough

The key functions of the sketch, and what each one does.

drop sketch.ino

Throws one needle. It picks distance from the nearest line and a random point inside a circle, retrying until the point lands inside. That point gives the direction, so no sine or square root is needed. It compares squared values with 64 bit math and counts a hit.

void drop() {
  long distance = random(0, HALF + 1);   // middle to the nearest line
  long x, y, r2;
  do {
    x = random(-HALF, HALF + 1);
    y = random(-HALF, HALF + 1);
    r2 = x * x + y * y;
  } while (r2 > HALF * HALF || r2 == 0);
  drops++;
  // distance * r <= HALF * |y|, squared on both sides; in 64 bits, since the
  // squares of numbers near a million do not fit in 32.
  if ((uint64_t)(distance * distance) * (uint64_t)r2 <= (uint64_t)(HALF * HALF) * (uint64_t)(y * y)) {
    hits++;
    digitalWrite(LAMP_PIN, HIGH);
  } else {
    digitalWrite(LAMP_PIN, LOW);
  }
}

show sketch.ino

Draws the counts and the estimate on the LCD. The top row shows drops and crossings. The bottom row shows 2 times the drops divided by the hits, with four decimals, once there is at least one hit.

void show() {
  lcd.setCursor(0, 0);
  lcd.print("N ");
  lcd.print(drops);
  lcd.print(" H ");
  lcd.print(hits);
  lcd.print("   ");
  lcd.setCursor(0, 1);
  lcd.print("pi ~ ");
  if (hits > 0) lcd.print(2.0 * drops / hits, 4);
  lcd.print("    ");
}

loop sketch.ino

Checks the button, drops one needle, and refreshes the LCD every 250 ms. When the drop count reaches 100, then 1000, then 10 times more each time, it prints the estimate to the serial monitor.

void loop() {
  if (digitalRead(BUTTON_PIN) == LOW) {
    reset();
    while (digitalRead(BUTTON_PIN) == LOW) delay(10);
  }
  drop();
  if (millis() >= nextShow) {
    nextShow = millis() + 250;
    show();
  }
  if (drops == nextReport && hits > 0) {
    Serial.print(drops);
    Serial.print(" drops, ");
    Serial.print(hits);
    Serial.print(" crossings: pi is about ");
    Serial.println(2.0 * drops / hits, 4);
    nextReport *= 10;
  }
}

Troubleshooting

The usual mistakes with this circuit, and the fix for each.

  • The LCD stays blank. This project
    Check SDA on A4, SCL on A5 and power. The sketch expects the backpack at address 0x27.
  • The estimate is far from pi after a few hundred drops. This project
    That is normal. The estimate wanders and settles slowly. Wait for 10,000 drops or more.
  • The input reads random HIGH and LOW when the button is not pressed. Pushbutton
    A floating pin picks up noise. Add a 10 k pull-down or pull-up resistor, or use INPUT_PULLUP and wire the button between the pin and GND. Then pressed reads LOW.
  • The button seems always pressed, or never changes. Pushbutton
    A 4-leg tactile switch has legs joined in pairs. Place it across the breadboard center gap so the pairs sit on different rows. Wired along one side, the legs are already connected.
  • The LED is dim, burns out, or the pin reads wrong because the resistor value is off. Resistor
    Read the color bands again. A 220 ohm to 330 ohm resistor suits a typical LED on 5 V. 10k is a common pull-up or pull-down value. Check with a multimeter if unsure.
  • A pull-up or pull-down resistor is missing, so the input floats and reads random values. Resistor
    Tie the input to 5 V or ground through about 10k. Or use INPUT_PULLUP and wire the switch to ground.
  • The LED does not light, or it lights once and then dies. LED
    LEDs have polarity. The longer leg (anode) goes toward the positive side. Always add a series resistor, about 220 ohms to 1 k ohm on a 5 V pin.
  • A blue or white LED stays dark on 3.3 V. LED
    Blue and white LEDs drop about 3 V, so 3.3 V leaves almost nothing for the resistor. Use a 5 V supply, or a smaller resistor and a red or green LED.

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.