xxxxxxxxxx
68
let canvasWidth = 800;
let canvasHeight = 600;
let dutyCycle = 0.5; // Initial duty cycle (50%)
let numHarmonics = 10; // Number of harmonics
let wave = []; // Stores the wave data
function setup() {
createCanvas(canvasWidth, canvasHeight);
createUI();
}
function draw() {
background(240);
drawAxes();
generateHarmonicGraph();
drawWave();
}
function createUI() {
createP("Duty Cycle (0.1 to 0.9):");
let dutySlider = createSlider(0.1, 0.9, dutyCycle, 0.01);
dutySlider.input(() => (dutyCycle = dutySlider.value()));
createP("Number of Harmonics (1 to 50):");
let harmonicsSlider = createSlider(1, 50, numHarmonics, 1);
harmonicsSlider.input(() => (numHarmonics = harmonicsSlider.value()));
}
function drawAxes() {
stroke(0);
strokeWeight(1);
// Horizontal axis
line(50, canvasHeight / 2, canvasWidth - 50, canvasHeight / 2);
// Vertical axis
line(50, 50, 50, canvasHeight - 50);
}
function generateHarmonicGraph() {
wave = [];
let waveResolution = 500; // Number of points in the wave
for (let x = 0; x < waveResolution; x++) {
let t = map(x, 0, waveResolution, 0, TWO_PI); // Map to time
let y = 0;
// Fourier series for square wave with duty cycle
for (let n = 1; n <= numHarmonics; n++) {
let harmonic = (2 / (n * PI)) * sin(n * PI * dutyCycle) * sin(n * t);
y += harmonic;
}
wave.push(y);
}
}
function drawWave() {
noFill();
stroke(0);
strokeWeight(2);
beginShape();
let waveResolution = wave.length;
for (let x = 0; x < waveResolution; x++) {
let xPos = map(x, 0, waveResolution, 50, canvasWidth - 50);
let yPos = map(wave[x], -1, 1, canvasHeight - 50, 50); // Flip vertically
vertex(xPos, yPos);
}
endShape();
}