xxxxxxxxxx
let dutyCycleSlider;
let dutyCycle = 0.5; // Initialize to 50%
function setup() {
createCanvas(600, 300);
dutyCycleSlider = createSlider(0, 1, 0.5, 0.01); // Range from 0 to 1, default value 0.5, step size 0.01
dutyCycleSlider.style('width', '400px'); // Set width of slider
dutyCycleSlider.position(20, 20); // Position slider
}
function draw() {
background(220);
// Update duty cycle
dutyCycle = dutyCycleSlider.value();
// Set stroke for waveform
stroke(0);
// Generate PWM waveform
beginShape();
for (let x = 0; x < width; x++) {
// Map x to time period of waveform
let t = map(x, 0, width, 0, TWO_PI);
// Calculate value of waveform at this point in time
let y = (sin(t) > 2 * dutyCycle - 1) ? height/3 : 2*height/3; // Draw high if in duty cycle, low otherwise
// Add vertex to waveform
vertex(x, y);
}
endShape();
// Display duty cycle
fill(0);
noStroke();
textSize(20);
text("Duty Cycle: " + nf(dutyCycle*100, 0, 2) + "%", 20, height - 50); // Display duty cycle as percentage
}