-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcar_pid.html
465 lines (380 loc) · 13 KB
/
car_pid.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Matter.js Car Simulation</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.20.0/matter.min.js"></script>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
padding: 10px;
}
.grid-item {
padding: 20px;
text-align: center;
}
</style>
<body>
<!-- Reset Button -->
<form id="ctrl">
<div class="grid-container">
<div>
<input type="reset" onclick="location.reload()">
</div>
<div></div>
<!-- Enable Control -->
<div>
<label for="enable">Enable:</label>
<input type="checkbox" id="enable">
</div>
<!-- Proportional Control -->
<div>
<label for="pid">PI Control:</label>
<input type="checkbox" id="pid">
</div>
<!-- Target Velocity -->
<div>
<label for="targetVelocity">Target Velocity:</label>
<input type="range" id="targetVelocity" min="0" max="6" value="4" step="0.1">
<span id="targetVelocityValue">4</span>
</div>
<!-- kP slider -->
<div>
<label for="kP">kP:</label>
<input type="range" id="kP" min="0" max="1" value="0.1" step="0.01">
<span id="kPValue">0.1</span>
</div>
<!-- Max torque -->
<div>
<label for="maxTorque">Max Torque:</label>
<input type="range" id="maxTorque" min="0" max="0.3" value="0.15" step="0.01">
<span id="maxTorqueValue">0.15</span>
</div>
<!-- kI slider -->
<div>
<label for="kI">kI:</label>
<input type="range" id="kI" min="0" max=".005" value="0.0" step="0.0001">
<span id="kIValue">0.0</span>
</div>
</div>
</form>
<div id="velocityChart"></div>
<script>
const enableCheckbox = document.getElementById("enable");
const velocitySlider = document.getElementById("targetVelocity");
const velocityOutput = document.getElementById("targetVelocityValue");
velocityOutput.textContent = velocitySlider.value;
velocitySlider.addEventListener("input", function () {
velocityOutput.textContent = velocitySlider.value;
});
const maxTorqueSlider = document.getElementById("maxTorque");
const maxTorqueOutput = document.getElementById("maxTorqueValue");
maxTorqueOutput.textContent = maxTorqueSlider.value;
maxTorqueSlider.addEventListener("input", function () {
maxTorqueOutput.textContent = maxTorqueSlider.value;
});
const pidCheckbox = document.getElementById("pid");
const kPSlider = document.getElementById("kP");
const kPOutput = document.getElementById("kPValue");
kPOutput.textContent = kPSlider.value;
kPSlider.addEventListener("input", function () {
kPOutput.textContent = kPSlider.value;
});
const kISlider = document.getElementById("kI");
const kIOutput = document.getElementById("kIValue");
kIOutput.textContent = kISlider.value;
kISlider.addEventListener("input", function () {
kIOutput.textContent = kISlider.value;
});
const margin = { top: 20, right: 30, bottom: 30, left: 40 },
width = 800 - margin.left - margin.right,
height = 200 - margin.top - margin.bottom;
const svg = d3.select("#velocityChart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// Set up scales for the x and y axes
const x = d3.scaleLinear().domain([0, 10]).range([0, 600]); // Time (seconds)
const y = d3.scaleLinear().domain([0, 7]).range([height, 0]); // Velocity (m/s)
// Add the x and y axes
svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(x));
svg.append("g")
.call(d3.axisLeft(y));
// Create a line generator
const line = d3.line()
.x((d, i) => x(i / 60)) // Assuming 60 FPS, adjust as needed
.y(d => y(d));
// Data storage for velocity values
let target_velocity = [];
let real_velocity = [];
let rear_wheel_velocity = [];
let front_wheel_velocity = [];
let torque = [];
// Append the path element to the SVG that will hold the line
const target_velocity_path = svg.append("path")
.datum(target_velocity)
.attr("fill", "none")
.attr("stroke", "black")
.attr("stroke-width", 1.5)
.attr("d", line);
const real_velocity_path = svg.append("path")
.datum(real_velocity)
.attr("fill", "none")
.attr("stroke", "blue")
.attr("stroke-width", 1.5)
.attr("d", line);
const rear_wheel_velocity_path = svg.append("path")
.datum(rear_wheel_velocity)
.attr("fill", "none")
.attr("stroke", "red")
.attr("stroke-width", 1.5)
.attr("d", line);
const front_wheel_velocity_path = svg.append("path")
.datum(front_wheel_velocity)
.attr("fill", "none")
.attr("stroke", "green")
.attr("stroke-width", 1.5)
.attr("d", line);
const torque_path = svg.append("path")
.datum(front_wheel_velocity)
.attr("fill", "none")
.attr("stroke", "pink")
.attr("stroke-width", 1.5)
.attr("d", line);
const legend = svg.append("g")
.attr("class", "legend")
.attr("transform", "translate(20, 20)"); // Position the legend
const categories = [
{ name: "Target Velocity", color: "black" },
{ name: "Real Velocity", color: "blue" },
{ name: "Rear Wheel Velocity", color: "red" },
{ name: "Front Wheel Velocity", color: "green" },
{ name: "Torque", color: "pink" }
];
// Add legend items
const legendItem = legend.selectAll(".legend-item")
.data(categories)
.enter()
.append("g")
.attr("class", "legend-item")
.attr("transform", (d, i) => `translate(600, ${i * 20})`); // Space the items
// Add rectangles (or circles) as legend keys
legendItem.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", 15)
.attr("height", 15)
.attr("fill", d => d.color); // Set the color for each category
// Add text labels to the right of the rectangles
legendItem.append("text")
.attr("x", 20)
.attr("y", 12) // Vertically center the text relative to the rectangle
.text(d => d.name)
.style("font-size", "12px");
var Example = Example || {};
Example.car = function () {
var Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Composites = Matter.Composites,
Composite = Matter.Composite,
Bodies = Matter.Bodies,
Events = Matter.Events,
Body = Matter.Body;
// create engine
var engine = Engine.create(),
world = engine.world;
// create renderer
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: 800,
height: 300,
showAngleIndicator: true,
showCollisions: true
}
});
Render.run(render);
// create runner
var runner = Runner.create();
Runner.run(runner, engine);
// add bodies
Composite.add(world, [
Bodies.rectangle(400, 300, 1000, 50, { isStatic: true }),
]);
// see car function defined later in this file
var car = Example.car.car(150, 100, 150, 30, 30);
Composite.add(world, car);
// fit the render viewport to the scene
Render.lookAt(render, {
min: { x: 0, y: 0 },
max: { x: 800, y: 300 }
});
function userUpdate() {
// Loop around the screen: if the car reaches the right edge, teleport it to the left
if (car.position().x > 800) {
car.reset();
}
let t = car.control() * 10;
if (enableCheckbox.checked) {
torque.push(t);
// Add the new velocity to the data array
target_velocity.push(parseFloat(velocitySlider.value));
real_velocity.push(car.real_velocity());
rear_wheel_velocity.push(car.rear_wheel_velocity());
front_wheel_velocity.push(car.front_wheel_velocity());
// Limit the number of data points (e.g., to the last 100 points)
if (real_velocity.length > 500) {
target_velocity.shift();
real_velocity.shift();
rear_wheel_velocity.shift();
front_wheel_velocity.shift();
torque.shift();
}
// Update the scales
x.domain([0, real_velocity.length / 60]); // Adjust the x-axis based on time (assumed 60 FPS)
// Update the path with the new data
target_velocity_path.datum(target_velocity)
.attr("d", line);
real_velocity_path.datum(real_velocity)
.attr("d", line);
rear_wheel_velocity_path.datum(rear_wheel_velocity)
.attr("d", line);
front_wheel_velocity_path.datum(front_wheel_velocity)
.attr("d", line);
torque_path.datum(torque)
.attr("d", line);
}
}
Events.on(engine, 'afterUpdate', function () {
userUpdate();
});
// context for MatterTools.Demo
return {
engine: engine,
runner: runner,
render: render,
canvas: render.canvas,
stop: function () {
Matter.Render.stop(render);
Matter.Runner.stop(runner);
}
};
};
Example.car.title = 'Car';
Example.car.for = '>=0.14.2';
Example.car.car = function (xx, yy, width, height, wheelSize) {
var Body = Matter.Body,
Bodies = Matter.Bodies,
Composite = Matter.Composite,
Constraint = Matter.Constraint;
var group = Body.nextGroup(true),
wheelBase = 20,
wheelAOffset = -width * 0.5 + wheelBase,
wheelBOffset = width * 0.5 - wheelBase,
wheelYOffset = 0;
var car = Composite.create({ label: 'Car' });
var body = Bodies.rectangle(xx, yy, width, height, {
collisionFilter: {
group: group
},
chamfer: {
radius: height * 0.5
},
density: 0.0002,
frictionAir: 0.05
});
var wheelA = Bodies.circle(xx + wheelAOffset, yy + wheelYOffset, wheelSize, {
collisionFilter: {
group: group
},
friction: 0.8
});
var wheelB = Bodies.circle(xx + wheelBOffset, yy + wheelYOffset, wheelSize, {
collisionFilter: {
group: group
},
friction: 0.8
});
var axelA = Constraint.create({
bodyB: body,
pointB: { x: wheelAOffset, y: wheelYOffset },
bodyA: wheelA,
stiffness: 1,
length: 0
});
var axelB = Constraint.create({
bodyB: body,
pointB: { x: wheelBOffset, y: wheelYOffset },
bodyA: wheelB,
stiffness: 1,
length: 0
});
Composite.addBody(car, body);
Composite.addBody(car, wheelA);
Composite.addBody(car, wheelB);
Composite.addConstraint(car, axelA);
Composite.addConstraint(car, axelB);
car.position = function () {
return body.position;
};
car.reset = function (position) {
Composite.translate(car, { x: -800, y: 0 });
};
var integral = 0;
var lastKI = 0;
var lastTargetVel = 0;
car.control = function () {
const target_vel = parseFloat(velocitySlider.value);
const max_torque = parseFloat(maxTorqueSlider.value);
// Reset integral when changing set points
if (target_vel != lastTargetVel || kISlider.value != lastKI) {
integral = 0;
}
lastKI = kISlider.value;
lastTargetVel = target_vel;
var enabled = enableCheckbox.checked;
if (enabled) {
if (pidCheckbox.checked) {
const kP = parseFloat(kPSlider.value);
const kI = parseFloat(kISlider.value);
const error = target_vel - car.front_wheel_velocity();
integral += error;
const torque = Math.max(Math.min(kP * error + kI * integral, max_torque), -max_torque);
console.log(error.toPrecision(3), (error * kP).toPrecision(3), integral.toPrecision(3), (integral * kI).toPrecision(3), torque.toPrecision(3));
wheelA.torque = torque;
return torque;
} else {
wheelA.torque = max_torque;
integral = 0;
return max_torque;
}
} else {
integral = 0;
return 0;
}
}
car.real_velocity = function () {
return body.velocity.x;
}
car.rear_wheel_velocity = function () {
return wheelA.angularVelocity * wheelSize;
}
car.front_wheel_velocity = function () {
return wheelB.angularVelocity * wheelSize;
}
return car;
};
Example.car();
</script>
</body>
</html>