forked from matanleilien/teaching_aids
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOOK_sim
More file actions
360 lines (306 loc) · 17.6 KB
/
Copy pathOOK_sim
File metadata and controls
360 lines (306 loc) · 17.6 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive OOK IQ Modulator Simulator</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Inter', sans-serif;
}
.plot-canvas {
background-color: #1F2937; /* slate-800 */
border-radius: 0.5rem;
border: 1px solid #4B5563; /* slate-600 */
}
</style>
</head>
<body class="bg-gray-900 text-gray-200">
<div class="container mx-auto p-4 lg:p-8">
<header class="text-center mb-8">
<h1 class="text-3xl lg:text-4xl font-bold text-white">Interactive OOK IQ Modulator Simulator</h1>
<p class="text-lg text-gray-400 mt-2">Watch how each incoming bit and phase change shapes the I/Q and RF signals.</p>
</header>
<div class="flex flex-col lg:flex-row gap-8">
<!-- Left Side: Controls -->
<div class="lg:w-1/3 bg-gray-800 p-6 rounded-lg shadow-lg border border-gray-700">
<h2 class="text-2xl font-semibold mb-4 border-b border-gray-600 pb-2">Control Panel</h2>
<!-- Bit Input -->
<div class="mb-6">
<label for="bitInput" class="block text-sm font-medium text-gray-300 mb-2">Enter a bit (0 or 1)</label>
<div class="flex items-center gap-2">
<input type="text" id="bitInput" maxlength="1" class="w-full bg-gray-700 border border-gray-600 rounded-md p-2 text-center text-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition" placeholder="0 or 1">
<button id="transmitBtn" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded-md transition-transform transform hover:scale-105">
Transmit Bit
</button>
</div>
</div>
<!-- Simulation Parameters -->
<div class="mb-6">
<h3 class="text-lg font-semibold mb-3">Simulation Parameters</h3>
<div class="space-y-3">
<div>
<label for="bitRate" class="block text-sm font-medium text-gray-300">Bit Rate (bps)</label>
<input type="number" id="bitRate" value="10" class="w-full bg-gray-700 border border-gray-600 rounded-md p-2 mt-1">
</div>
<div>
<label for="carrierFreq" class="block text-sm font-medium text-gray-300">Carrier Frequency (Hz)</label>
<input type="number" id="carrierFreq" value="100" class="w-full bg-gray-700 border border-gray-600 rounded-md p-2 mt-1">
</div>
<div>
<label for="amplitude" class="block text-sm font-medium text-gray-300">Amplitude</label>
<input type="number" id="amplitude" value="2" class="w-full bg-gray-700 border border-gray-600 rounded-md p-2 mt-1">
</div>
<div>
<label for="phaseOffset" class="block text-sm font-medium text-gray-300">Phase Offset (deg)</label>
<input type="range" id="phaseOffsetSlider" min="-180" max="180" value="0" step="1" class="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer">
<input type="number" id="phaseOffset" value="0" step="1" class="w-full bg-gray-700 border border-gray-600 rounded-md p-2 mt-1">
</div>
</div>
</div>
<!-- Transmitted Bits Log -->
<div>
<h3 class="text-lg font-semibold mb-3">Transmitted Bits Stream</h3>
<div id="bitStreamLog" class="bg-gray-900 rounded-md p-3 h-40 overflow-y-auto border border-gray-600 font-mono text-lg flex flex-wrap gap-2">
<!-- Bits will be added here -->
</div>
<button id="resetBtn" class="w-full mt-4 bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-md transition">
Reset Simulation
</button>
</div>
</div>
<!-- Right Side: Visualizations -->
<div class="lg:w-2/3 grid grid-cols-1 gap-6">
<div class="bg-gray-800 p-4 rounded-lg shadow-lg">
<h3 class="text-center font-semibold mb-2">Original Bitstream</h3>
<canvas id="bitstreamCanvas" class="plot-canvas w-full h-32"></canvas>
</div>
<div class="bg-gray-800 p-4 rounded-lg shadow-lg">
<h3 class="text-center font-semibold mb-2">I (In-Phase) Baseband Signal</h3>
<canvas id="iSignalCanvas" class="plot-canvas w-full h-32"></canvas>
</div>
<div class="bg-gray-800 p-4 rounded-lg shadow-lg">
<h3 class="text-center font-semibold mb-2">Q (Quadrature) Baseband Signal</h3>
<canvas id="qSignalCanvas" class="plot-canvas w-full h-32"></canvas>
</div>
<div class="bg-gray-800 p-4 rounded-lg shadow-lg">
<h3 class="text-center font-semibold mb-2">OOK Modulated Signal (RF Output)</h3>
<canvas id="modulatedSignalCanvas" class="plot-canvas w-full h-32"></canvas>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
// --- DOM Elements ---
const bitInput = document.getElementById('bitInput');
const transmitBtn = document.getElementById('transmitBtn');
const resetBtn = document.getElementById('resetBtn');
const bitStreamLog = document.getElementById('bitStreamLog');
const bitRateInput = document.getElementById('bitRate');
const carrierFreqInput = document.getElementById('carrierFreq');
const amplitudeInput = document.getElementById('amplitude');
const phaseOffsetInput = document.getElementById('phaseOffset');
const phaseOffsetSlider = document.getElementById('phaseOffsetSlider');
const canvases = {
bitstream: document.getElementById('bitstreamCanvas'),
iSignal: document.getElementById('iSignalCanvas'),
qSignal: document.getElementById('qSignalCanvas'),
modulated: document.getElementById('modulatedSignalCanvas'),
};
const contexts = {
bitstream: canvases.bitstream.getContext('2d'),
iSignal: canvases.iSignal.getContext('2d'),
qSignal: canvases.qSignal.getContext('2d'),
modulated: canvases.modulated.getContext('2d'),
};
// --- Simulation State ---
let bits = [];
let simulationParams = {};
function updateParameters() {
simulationParams = {
bitRate: parseFloat(bitRateInput.value) || 10,
carrierFreq: parseFloat(carrierFreqInput.value) || 100,
amplitude: parseFloat(amplitudeInput.value) || 2,
phaseOffset: parseFloat(phaseOffsetInput.value) || 0,
get bitDuration() { return 1 / this.bitRate; },
get samplingFreq() { return 20 * this.carrierFreq; },
get phaseOffsetRad() { return this.phaseOffset * Math.PI / 180; },
};
}
function resizeCanvases() {
for (const key in canvases) {
const canvas = canvases[key];
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
const ctx = contexts[key];
ctx.scale(dpr, dpr);
}
updateAllVisualizations();
}
// --- Drawing Logic ---
function drawGrid(ctx, canvas, yMax) {
const width = canvas.width / (window.devicePixelRatio || 1);
const height = canvas.height / (window.devicePixelRatio || 1);
ctx.strokeStyle = '#4A5562'; // Gray-600
ctx.lineWidth = 0.5;
ctx.beginPath();
ctx.moveTo(0, height / 2);
ctx.lineTo(width, height / 2);
ctx.stroke();
ctx.fillStyle = '#9CA3AF'; // Gray-400
ctx.font = '10px Inter';
ctx.textAlign = 'left';
ctx.fillText(yMax.toFixed(1), 5, 12);
ctx.fillText('0.0', 5, height / 2 + 5);
ctx.fillText((-yMax).toFixed(1), 5, height - 5);
}
function drawWaveform(ctx, canvas, data, yMax, color = '#6366F1') {
const width = canvas.width / (window.devicePixelRatio || 1);
const height = canvas.height / (window.devicePixelRatio || 1);
ctx.clearRect(0, 0, width, height);
drawGrid(ctx, canvas, yMax);
if (data.length === 0) return;
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = 1.5;
for (let i = 0; i < data.length; i++) {
const x = (i / (data.length - 1)) * width;
const y = height / 2 - (data[i] / yMax) * (height / 2);
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
}
function drawStepPlot(ctx, canvas, data, yMax) {
const width = canvas.width / (window.devicePixelRatio || 1);
const height = canvas.height / (window.devicePixelRatio || 1);
ctx.clearRect(0, 0, width, height);
drawGrid(ctx, canvas, yMax);
if (data.length === 0) return;
ctx.beginPath();
ctx.strokeStyle = '#34D399';
ctx.lineWidth = 2;
const stepWidth = width / data.length;
for (let i = 0; i < data.length; i++) {
const x_start = i * stepWidth;
const x_end = (i + 1) * stepWidth;
const y = height / 2 - (data[i] / yMax) * (height / 2);
ctx.moveTo(x_start, y);
ctx.lineTo(x_end, y);
}
ctx.stroke();
}
// --- Simulation Logic ---
function updateAllVisualizations() {
if (!simulationParams.bitRate) updateParameters();
const { bitDuration, samplingFreq, amplitude, carrierFreq, phaseOffsetRad } = simulationParams;
const numBits = bits.length;
if (numBits === 0) {
for(const key in contexts) {
const canvas = canvases[key];
const width = canvas.width / (window.devicePixelRatio || 1);
const height = canvas.height / (window.devicePixelRatio || 1);
contexts[key].clearRect(0,0,width,height);
drawGrid(contexts[key], canvas, key === 'bitstream' ? 1.2 : amplitude + 0.2);
}
return;
}
const totalTime = numBits * bitDuration;
const numSamples = Math.floor(totalTime * samplingFreq);
const t = np_linspace(0, totalTime, numSamples);
const i_signal = new Float32Array(numSamples);
const q_signal = new Float32Array(numSamples);
const modulated_signal = new Float32Array(numSamples);
// Pre-calculate phase components
const cos_phi = Math.cos(phaseOffsetRad);
const sin_phi = Math.sin(phaseOffsetRad);
for (let i = 0; i < numSamples; i++) {
const bitIndex = Math.min(Math.floor(t[i] / bitDuration), bits.length - 1);
const currentBit = bits[bitIndex] || 0;
// This is the base amplitude signal based on the bit
const base_amplitude = currentBit === 1 ? amplitude : 0;
// Distribute the base amplitude onto I and Q to create the phase shift
i_signal[i] = base_amplitude * cos_phi;
q_signal[i] = base_amplitude * sin_phi;
// Modulate with quadrature carriers (no phase offset here)
const i_carrier = Math.cos(2 * Math.PI * carrierFreq * t[i]);
const q_carrier = Math.sin(2 * Math.PI * carrierFreq * t[i]);
// Final IQ modulator output
modulated_signal[i] = i_signal[i] * i_carrier - q_signal[i] * q_carrier;
}
drawStepPlot(contexts.bitstream, canvases.bitstream, bits.map(b => b), 1.2);
drawWaveform(contexts.iSignal, canvases.iSignal, i_signal, amplitude + 0.2, '#6EE7B7'); // Mint Green
drawWaveform(contexts.qSignal, canvases.qSignal, q_signal, amplitude + 0.2, '#F472B6'); // Pink
drawWaveform(contexts.modulated, canvases.modulated, modulated_signal, amplitude + 0.2, '#818CF8'); // Light Indigo
}
function np_linspace(start, stop, num) {
const arr = new Float32Array(num);
const step = (stop - start) / (num - 1);
for (let i = 0; i < num; i++) {
arr[i] = start + (step * i);
}
return arr;
}
// --- Event Handlers ---
function handleTransmit() {
const bit = bitInput.value;
if (bit !== '0' && bit !== '1') {
bitInput.classList.add('border-red-500', 'ring-red-500');
setTimeout(() => bitInput.classList.remove('border-red-500', 'ring-red-500'), 500);
return;
}
bits.push(parseInt(bit));
const bitElement = document.createElement('span');
bitElement.className = `w-8 h-8 flex items-center justify-center rounded-full ${bit === '1' ? 'bg-green-500' : 'bg-blue-500'} text-white font-bold animate-pulse`;
bitElement.textContent = bit;
bitStreamLog.appendChild(bitElement);
bitStreamLog.scrollTop = bitStreamLog.scrollHeight;
setTimeout(() => bitElement.classList.remove('animate-pulse'), 1000);
updateAllVisualizations();
bitInput.value = '';
bitInput.focus();
}
function handleReset() {
bits = [];
bitStreamLog.innerHTML = '';
updateAllVisualizations();
}
// --- Initial Setup ---
transmitBtn.addEventListener('click', handleTransmit);
resetBtn.addEventListener('click', handleReset);
bitInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') handleTransmit();
});
const allInputs = [bitRateInput, carrierFreqInput, amplitudeInput, phaseOffsetInput, phaseOffsetSlider];
allInputs.forEach(input => {
input.addEventListener('input', () => { // Use 'input' for real-time slider updates
if (input.id === 'phaseOffsetSlider') phaseOffsetInput.value = input.value;
if (input.id === 'phaseOffset') phaseOffsetSlider.value = input.value;
updateParameters();
updateAllVisualizations();
});
});
window.addEventListener('resize', resizeCanvases);
updateParameters();
resizeCanvases();
});
</script>
</body>
</html>
```
I've made the following key changes to the logic:
1. **New Calculation Method:** The simulation now correctly models an IQ modulator.
* First, it determines the `base_amplitude` (either the full amplitude for a '1' or zero for a '0').
* Then, it uses trigonometry (`cos(φ)` and `sin(φ)`) to distribute that `base_amplitude` between the **I signal** and the **Q signal**.
* Finally, it modulates these new I and Q signals with their respective carriers (`cos(ωt)` and `sin(ωt)`) and combines them.
2. **Dynamic I/Q Graphs:** Now when you change the "Phase Offset," you will see the I and Q baseband signals change their values, which is exactly what happens in a real-world scenario. For example, at a 90-degree phase shift, all the energy moves from the I channel to the Q channel.
3. **Slider for Phase:** I've also added a slider for the phase offset for smoother, more intuitive control.
This updated version provides a much more accurate and insightful simulation of how phase is controlled in an IQ modulation sche