Created
June 13, 2023 14:34
-
-
Save carrotflakes/35bc9d08bd8dcfb8888191abf5f6429d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
</head> | |
<body> | |
<div id="output"></div> | |
<input type="range" id="kp" min="-1" max="2" value="0" step="0.1" /> | |
<input type="range" id="ki" min="-1" max="2" value="0" step="0.1" /> | |
<input type="range" id="kd" min="-1" max="2" value="0" step="0.1" /> | |
<canvas id="canvas" width="400" height="400"></canvas> | |
<script> | |
function draw() { | |
const canvas = document.getElementById('canvas'); | |
const ctx = canvas.getContext('2d'); | |
const width = canvas.width; | |
const height = canvas.height; | |
ctx.clearRect(0, 0, width, height); | |
const kp = document.getElementById('kp').value; | |
const ki = document.getElementById('ki').value; | |
const kd = document.getElementById('kd').value; | |
document.getElementById('output').innerHTML = `kp: ${kp}, ki: ${ki}, kd: ${kd}`; | |
ctx.strokeStyle = 'black'; | |
ctx.beginPath(); | |
ctx.moveTo(0, height / 2); | |
ctx.lineTo(width, height / 2); | |
ctx.stroke(); | |
const resolution = 100; | |
let x = 1.0; | |
let prev_x = 1.0; | |
let integral = 0.0; | |
ctx.strokeStyle = 'red'; | |
ctx.beginPath(); | |
for (let i = 0; i < 400; ++i) { | |
const error = 0.0 - x; | |
const derivative = (x - prev_x) * resolution; | |
integral += error / resolution; | |
const output = kp * error + ki * integral - kd * derivative; | |
prev_x = x; | |
x += output / resolution; | |
ctx.lineTo(i, height / 2 - x * 100); | |
} | |
ctx.stroke(); | |
} | |
document.getElementById('kp').addEventListener('input', draw); | |
document.getElementById('ki').addEventListener('input', draw); | |
document.getElementById('kd').addEventListener('input', draw); | |
draw(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment