Try this code main.py:
from machine import UART, Pin
import time
# Set up UART (adjust the TX and RX pins to match your hardware)
uart = UART(0, baudrate=115200, tx=Pin(0), rx=Pin(1))
# Function to send an AT command and wait for the response
def send_at_command(command, timeout=5000):
uart.write(command + "\r\n")
time.sleep(0.1)
start = time.ticks_ms()
response = b""
while time.ticks_diff(time.ticks_ms(), start) < timeout:
if uart.any():
data = uart.read()
if data is not None:
response += data
if not response:
print("No response received for command:", command)
return response
# Disable AP mode and set to STA mode
response = send_at_command("AT+CWMODE=1", timeout=2000)
print("Set to STA mode:", response.decode())
# Scan for available Wi-Fi networks
response = send_at_command("AT+CWLAP", timeout=10000)
print("Available Networks:", response.decode())
# Send AT command to connect to the Wi-Fi
ssid = "YOUR SSID"
password = "YOUR PASSWORD"
response = send_at_command('AT+CWJAP="{}", "{}"'.format(ssid, password), timeout=20000)
print("Connection attempt response:", response.decode())
# Check IP address if successfully connected
response = send_at_command("AT+CIFSR", timeout=5000)
print("IP Address:", response.decode())