edge lab LIVE! starts Tuesday in Munich. Grab a workshop seat and take home the board you build on. Code FRIEND-HACKSTER saves 20%. () Learn more!
Klausj
Published © GPL3+

Galton Board

For most kinds of statistical calculations, the binomial distribution is essential.

IntermediateFull instructions provided1 hour527
Galton Board

Things used in this project

Story

Read more

Code

Galton Board Simulation

Arduino
Electronic replacment fpr mechanical Galton Board
No preview (download only).

Galton, latest version

Arduino
including instructions
No preview (download only).

The very last update

Arduino
all the same, but better readability
/*
  Galton board
*/
#include "Adafruit_ST7735.h"
#define cs   10
#define dc   9
#define rst  8

Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, rst);

const int DELAY = 0;
const int BLUE = 12345;
const int N = 15;
long cnt[N];
int w, h, mx, r;
long total = 0;

void setup() {
  Serial.begin(9600);
  Serial.println(__FILE__);
  tft.initR(INITR_BLACKTAB);
  tft.setRotation(0);
  tft.fillScreen(0);
  w = tft.width();
  h = tft.height();
  tft.drawRect(0, 0, w, h, ST7735_WHITE);
  tft.setCursor(w - 32, 2);
  tft.print("total");
  mx = w / 2;
  r = 1;
  tft.setTextColor(ST7735_GREEN);
  tft.drawLine(4, 122, 4, h - 2, BLUE);
  for (int i = 0; i < N + 1; i++) {
    int i1 = 8 * i;
    for (int j = 1; j < i; j++)
      tft.drawCircle(mx + 8 * j - 4 * i, i1, r, ST7735_WHITE);
    // collecting compartments:
    i1 = i1 + 2 * r + 10;
    tft.drawLine(i1, 122, i1, h - 2, BLUE);
    printCnt(i);
  }
}

void loop() {
  int u = 50;
  int x = mx;
  int y = 10;
  int p = 0;
  // draw ball:
  tft.drawCircle(x, y, r, ST7735_CYAN);
  for (int i = 1; i < N; i++) {
    //----------------------------------
    int v = random(100);
    int w = 0;
    if (v > u) w = 1;
    //----------------------------------
    // erase ball:
    tft.fillRect(x - 1, y - 1, 4, 4, 0);
    x = x - 4 + 8 * w;
    y = y + 8;
    // draw ball:
    tft.drawCircle(x, y, r, ST7735_CYAN);
    p = p + w;
    delay(DELAY);
  }
  // erase ball:
  tft.fillRect(x - 1, y - 1, 4, 4, 0);
  total++;
  cnt[p]++;
  printCnt(p);
}

void printCnt(int i) {
  if (i >= N) return;
  // loesche altes total:
  tft.setRotation(0);
  tft.fillRect(80, 12, 47, 8, 0);
  // drucke rechtsbuendig:
  tft.setCursor(posVal(total), 12);
  tft.print(total);
  tft.setRotation(1);
  int x = h - 7;
  int y = 4 + 8 * i;
  long z = cnt[i];
  if (z > 9) x = x - 6;
  if (z > 99) x = x - 6;
  if (z > 999) x = x - 6;
  if (z > 9999) x = x - 6;
  tft.fillRect(x, y, h - x - 2, 7, 0);
  tft.setCursor(x, y);
  tft.print(z);
  tft.setRotation(0);
}

byte posVal(long x) {
  byte p = 0;
  if (x >= 10) p++;
  if (x >= 100) p++;
  if (x >= 1000) p++;
  if (x >= 10000) p++;
  if (x >= 100000) p++;
  if (x >= 1000000) p++;
  if (x >= 10000000) p++;
  return w - 7 - 6 * p;
}

Credits

Klausj
99 projects • 9 followers

Comments