Micropython script works unless IDE connected

The following main.py script works perfectly if the NanoESP32 is powered from another source and not connected to the Arduino Lab for Micropython IDE. It shows "Server listening" on the OLED screen and if I send it some code it tries it and reports "Code ran OK" on the OLED screen and "Code ran successfully" on the serial monitor of the client device if the code is good and the error on the OLED and on the serial monitor of the client device if the code is bad. Everything works as I intended.

However if I connect the NanoESP32 to the Arduino Lab for Micropython IDE I cannot get the server to listen reliably. I have to press the IDE Reset, Stop and Run buttons tens of time and sometimes the server starts to listen, but usually I get a warning that "line 32, in
OSError: [Errno 112] EADDRINUSE" (usually) or "", line 21, "in OSError: Wifi Internal Error" (sometimes)

I have changed the port to 8080 but that hasn't helped.

Here is the code:

import network
import socket
from machine import Pin, SoftI2C
import ssd1306

# ESP32 Pin assignment 
i2c = SoftI2C(scl=Pin(18), sda=Pin(21))

# ESP8266 Pin assignment
#i2c = SoftI2C(scl=Pin(5), sda=Pin(4))

oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

# Connect to your WiFi network
wifi_ssid = "XXXXXXXX"
wifi_password = "XXXXXXXXX"
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(wifi_ssid, wifi_password)

# Wait until connected to Wi-Fi
while not wifi.isconnected():
    pass

# Configure server
server_address = ('192.168.178.54', 8080)  # Use port 8080
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(server_address)
server_socket.listen(1)

print("Server is up and listening...")
oled.text('Server listening', 0, 0)
oled.show()

while True:
    print("Waiting for a connection...")
    client_socket, client_address = server_socket.accept()
    print("Client connected:", client_address)

    try:
        while True:
            data = client_socket.recv(1024).decode().strip()
            if data:
                print(data)
                exec(data)
                print("Code ran successfully")
                oled.text('Code ran OK', 0, 20)
                oled.show()
                response = "Code ran successfully"
                break
    except Exception as e:
        print("Error:", e)
        oled.text(str(e), 0, 20)
        oled.show()
        response = str(e)
    finally:
        client_socket.sendall(response.encode())
        client_socket.close()
        server_socket.close()

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.