web analytics
October 22, 2015

ESP8266 – Connect to a network

To connect to an existing wireless network, switch the module into station mode and use the joinAP function. To connect, the network SSID (usually the network name) and password are required. Connecting can take several seconds depending on the quality of the connection.

#include "ESP8266.h"
#include "Phoenard.h"

// Initialize the module over Serial2 at 115200 baud
ESP8266 wifi(Serial2, 115200);

void setup() {
  Serial.begin(9600);  // Initialize Serial
  enableWiFi();        // Turn on module
  wifi.restart();      // Restart the module

  // Set to station mode
  if (wifi.setOprToStation()) {
    Serial.println("Station mode: OK");
  } else {
    Serial.println("Station mode: ERROR");
  }

  // Connect to a WiFi AP
  if (wifi.joinAP("MyNetworkID", "MyNetworkPassword")) {
    Serial.println("Join AP success:");
    Serial.println(wifi.getLocalIP());
  } else {
    Serial.println("Join AP failure");
  }
  
  // Start making connections over the network here
}

void loop() {
}

 

Listing networks

To list all available networks, the getAPList function can be used.

#include "ESP8266.h"
#include "Phoenard.h"

// Initialize the module over Serial2 at 115200 baud
ESP8266 wifi(Serial2, 115200);

void setup(void) {
  Serial.begin(9600);  // Initialize Serial
  enableWiFi();        // Turn on module
  wifi.restart();      // Restart the module

  // Set to station mode
  if (wifi.setOprToStation()) {
    Serial.println("Station mode: OK");
  } else {
    Serial.println("Station mode: ERROR");
  }

  // List all available networks
  String networks = wifi.getAPList();
  Serial.println(networks);

  /******************** Output ********************
   * +CWLAP:(ECN,"Network name",rssi,"MAC",channel)
   * +CWLAP:(0,"Network 1",-74,"aa:aa:aa:aa:aa:aa",1)
   * +CWLAP:(3,"Network 2",-73,"bb:bb:bb:bb:bb:bb",11)
   * +CWLAP:(4,"Network 3",-81,"cc:cc:cc:cc:cc:cc",11)
   * 
   * ECN:
   * 0 = OPEN
   * 1 = WEP
   * 2 = WPA_PSK
   * 3 = WPA2_PSK
   * 4 = WPA_WPA2_PSK
   *************************************************/
}

void loop() {
}