Skip to content

Web Server Test

In this lab we will create a web interface to test all your robot's hardware:

  1. LED control with visual feedback
  2. NeoPixel colors with real-time status updates
  3. Speaker tones at different frequencies
  4. Motor movements with automatic 2-second safety timeouts
  5. Emergency stop functionality

The debugging output in the Thonny console should also help you understand exactly what's happening when each command is executed. This makes it a great development and testing tool for your STEM robot project.

Web Test Form

Thonny Console Log

  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
>>> %Run -c $EDITOR_CONTENT

MPY: soft reboot
Robot Web Server Test Interface
===================================
NeoPixels set to off
Connecting to WiFi Network: anndan
Powering up WiFi chip...
Connection attempt 1/10


==================================================
WIFI CONNECTION SUCCESSFUL!
==================================================
IP Address: 10.0.0.57
Network: anndan
==================================================

Web server started!
Open your browser and go to: http://10.0.0.57
Robot control interface ready!
==================================================
Client connected from ('10.0.0.2', 58686)
Full request received (482 bytes)
Client connected from ('10.0.0.2', 58687)
Full request received (420 bytes)
Unknown request: GET /favicon.ico HTTP/1.1
Host: 10.0.0.57
Connection: keep-alive
Pragma: no-cache
Cache-Control:...
Client connected from ('10.0.0.2', 58688)
Full request received (422 bytes)
POST request received, length: 422
Request body: 'cmd=toggle_led'
Executing command: 'toggle_led'
LED turned ON
Command 'toggle_led' executed successfully
Client connected from ('10.0.0.2', 58690)
Full request received (493 bytes)
Client connected from ('10.0.0.2', 58691)
Full request received (422 bytes)
POST request received, length: 422
Request body: 'cmd=toggle_led'
Executing command: 'toggle_led'
LED turned OFF
Command 'toggle_led' executed successfully
Client connected from ('10.0.0.2', 58692)
Full request received (424 bytes)
POST request received, length: 424
Request body: 'cmd=neopixel_red'
Executing command: 'neopixel_red'
NeoPixels set to red
Command 'neopixel_red' executed successfully
Client connected from ('10.0.0.2', 58693)
Full request received (493 bytes)
Client connected from ('10.0.0.2', 58694)
Full request received (426 bytes)
POST request received, length: 426
Request body: 'cmd=neopixel_green'
Executing command: 'neopixel_green'
NeoPixels set to green
Command 'neopixel_green' executed successfully
Client connected from ('10.0.0.2', 58698)
Full request received (425 bytes)
POST request received, length: 425
Request body: 'cmd=neopixel_blue'
Executing command: 'neopixel_blue'
NeoPixels set to blue
Command 'neopixel_blue' executed successfully
Client connected from ('10.0.0.2', 58699)
Full request received (424 bytes)
POST request received, length: 424
Request body: 'cmd=neopixel_off'
Executing command: 'neopixel_off'
NeoPixels set to off
Command 'neopixel_off' executed successfully
Client connected from ('10.0.0.2', 58700)
Full request received (421 bytes)
POST request received, length: 421
Request body: 'cmd=play_tone'
Executing command: 'play_tone'
Played tone: 1000Hz for 0.5s
Command 'play_tone' executed successfully
Client connected from ('10.0.0.2', 58701)
Full request received (424 bytes)
POST request received, length: 424
Request body: 'cmd=move_forward'
Executing command: 'move_forward'
Moving forward
Command 'move_forward' executed successfully
Client connected from ('10.0.0.2', 58702)
Full request received (423 bytes)
POST request received, length: 423
Request body: 'cmd=stop_motors'
Executing command: 'stop_motors'
Command 'stop_motors' executed successfully
Client connected from ('10.0.0.2', 58703)
Full request received (424 bytes)
POST request received, length: 424
Request body: 'cmd=move_reverse'
Executing command: 'move_reverse'
Moving reverse
Command 'move_reverse' executed successfully
Client connected from ('10.0.0.2', 58704)
Full request received (423 bytes)
POST request received, length: 423
Request body: 'cmd=stop_motors'
Executing command: 'stop_motors'
Command 'stop_motors' executed successfully

Source Code

  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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import network
import socket
import secrets
import time
from machine import Pin, PWM
import neopixel
import config

# Hardware setup based on config.py
led = Pin("LED", Pin.OUT)

# Motor PWM setup
right_forward = PWM(Pin(config.RIGHT_FORWARD_PIN))
right_reverse = PWM(Pin(config.RIGHT_REVERSE_PIN))
left_forward = PWM(Pin(config.LEFT_FORWARD_PIN))
left_reverse = PWM(Pin(config.LEFT_REVERSE_PIN))

# Set PWM frequency for motors (1000 Hz is good for motors)
right_forward.freq(1000)
right_reverse.freq(1000)
left_forward.freq(1000)
left_reverse.freq(1000)

# NeoPixel setup
np = neopixel.NeoPixel(Pin(config.NEOPIXEL_PIN), config.NUMBER_NEOPIXELS)

# Speaker setup
speaker = PWM(Pin(config.SPEAKER_PIN))

# Global variables for state tracking
led_state = False
current_neopixel_color = "off"

def blink_led(times=1, delay=0.2):
    """Blink the onboard LED for status indication"""
    for _ in range(times):
        led.on()
        time.sleep(delay)
        led.off()
        time.sleep(delay)

def connect_wifi(max_retries=10):
    """Connect to WiFi with retry logic"""
    print(f'Connecting to WiFi Network: {secrets.SSID}')

    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

    # Disable power management for better responsiveness
    wlan.config(pm=0xa11140)

    print('Powering up WiFi chip...')
    time.sleep(3)

    retry_count = 0
    while retry_count < max_retries:
        try:
            print(f'Connection attempt {retry_count + 1}/{max_retries}')
            wlan.connect(secrets.SSID, secrets.PASSWORD)

            timeout = 15
            start_time = time.time()

            while not wlan.isconnected() and (time.time() - start_time) < timeout:
                time.sleep(1)
                print('.', end='')

            print()

            if wlan.isconnected():
                return wlan
            else:
                print(f'Timeout on attempt {retry_count + 1}')
                retry_count += 1
                time.sleep(2)

        except Exception as e:
            print(f'Error on attempt {retry_count + 1}: {e}')
            retry_count += 1
            time.sleep(2)

    return None

def stop_motors():
    """Stop all motors"""
    right_forward.duty_u16(0)
    right_reverse.duty_u16(0)
    left_forward.duty_u16(0)
    left_reverse.duty_u16(0)

def move_forward():
    """Move robot forward"""
    stop_motors()
    time.sleep(0.1)
    right_forward.duty_u16(32000)  # About 50% power
    left_forward.duty_u16(32000)
    print("Moving forward")

def move_reverse():
    """Move robot in reverse"""
    stop_motors()
    time.sleep(0.1)
    right_reverse.duty_u16(32000)
    left_reverse.duty_u16(32000)
    print("Moving reverse")

def turn_right():
    """Turn robot right"""
    stop_motors()
    time.sleep(0.1)
    left_forward.duty_u16(32000)   # Left wheel forward
    right_reverse.duty_u16(32000)  # Right wheel reverse
    print("Turning right")

def turn_left():
    """Turn robot left"""
    stop_motors()
    time.sleep(0.1)
    right_forward.duty_u16(32000)  # Right wheel forward
    left_reverse.duty_u16(32000)   # Left wheel reverse
    print("Turning left")

def set_neopixels(color):
    """Set NeoPixels to specified color"""
    global current_neopixel_color
    current_neopixel_color = color

    if color == "red":
        for i in range(config.NUMBER_NEOPIXELS):
            np[i] = (255, 0, 0)
    elif color == "green":
        for i in range(config.NUMBER_NEOPIXELS):
            np[i] = (0, 255, 0)
    elif color == "blue":
        for i in range(config.NUMBER_NEOPIXELS):
            np[i] = (0, 0, 255)
    else:  # off
        for i in range(config.NUMBER_NEOPIXELS):
            np[i] = (0, 0, 0)

    np.write()
    print(f"NeoPixels set to {color}")

def play_tone(frequency=1000, duration=0.5):
    """Play a tone on the speaker"""
    speaker.freq(frequency)
    speaker.duty_u16(32768)  # 50% duty cycle
    time.sleep(duration)
    speaker.duty_u16(0)  # Turn off
    print(f"Played tone: {frequency}Hz for {duration}s")

def toggle_led():
    """Toggle the onboard LED"""
    global led_state
    led_state = not led_state
    if led_state:
        led.on()
        print("LED turned ON")
    else:
        led.off()
        print("LED turned OFF")

def generate_html():
    """Generate the HTML page for robot control"""
    html = f"""
<!DOCTYPE html>
<html>
<head>
    <title>Robot Test Interface</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {{
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f0f0f0;
        }}
        .container {{
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #333;
            text-align: center;
        }}
        .section {{
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }}
        .section h3 {{
            margin-top: 0;
            color: #555;
        }}
        button {{
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }}
        button:hover {{
            background-color: #45a049;
        }}
        .motor-btn {{
            background-color: #2196F3;
        }}
        .motor-btn:hover {{
            background-color: #1976D2;
        }}
        .stop-btn {{
            background-color: #f44336;
        }}
        .stop-btn:hover {{
            background-color: #d32f2f;
        }}
        .status {{
            margin-top: 20px;
            padding: 10px;
            background-color: #e8f5e8;
            border-radius: 5px;
        }}
        .color-buttons {{
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }}
        .red-btn {{ background-color: #f44336; }}
        .green-btn {{ background-color: #4CAF50; }}
        .blue-btn {{ background-color: #2196F3; }}
        .off-btn {{ background-color: #757575; }}
    </style>
</head>
<body>
    <div class="container">
        <h1>Robot Test Interface v2</h1>

        <div class="section">
            <h3>Onboard LED</h3>
            <button onclick="sendCommand('toggle_led')">Toggle LED</button>
            <p>Current state: <span id="led-status">{'ON' if led_state else 'OFF'}</span></p>
        </div>

        <div class="section">
            <h3>NeoPixels</h3>
            <div class="color-buttons">
                <button class="red-btn" onclick="sendCommand('neopixel_red')">Red</button>
                <button class="green-btn" onclick="sendCommand('neopixel_green')">Green</button>
                <button class="blue-btn" onclick="sendCommand('neopixel_blue')">Blue</button>
                <button class="off-btn" onclick="sendCommand('neopixel_off')">Off</button>
            </div>
            <p>Current color: <span id="neopixel-status">{current_neopixel_color}</span></p>
        </div>

        <div class="section">
            <h3>Speaker</h3>
            <button onclick="sendCommand('play_tone')">Play Tone (1000Hz)</button>
            <button onclick="sendCommand('play_tone_low')">Low Tone (500Hz)</button>
            <button onclick="sendCommand('play_tone_high')">High Tone (1500Hz)</button>
        </div>

        <div class="section">
            <h3>Motor Control</h3>
            <div>
                <button class="motor-btn" onclick="sendCommand('move_forward')">Forward</button>
                <button class="motor-btn" onclick="sendCommand('move_reverse')">Reverse</button>
            </div>
            <div>
                <button class="motor-btn" onclick="sendCommand('turn_left')">Turn Left</button>
                <button class="motor-btn" onclick="sendCommand('turn_right')">Turn Right</button>
            </div>
            <div>
                <button class="stop-btn" onclick="sendCommand('stop_motors')">STOP</button>
            </div>
            <p><em>Note: Motors will run for 2 seconds then auto-stop</em></p>
        </div>

        <div class="status">
            <h3>System Status</h3>
            <p>WiFi: Connected</p>
            <p>Last command: <span id="last-command">None</span></p>
        </div>
    </div>

    <script>
        function sendCommand(command) {{
            console.log('Sending command:', command);
            document.getElementById('last-command').textContent = 'Sending: ' + command;

            fetch('/command', {{
                method: 'POST',
                headers: {{
                    'Content-Type': 'application/x-www-form-urlencoded',
                }},
                body: 'cmd=' + encodeURIComponent(command)
            }})
            .then(response => {{
                console.log('Response status:', response.status);
                return response.text();
            }})
            .then(data => {{
                console.log('Response data:', data);
                document.getElementById('last-command').textContent = command + ' (' + data + ')';

                // Update status displays based on command
                if (command === 'toggle_led') {{
                    // Will be updated on next page load or we can toggle the display
                    setTimeout(() => location.reload(), 500);
                }}
                if (command.startsWith('neopixel_')) {{
                    const color = command.replace('neopixel_', '');
                    document.getElementById('neopixel-status').textContent = color;
                }}
            }})
            .catch(error => {{
                console.error('Error:', error);
                document.getElementById('last-command').textContent = 'Error: ' + command + ' - ' + error.message;
            }});
        }}

        // Add some debug info
        console.log('Robot control interface loaded');
    </script>
</body>
</html>
"""
    return html

def handle_command(command):
    """Handle robot commands from web interface"""
    try:
        if command == "toggle_led":
            toggle_led()
        elif command == "neopixel_red":
            set_neopixels("red")
        elif command == "neopixel_green":
            set_neopixels("green")
        elif command == "neopixel_blue":
            set_neopixels("blue")
        elif command == "neopixel_off":
            set_neopixels("off")
        elif command == "play_tone":
            play_tone(1000, 0.5)
        elif command == "play_tone_low":
            play_tone(500, 0.5)
        elif command == "play_tone_high":
            play_tone(1500, 0.5)
        elif command == "move_forward":
            move_forward()
            time.sleep(2)  # Run for 2 seconds
            stop_motors()
        elif command == "move_reverse":
            move_reverse()
            time.sleep(2)
            stop_motors()
        elif command == "turn_left":
            turn_left()
            time.sleep(2)
            stop_motors()
        elif command == "turn_right":
            turn_right()
            time.sleep(2)
            stop_motors()
        elif command == "stop_motors":
            stop_motors()
        else:
            print(f"Unknown command: {command}")
            return False
        return True
    except Exception as e:
        print(f"Error executing command {command}: {e}")
        return False

def start_web_server(wlan):
    """Start the web server"""
    addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(1)

    ip = wlan.ifconfig()[0]
    print(f'\nWeb server started!')
    print(f'Open your browser and go to: http://{ip}')
    print(f'Robot control interface ready!')
    print('='*50)

    while True:
        try:
            cl, addr = s.accept()
            print(f'Client connected from {addr}')

            # Set a timeout for receiving data
            cl.settimeout(2.0)

            # Read the request in chunks to ensure we get it all
            request = b''
            try:
                while True:
                    chunk = cl.recv(1024)
                    if not chunk:
                        break
                    request += chunk
                    # Check if we have the complete request
                    if b'\r\n\r\n' in request:
                        break
            except:
                # Timeout or error reading - proceed with what we have
                pass

            request = request.decode('utf-8')
            print(f"Full request received ({len(request)} bytes)")

            # Parse the request
            if 'GET / ' in request:
                # Serve the main page
                response = generate_html()
                cl.send('HTTP/1.1 200 OK\r\n')
                cl.send('Content-Type: text/html\r\n')
                cl.send(f'Content-Length: {len(response)}\r\n')
                cl.send('\r\n')
                cl.send(response)

            elif 'POST /command' in request:
                # Handle command - improved parsing with debugging
                print(f"POST request received, length: {len(request)}")

                # Find the body of the request
                body_start = request.find('\r\n\r\n')
                if body_start != -1:
                    body = request[body_start + 4:]
                    print(f"Request body: '{body}'")

                    # Parse URL-encoded data
                    if body.startswith('cmd='):
                        command = body[4:].strip()  # Remove 'cmd=' prefix and whitespace
                        print(f"Executing command: '{command}'")
                        success = handle_command(command)

                        if success:
                            response = "OK"
                            print(f"Command '{command}' executed successfully")
                        else:
                            response = "ERROR"
                            print(f"Command '{command}' failed")

                        cl.send('HTTP/1.1 200 OK\r\n')
                        cl.send('Content-Type: text/plain\r\n')
                        cl.send('Access-Control-Allow-Origin: *\r\n')
                        cl.send(f'Content-Length: {len(response)}\r\n')
                        cl.send('\r\n')
                        cl.send(response)
                    else:
                        print(f"Invalid body format: '{body}'")
                        cl.send('HTTP/1.1 400 Bad Request\r\n\r\n')
                else:
                    print("No body found in POST request")
                    cl.send('HTTP/1.1 400 Bad Request\r\n\r\n')
            else:
                # 404 for other requests
                print(f"Unknown request: {request[:100]}...")
                cl.send('HTTP/1.1 404 Not Found\r\n\r\n')

        except Exception as e:
            print(f'Web server error: {e}')
        finally:
            try:
                cl.close()
            except:
                pass

def main():
    """Main program function"""
    print('Robot Web Server Test Interface')
    print('===================================')

    # Initialize hardware
    stop_motors()
    set_neopixels("off")
    led.off()

    # Initial LED indication
    blink_led(2, 0.5)

    # Connect to WiFi
    wlan = connect_wifi()

    if wlan:
        config = wlan.ifconfig()
        print('\n' + '='*50)
        print('WIFI CONNECTION SUCCESSFUL!')
        print('='*50)
        print(f'IP Address: {config[0]}')
        print(f'Network: {secrets.SSID}')
        print('='*50)

        blink_led(3, 0.2)  # Success indication

        # Start the web server
        start_web_server(wlan)
    else:
        print('\nFAILED TO CONNECT!')
        print('Check your secrets.py file for correct SSID and PASSWORD')
        blink_led(10, 0.1)  # Error indication

if __name__ == '__main__':
    main()