メインコンテンツへスキップ

The Simple Pendulum motion: Measuring and Testing the Frequency/Period Equation Using a Magnetometer and JavaScript Code


    Testing the Law of the Period

    What to do

    1. Use JavaScript code to compute the period and compare it with the theoretical value

    2. Repeat the experiment for different rod lengths L

    3. Modify the page layout and the code to compute different values


    The SchooMy board, equipped with a magnetic sensor, is placed stably on a table. A magnet is suspended from a wire (or rod) and set into oscillation with small angular displacements, ensuring that it passes directly over the sensor at its lowest point. Each time the magnet passes close to the sensor, the sensor records a peak in its measured value.

    We now write a JavaScript program to compute the period from the magnetic field 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

    /* =====================
       COSTANTI
    ===================== */
    const g = 9.81;
    const PERC_TOL = 0.10;
    const GRAPH_WIDTH = 500;
    const GRAPH_HEIGHT = 300;
    
    /* =====================
       VARIABLES
    ===================== */
    let collecting = false;
    let count = 0;
    let mag_values = [];
    let time_values = [];
    
    let f_meas = 0;     // periodo misurato (s)
    let f_theory = 0;  // periodo teorico (s)
    
    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);
    
        // etichetta asse X
        p.noStroke();
        p.fill(0);
        p.textSize(14);
        p.textAlign(p.CENTER, p.CENTER);
        p.text("Time (s)", (GRAPH_WIDTH + 50) / 2, GRAPH_HEIGHT - 10);
    
        // griglia verticale + tick (secondi)
        if (time_values.length > 1) {
          let t0 = time_values[0];
          let t1 = time_values[time_values.length - 1];
    
          let startSec = Math.ceil(t0);
          let endSec = Math.floor(t1);
    
          for (let t = startSec; t <= endSec; t++) {
            let x = p.map(t, t0, t1, 50, GRAPH_WIDTH - 20);
    
            // griglia
            p.stroke(210);
            p.line(x, 20, x, GRAPH_HEIGHT - 40);
    
            // tick
            p.stroke(0);
            p.line(x, GRAPH_HEIGHT - 40, x, GRAPH_HEIGHT - 34);
    
            // label
            p.noStroke();
            p.fill(0);
            p.textAlign(p.CENTER, p.TOP);
            p.text(`${(t - t0).toFixed(0)} s`, x, GRAPH_HEIGHT - 32);
          }
        }
    
        // etichetta asse Y
        p.push();
        p.translate(15, (GRAPH_HEIGHT - 40) / 2 + 20);
        p.rotate(-p.PI / 2);
        p.textAlign(p.CENTER, p.CENTER);
        p.text("Campo magnetico (a.u.)", 0, 0);
        p.pop();
    
        if (mag_values.length < 2) return;
    
        let m_min = Math.min(...mag_values);
        let m_max = Math.max(...mag_values);
        if (m_max === m_min) m_max += 1;
    
        // curva
        p.stroke("blue");
        p.noFill();
        p.beginShape();
        for (let i = 0; i < mag_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(
            mag_values[i],
            m_min,
            m_max,
            GRAPH_HEIGHT - 40,
            20
          );
          p.vertex(x, y);
        }
        p.endShape();
      };
    };
    
    new p5(sketch);
    
    /* =====================
       BUTTONS
    ===================== */
    document.getElementById("start").onclick = () => {
      collecting = true;
      count = 0;
      mag_values = [];
      time_values = [];
      f_meas = 0;
      f_theory = 0;
      document.getElementById("led").style.background = "gray";
      updateInfo();
    };
    
    document.getElementById("end").onclick = () => {
      collecting = false;
    
      // servono abbastanza dati
      if (mag_values.length < 100) return;
    
      /* =====================
         1. RIMUOVI OFFSET
      ===================== */
      const mean =
        mag_values.reduce((a, b) => a + b, 0) / mag_values.length;
    
      const signal = mag_values.map(v => v - mean);
    
      /* =====================
         2. MASSIMI LOCALI GREZZI
      ===================== */
      let rawPeaks = [];
      for (let i = 1; i < signal.length - 1; i++) {
        if (signal[i] > signal[i - 1] && signal[i] > signal[i + 1]) {
          rawPeaks.push({
            t: time_values[i],
            v: signal[i]
          });
        }
      }
    
      if (rawPeaks.length < 2) return;
    
      /* =====================
         3. RAGGRUPPA PICCHI VICINI
         (stesso picco fisico)
      ===================== */
      const MERGE_DT = 0.4; // s  (<< periodo ~1s)
      let peaks = [];
      let group = [rawPeaks[0]];
    
      for (let i = 1; i < rawPeaks.length; i++) {
        if (rawPeaks[i].t - group[group.length - 1].t < MERGE_DT) {
          group.push(rawPeaks[i]);
        } else {
          let best = group.reduce((a, b) => (b.v > a.v ? b : a));
          peaks.push(best);
          group = [rawPeaks[i]];
        }
      }
    
      // ultimo gruppo
      let best = group.reduce((a, b) => (b.v > a.v ? b : a));
      peaks.push(best);
    
      if (peaks.length < 2) return;
    
      /* =====================
         4. PERIODI
      ===================== */
      let periods = [];
      for (let i = 1; i < peaks.length; i++) {
        periods.push(peaks[i].t - peaks[i - 1].t);
      }
    
      let T_avg =
        periods.reduce((a, b) => a + b, 0) / periods.length;
    
      f_meas = T_avg;   // PERIODO MISURATO
    
      /* =====================
         5. TEORIA
      ===================== */
      let L = parseFloat(document.getElementById("length").value);
      f_theory = 2 * Math.PI * Math.sqrt(L / g);
    
      /* =====================
         6. LED + INFO
      ===================== */
      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 period<br>P_mis = ${f_meas.toFixed(3)} s<br>` : ""}
        ${f_theory > 0 ? `<br>Theoretical period<br>P_teo = ${f_theory.toFixed(3)} s<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 mag = parseFloat(line.trim());
          if (!isNaN(mag) && collecting) {
            mag_values.push(mag);
            time_values.push(performance.now() / 1000);
            count++;
          }
        }
      }
    }
    

    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 magnetometer sensor) into oscillation, and click “START” to collect magnetic field 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 period, but it can easily be modified to calculate the frequency 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,

    • Magnetic attraction between the magnet and the SchooMy board,

    • Inaccurate length measurement.

     
     
    スクーミーワールド通信ロクサンヨン634 は、スクーミー活用の事例を発信する社外報です。 スクーミーの活用事例や、新しいプロダクトのリリース情報、学校現場での教育実践レポート、イベントや部活動の案内まで、スクーミーの最新情報を、お伝えします。

    あなたへのおすすめ