The Simple Pendulum motion: Measuring and Testing the Frequency/Period Equation Using an Accelerometer and JavaScript Code
Testing the Law of the Period
What to do
Use JavaScript code to compute the period and compare it with the theoretical value
Repeat the experiment for different rod lengths L
Modify the page layout and the code to compute different values
We now write a JavaScript program to compute the period from the acceleration data and display the results using the web monitor.
We create three files: index.html, sketch.js, and style.css

Executing the code
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SchooMy: Pendulum</title>
<!-- p5.js -->
<script src="https://cdn.jsdelivr.net/npm/p5@1.9.0/lib/p5.min.js"></script>
<!-- CSS -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="left-panel">
<button id="connect">Connect</button>
<button id="start">START</button>
<button id="end">STOP</button>
<br><br>
Rod length L (m):
<input id="length" type="number" step="0.01" value="0.50">
<br><br>
<div id="led"></div>
<br><br>
<div id="info"></div>
</div>
<div id="graph-container"></div>
<!-- sketch.js -->
<script src="sketch.js"></script>
</body>
</html>sketch.js
/* =====================
COSTANTS
===================== */
const g = 9.81;
const OFFSET = 1.5;
const PERC_TOL = 0.10;
const GRAPH_WIDTH = 500;
const GRAPH_HEIGHT = 300;
/* =====================
VARIABLES
===================== */
let collecting = false;
let count = 0;
let a_values = [];
let time_values = [];
let f_meas = 0;
let f_theory = 0;
let port, reader;
let buffer = "";
/* =====================
P5.JS
===================== */
let sketch = (p) => {
p.setup = () => {
let canvas = p.createCanvas(GRAPH_WIDTH, GRAPH_HEIGHT);
canvas.parent('graph-container');
};
p.draw = () => {
p.background(240);
// bordo
p.stroke(0);
p.noFill();
p.rect(50, 20, GRAPH_WIDTH - 70, GRAPH_HEIGHT - 60);
// assi
p.line(50, GRAPH_HEIGHT - 40, GRAPH_WIDTH - 20, GRAPH_HEIGHT - 40);
p.line(50, GRAPH_HEIGHT - 40, 50, 20);
// etichette
p.fill(0);
p.textSize(14);
p.textAlign(p.CENTER, p.CENTER);
p.text("時間 (秒)", (GRAPH_WIDTH + 50) / 2, GRAPH_HEIGHT - 10);
p.push();
p.translate(15, (GRAPH_HEIGHT - 40) / 2 + 20);
p.rotate(-p.PI / 2);
p.text("加速度 (m/s²)", 0, 0);
p.pop();
if (a_values.length < 2) return;
let a_min = Math.min(...a_values);
let a_max = Math.max(...a_values);
if (a_max === a_min) a_max += 1;
p.stroke("blue");
p.noFill();
p.beginShape();
for (let i = 0; i < a_values.length; i++) {
let x = p.map(
time_values[i],
time_values[0],
time_values[time_values.length - 1],
50,
GRAPH_WIDTH - 20
);
let y = p.map(
a_values[i],
a_min,
a_max,
GRAPH_HEIGHT - 40,
20
);
p.vertex(x, y);
}
p.endShape();
};
};
new p5(sketch);
/* =====================
BUTTONS
===================== */
document.getElementById("start").onclick = () => {
collecting = true;
count = 0;
a_values = [];
time_values = [];
f_meas = 0;
f_theory = 0;
document.getElementById("led").style.background = "gray";
updateInfo();
};
document.getElementById("end").onclick = () => {
collecting = false;
if (a_values.length < 2) return;
let a_mean = a_values.reduce((a, b) => a + b, 0) / a_values.length;
let zeroTimes = [];
for (let i = 1; i < a_values.length; i++) {
if (
(a_values[i - 1] - a_mean > 0 && a_values[i] - a_mean <= 0) ||
(a_values[i - 1] - a_mean < 0 && a_values[i] - a_mean >= 0)
) {
zeroTimes.push(time_values[i]);
}
}
if (zeroTimes.length < 2) return;
let periods = [];
for (let i = 2; i < zeroTimes.length; i += 2) {
periods.push(zeroTimes[i] - zeroTimes[i - 2]);
}
if (periods.length === 0) return;
let T_avg = periods.reduce((a, b) => a + b, 0) / periods.length;
f_meas = 1 / (2 * T_avg);
let L = parseFloat(document.getElementById("length").value);
f_theory = (1 / (2 * Math.PI)) * Math.sqrt(g / L);
let relDiff = Math.abs(f_meas - f_theory) / f_theory;
document.getElementById("led").style.background =
relDiff <= PERC_TOL ? "green" : "red";
updateInfo();
};
/* =====================
INFO
===================== */
function updateInfo() {
document.getElementById("info").innerHTML = `
Status: ${collecting ? "Collecting" : "Stopped"}<br>
Number of samples: ${count}<br><br>
Simple pendulum:<br>
T = 2π √(L / g)<br>
f = (1 / 2π) √(g / L)<br><br>
${f_meas > 0 ? `Measured frequency<br>f_mis = ${f_meas.toFixed(3)} Hz<br>` : ""}
${f_theory > 0 ? `<br>Theoretical frequency<br>f_teo = ${f_theory.toFixed(3)} Hz<br>` : ""}
${
f_meas > 0 && f_theory > 0
? `<br>Percentage error = ${(Math.abs(f_meas - f_theory) / f_theory * 100).toFixed(1)} %`
: ""
}
`;
}
/* =====================
SERIAL
===================== */
document.getElementById("connect").onclick = async () => {
port = await navigator.serial.requestPort();
await port.open({ baudRate: 9600 });
reader = port.readable.getReader();
readSerial();
};
async function readSerial() {
const decoder = new TextDecoder();
while (true) {
const { value } = await reader.read();
buffer += decoder.decode(value);
let lines = buffer.split("\n");
buffer = lines.pop();
for (let line of lines) {
let a_g = parseFloat(line.trim());
if (!isNaN(a_g)) {
let a_ms = a_g * g - OFFSET;
if (collecting) {
a_values.push(a_ms);
time_values.push(performance.now() / 1000);
count++;
updateInfo();
}
}
}
}
}style.css
body {
display: flex;
font-family: monospace;
}
#left -panel {
width: 300px;
padding: 10px;
}
#graph -container {
background: #f0f0f0 ;
padding: 10px;
}
#led {
width: 30px;
height: 30px;
border-radius: 50%;
background: gray;
display: inline-block;
}
input {
width: 60px;
}
Run the experiment
We input the rod length L, set the mass (SchooMy board with the accelerometer sensor) into oscillation, and click “START” to collect acceleration data. When we click “STOP,” the system computes the period and or the frequency of the motion and compares it with the theoretical value. If the result is within 10% (*) of the theoretical period and or frequency, the gray circle turns green; otherwise, it turns red.
(*) We can reduce the tolerance to 5% or lower if we are confident that the experiment has been set up precisely.
The code in this example computes the frequency, but it can easily be modified to calculate the period instead. In any case, frequency and period are simply the inverse of each other, as shown by the formula above.

Repeat the experiment for different lengths L:
20 cm
40 cm
60 cm
etc.
You can now change the content of the three files to customize both the computing section and the layout.
Some examples could be:
- Change the formula in the code to compute the period instead of the frequency.
- Change the layout of the page to display the graph below the text.

Sources of Experimental Error
Possible causes of small discrepancies for which we apply 10% tolerance:
air resistance,
friction at the pivot,
inaccurate length measurement.