Connecting to Arduino alvik using Nano ESP32

Hi all!

I'm working on developing a lab for class using the Alvik. We want to log some data while the bot is running and I figured the best way to do this was to use the built-in esp32 chip. I'm attempting to follow the instructions in the Alvik documentation but we're having issues.

Firstly, here is the code I'm using, pulled directly from the docs.

import network
import socket
from arduino_alvik import ArduinoAlvik
from time import sleep_ms

# Wi-Fi credentials
SSID = "my ssid"
PASSWORD = ""

sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
if not sta_if.isconnected():
    print("\nConnecting to network...", SSID)
    sta_if.connect(SSID)

    # Wait for connection with a timeout
    timeout = 10  # 10 seconds timeout
    for _ in range(timeout * 10):
        if sta_if.isconnected():
            break
        sleep_ms(100)

if sta_if.isconnected():
    print("Connected to WiFi. IP address:", sta_if.ifconfig()[0])
else:
    print("Failed to connect to WiFi. Please check your credentials and signal strength.")


# Initialize the robot
alvik = ArduinoAlvik()
alvik.begin()
sleep_ms(5000)

# HTML for the web interface
html = """
<!DOCTYPE html>
<html>
<head>
<title>Alvik Robot Control</title>
</head>
<body>
<h1>Control Alvik Robot</h1>
<form action="/up">
    <button type="submit">Up</button>
</form>
<form action="/down">
    <button type="submit">Down</button>
</form>
<form action="/left">
    <button type="submit">Left</button>
</form>
<form action="/right">
    <button type="submit">Right</button>
</form>
</body>
</html>
"""

# Specify a port
port = 8080
addr = socket.getaddrinfo('0.0.0.0', port)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(5)

s.settimeout(5) 

print(f'Listening on {sta_if.ifconfig()[0]}:{port}')

# Function to handle incoming HTTP requests
def handle_request(conn):
    try:
        request = conn.recv(1024).decode('utf-8')
        first_line = request.split('\n')[0]  # Get the first line of the request
        path = first_line.split(' ')[1]  # Extract the path (e.g., "/up")

        # Strip query strings (e.g., "/up?")
        if '?' in path:
            path = path.split('?')[0]
        print(f"Request path: {path}")

        # Ignore favicon requests
        if path == '/favicon.ico':
            conn.send('HTTP/1.1 204 No Content\n')
            conn.send('Connection: close\n\n')
            return

        # Control the robot based on the request path
        if path == '/up':
            alvik.set_wheels_speed(30, 30)
        elif path == '/down':
            alvik.set_wheels_speed(-30, -30)
        elif path == '/left':
            alvik.set_wheels_speed(-30, 30)
        elif path == '/right':
            alvik.set_wheels_speed(30, -30)
        else:
            alvik.brake()

        # Send the response for valid paths
        conn.send('HTTP/1.1 200 OK\n')
        conn.send('Content-Type: text/html\n')
        conn.send('Connection: close\n\n')
        conn.sendall(html)

    except OSError as e:
        if e.errno == 104:  # ECONNRESET error
            print("Connection reset by client.")
        else:
            print(f"Error: {e}")
    finally:
        conn.close()

# Main loop to handle incoming connections
try:
    while True:
        try:
            conn, addr = s.accept()
            print('Connection from', addr)
            handle_request(conn)
        except OSError as e:
            if e.errno == 116:  # ETIMEDOUT error
                print("Waiting for connection...")
            elif e.errno == 104:  # ECONNRESET error
                print("Connection reset by client.")
            else:
                print(f"Accept error: {e}")
except KeyboardInterrupt:
    print("Server stopped")
    s.close()
    alvik.stop()

I replaced the ssid and password with the necessary credentials (we don't have a password on the wifi I'm trying to use). We're running this in ArduinoLab with Micropython, since that is what was recommended for the Alvik. I was able to get this working while connected to a hotspot, but now we're trying with a different wifi. I get this message in the terminal

OKConnected to WiFi. IP address: XX.X.XXX.XXX

and eventually

Listening on XX.X.XXX.XXX:8080

which tells me it's made an ip and connected. However, after this I just get "Waiting for connection..." over and over again, and pinging the ip address gives me a timeout error. So something is wrong.

I haven't been able to get this working on Arduino IDE, as I get "dfu-util: No DFU capable USB device available" when I attempt to upload even just a blink() sketch to the board (yes I connected the Arduino Nano ESP32 board and a usb port so that isn't the issue. I suspect this is due to the Nano being part of the Alvik and not it's own board), So I think I have to use MicroPython.

I know this is possible because we got it working with a hotspot, like we had a website and were able to send a command to make the bot move, but that isn't sustainable for lab purposes. Does anyone have any advice/insight onto this subject? I'd appreciate just about anything. Thank you!!

Perhaps it's a matter of I.T. and Security.
At work, all I can do with ESP-whichever is access NTP server.

You posted in the Arduino Nano ESP32 section.
This is reserved for only questions about the official Arduino Nano board.

As your question concerned a processor that is not the official one but

Therefore I have moved your post here.

You might want to look at this How to get the best out of this forum before you proceed any further.
We only know what you tell us, and without knowing what you have, we don't stand a chance.

I was able to fix this issue by removing my nano board (thanks Delta_G!) from the bot and grounding my B1 pin. There's some documentation on doing that with nano esp32 boards so that resolved this issue. However, even with an arduino code that does virtually the same thing, there's still no connectivity to our internet

Here's the code (we don't need a password for our wifi)

#include <WiFi.h>

// Replace this with your open network's SSID
const char* ssid = "yourSSID";

void setup() {
  Serial.begin(115200);
  delay(10);

  // Connect to the open Wi-Fi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  // Initialize WiFi with SSID only (no password)
  WiFi.begin(ssid);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  // Placeholder for loop actions
}

I'm assuming at this point it's a network issue, rather than something wrong with the board itself. But maybe there's something I'm missing

1 Like

Yeah, I think it's the fact our uni wifi is 5 GHz but the esp32 chip needs 2.4. I'll see what I can figure out. Thanks for your help!

If there is, it's not easy to find! :melting_face:

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