Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
en:iot-open:espressif_arduino [2023/10/09 11:01] – created ktokarzen:iot-open:espressif_arduino [2023/11/21 21:57] (current) ktokarz
Line 1: Line 1:
-==== ESP32 Wifi Scanner ==== +====== Programming ESP8266 for the Network ======
-There are many different development software and  tools which can be used for ESP32 programming ((https://esp32.net/#Development)): +
-  * Arduino COre ( C++) +
-  * ESP-IDF (Espressif IoT Development Framework)  +
-  * Mongoose OS +
-  * MicroPython +
-  * Simba Embedded Programming Platform  +
-  * Lua +
-  * JacvaSript +
-  * mruby +
-  * BASIC+
  
-Of course, for programming ESP32 We can use all the previously described Arduino examples for sensors and actuatorsBut in our example, we will focus on programming in ESP-IDF, as this is the native Development Platform for ESP32. A detailed description of the installation of the development environment can be found [[https://esp-idf.readthedocs.io/en/latest/get-started/windows-setup.html|here]].+Programming networking services with Espressif SoCs requires the connection established on the networking layer between parties, mainly with TCP protocol.\\ 
 +Below are two code examples for ESP8266 of how to implement access point and network station modes using libraries that came during installation of the development environment for Arduino framework.\\ 
 +The third example shows how to send and receive a UDP packet while in client mode. It is the full solution to connect ESP8266 to the NTP (Network Time Protocol) server to obtain the current date and time from the Internet.\\ 
 +Examples on further pages show how to make a handy WiFi scanner showing available networks nearby. 
 + 
 +== ESP8266 AP (Access Point) Mode == 
 +Based on a standard example, this program demonstrates how to program ESP8266 in AP mode. After compilation and uploading this programan ESP8266 starts serving as the access point that can be connected to, e.g., a smartphoneIt presents a simple web server available at the local IP address 192.168.4.1 (the default address of the ESP access point). This web server responds with a short message: "You are connected".
  
-This example shows how to use the All Channel Scan or Fast Scan to connect to a Wi-Fi network. In the Fast Scan mode, the scan will stop as soon as the first network matching the SSID is found. In this mode, an application can set the threshold for the authentication mode and the Signal strength. Networks that do not meet the threshold requirements will be ignored. In the All Channel Scan mode, the scan will end after all the channels are scanned, and the connection will start with the best network. The networks can be sorted based on Authentication Mode or Signal Strength. The priority for the Authentication mode is:  WPA2 > WPA > WEP > Open.  
 <code c> <code c>
-#include "freertos/FreeRTOS.h" 
-#include "freertos/event_groups.h" 
-#include "esp_wifi.h" 
-#include "esp_log.h" 
-#include "esp_event_loop.h" 
-#include "nvs_flash.h" 
  
-/*Set the SSID and Password via "make menuconfig"*/ +#include <ESP8266WiFi.h> 
-#define DEFAULT_SSID CONFIG_WIFI_SSID +#include <WiFiClient.h>  
-#define DEFAULT_PWD CONFIG_WIFI_PASSWORD+#include <ESP8266WebServer.h>
  
-#if CONFIG_WIFI_ALL_CHANNEL_SCAN +/* Set these variables to your desired credentials. */ 
-#define DEFAULT_SCAN_METHOD WIFI_ALL_CHANNEL_SCAN +const char *ssid = "APmode"; 
-#elif CONFIG_WIFI_FAST_SCAN +const char *password = "password";
-#define DEFAULT_SCAN_METHOD WIFI_FAST_SCAN +
-#else +
-#define DEFAULT_SCAN_METHOD WIFI_FAST_SCAN +
-#endif /*CONFIG_SCAN_METHOD*/+
  
-#if CONFIG_WIFI_CONNECT_AP_BY_SIGNAL +ESP8266WebServer server(80);
-#define DEFAULT_SORT_METHOD WIFI_CONNECT_AP_BY_SIGNAL +
-#elif CONFIG_WIFI_CONNECT_AP_BY_SECURITY +
-#define DEFAULT_SORT_METHOD WIFI_CONNECT_AP_BY_SECURITY +
-#else +
-#define DEFAULT_SORT_METHOD WIFI_CONNECT_AP_BY_SIGNAL +
-#endif /*CONFIG_SORT_METHOD*/+
  
-#if CONFIG_FAST_SCAN_THRESHOLD +void hRoot() { 
-#define DEFAULT_RSSI CONFIG_FAST_SCAN_MINIMUM_SIGNAL + server.send(200, "text/html", "<h1>You are connected</h1>"); 
-#if CONFIG_EXAMPLE_OPEN +}
-#define DEFAULT_AUTHMODE WIFI_AUTH_OPEN +
-#elif CONFIG_EXAMPLE_WEP +
-#define DEFAULT_AUTHMODE WIFI_AUTH_WEP +
-#elif CONFIG_EXAMPLE_WPA +
-#define DEFAULT_AUTHMODE WIFI_AUTH_WPA_PSK +
-#elif CONFIG_EXAMPLE_WPA2 +
-#define DEFAULT_AUTHMODE WIFI_AUTH_WPA2_PSK +
-#else +
-#define DEFAULT_AUTHMODE WIFI_AUTH_OPEN +
-#endif +
-#else +
-#define DEFAULT_RSSI -127 +
-#define DEFAULT_AUTHMODE WIFI_AUTH_OPEN +
-#endif /*CONFIG_FAST_SCAN_THRESHOLD*/+
  
-static const char *TAG = "scan";+/Initialization */ 
 +void setup() { 
 + delay(1500); 
 + /* You can remove the password parameter  
 +           if you want the AP to be open. */ 
 + WiFi.softAP(ssid, password);
  
-static esp_err_t event_handler(void *ctx, system_event_t *event+ IPAddress myIP = WiFi.softAPIP(); 
-{ + 
-    switch (event->event_id) { + server.on("/", hRoot); 
-        case SYSTEM_EVENT_STA_START: + server.begin(); 
-            ESP_LOGI(TAG, "SYSTEM_EVENT_STA_START"); +} 
-            ESP_ERROR_CHECK(esp_wifi_connect()); + 
-            break; +void loop() { 
-        case SYSTEM_EVENT_STA_GOT_IP: + server.handleClient(); 
-            ESP_LOGI(TAG, "SYSTEM_EVENT_STA_GOT_IP"); +
-            ESP_LOGI(TAG, "Got IP: %s\n", +</code> 
-                     ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip)); + 
-            break+== ESP8266 Client Mode == 
-        case SYSTEM_EVENT_STA_DISCONNECTED: +This standard example demonstrates how to program ESP8266 in client modeIt tries to connect to the WiFi network with a specified name (SSID) and password 
-            ESP_LOGI(TAG, "SYSTEM_EVENT_STA_DISCONNECTED"); +<code c> 
-            ESP_ERROR_CHECK(esp_wifi_connect())+ 
-            break; +#include <ESP8266WiFi.h> 
-        default: +#include <ESP8266WiFiMulti.h> 
-            break;+ 
 +ESP8266WiFiMulti WiFiMulti; 
 + 
 +void setup(
 +    delay(1000); 
 +     
 +    // Initialise serial port to monitor program behaviour 
 +    Serial.begin(115200)
 + 
 +    // We start by connecting to a WiFi network 
 +    WiFi.mode(WIFI_STA); 
 +    WiFiMulti.addAP("SSID", "password"); 
 + 
 +    while(WiFiMulti.run() != WL_CONNECTED{ 
 +        delay(500);
     }     }
-    return ESP_OK;+    delay(500);
 } }
  
-/Initialize Wi-Fi as sta and set scan method */ + 
-static void wifi_scan(void)+void loop() { 
 +    const uint16_t port = 80; 
 +    const char host = "192.168.1.1"; // ip or dns 
 + 
 +    // Use WiFiClient class to create TCP connections 
 +    WiFiClient client; 
 + 
 +    if (!client.connect(host, port)) { 
 +        delay(5000); 
 +        return; 
 +    } 
 +    // This will print the IP address assigned by the DHCP server 
 +    Serial.println(WiFi.localIP()); 
 + 
 +    // This will send the request to the server 
 +    client.println("Send this data to server"); 
 +    // Trying to send the GET request possibly responses (with error) 
 +    // client.println("GET /echo"); 
 + 
 +    //read back one line from server 
 +    String line = client.readStringUntil('\r'); 
 +    Serial.println(line); 
 + 
 +    Serial.println("closing connection"); 
 +    client.stop(); 
 +     
 +    Serial.println("wait 5 sec..."); 
 +    delay(5000); 
 +
 +</code> 
 + 
 +== ESP8266 and UDP == 
 +This sketch (based on a standard example) demonstrates how to program ESP8266 as an NTP client using UDP packets (send and receive): 
 +<code c> 
 + 
 +#include <ESP8266WiFi.h> 
 +#include <WiFiUdp.h> 
 + 
 + 
 +char ssid[] = "**************";  //  your network SSID (name) 
 +char pass[] = "**************";  // your network password 
 + 
 +unsigned int localPort = 2390;   // local port to listen for UDP packets 
 + 
 +// NTP servers 
 +IPAddress ntpServerIP; // 0.pl.pool.ntp.org NTP server address 
 +const char* ntpServerName[] =  
 + {"0.pl.pool.ntp.org","1.pl.pool.ntp.org","2.pl.pool.ntp.org","3.pl.pool.ntp.org"}; 
 + 
 +const int timeZone = 1;  //Central European Time 
 +int servernbr=0; 
 + 
 +// NTP time stamp is in the first 48 bytes of the message 
 +const int NTP_PACKET_SIZE = 48;  
 + 
 +//buffer to hold incoming and outgoing packets 
 +byte packetBuffer[ NTP_PACKET_SIZE];  
 + 
 +// A UDP instance to let us send and receive packets over UDP 
 +WiFiUDP udp; 
 + 
 +// Prototype of the function defined at the end of this file  
 +// (required in Visual Studio Code) 
 +void sendNTPpacket(IPAddress& address); 
 + 
 +void setup()
 { {
-    tcpip_adapter_init(); +  Serial.begin(115200); 
-    ESP_ERROR_CHECK(esp_event_loop_init(event_handlerNULL));+  Serial.println(); 
 +    
 +  Serial.print("Connecting to "); 
 +  Serial.println(ssid); 
 +   
 +//  WiFi.persistent(false); 
 +  WiFi.mode(WIFI_OFF); 
 +  delay(2000); 
 +   
 +// We start by connecting to a WiFi network 
 +  WiFi.mode(WIFI_STA); 
 +  delay(3000);  
 +  WiFi.begin(ssidpass);  
 +   
 +  while (WiFi.status() != WL_CONNECTED) {    
 +    delay(500); 
 +    Serial.print("."); 
 +  } 
 +     
 +  Serial.println(""); 
 +   
 +  Serial.println("WiFi connected"); 
 +  Serial.println("DHCP assigned IP address: "); 
 +  Serial.println(WiFi.localIP());
  
-    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); +  Serial.println("Starting UDP"); 
-    ESP_ERROR_CHECK(esp_wifi_init(&cfg)); +  udp.begin(localPort); 
- ESP_LOGI(TAG, DEFAULT_SSID); +  Serial.print("Local port: "); 
- ESP_LOGI(TAG, DEFAULT_PWD); +  Serial.println(udp.localPort()); 
-    wifi_config_t wifi_config = { + 
-        .sta = { +  // first ntp server 
-            .ssid = DEFAULT_SSID, +  servernbr = 0;
-            .password = DEFAULT_PWD, +
-            .scan_method = DEFAULT_SCAN_METHOD, +
-            .sort_method = DEFAULT_SORT_METHOD, +
-            .threshold.rssi = DEFAULT_RSSI, +
-            .threshold.authmode = DEFAULT_AUTHMODE, +
-        }, +
-    }; +
-    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); +
-    ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config)); +
-    ESP_ERROR_CHECK(esp_wifi_start());+
 } }
  
-void app_main()+void loop()
 { {
-    // Initialize NVS +  //get a random server from the pool 
-    esp_err_t ret = nvs_flash_init(); + 
-    if (ret == ESP_ERR_NVS_NO_FREE_PAGES{ +  WiFi.hostByName(ntpServerName[servernbr], ntpServerIP);  
-        ESP_ERROR_CHECK(nvs_flash_erase()); +  Serial.print(ntpServerName[servernbr]) 
-        ret nvs_flash_init();+  Serial.print(":"); 
 +  Serial.println(ntpServerIP)
 + 
 +  // send an NTP packet to a time server 
 +  sendNTPpacket(ntpServerIP);  
 +   
 +  // wait to see if a reply is available 
 +  delay(1000); 
 +   
 +  int cb udp.parsePacket()
 +  if (!cb) { 
 +    Serial.println("no packet yet"); 
 +    if ( servernbr = 5 ) { 
 +      servernbr =0;
     }     }
-    ESP_ERROR_CHECKret );+    else { 
 +      servernbr++; 
 +    } 
 +  } 
 +  else { 
 +    Serial.print("packet received, length="); 
 +    Serial.println(cb); 
 +    // We've received a packet, read the data from it 
 +    // read the packet into the buffer 
 +    udp.read(packetBuffer, NTP_PACKET_SIZE); 
  
-    wifi_scan(); +    // the timestamp starts at byte 40  
-} +    // of the received packet and is four bytes, 
-</code>+    /or two words, long. First, extract the two words:
  
-To properly set up Station modeit is necessary to enter SSID and password. To enter these valuesbefore compiling the program, run the command:+    unsigned long highWord = word(packetBuffer[40]packetBuffer[41]); 
 +    unsigned long lowWord = word(packetBuffer[42]packetBuffer[43]); 
 +    // combine the four bytes (two words) into a long integer 
 +    // this is NTP time (seconds since Jan 1 1900): 
 +    unsigned long secsSince1900 = highWord << 16 | lowWord; 
 +    Serial.print("Seconds since Jan 1 1900 = " ); 
 +    Serial.println(secsSince1900);
  
-<code c> +    // now convert NTP time into everyday time: 
-make menuconfig +    Serial.print("Unix time = "); 
-</code>+    // Unix time starts on Jan 1 1970.  
 +    // In seconds, that's 2208988800: 
 +    const unsigned long seventyYears = 2208988800UL; 
 +    // subtract seventy years: 
 +    unsigned long epoch = secsSince1900 - seventyYears; 
 +    // print Unix time: 
 +    Serial.println(epoch);
  
-and then  
  
-<code c> +    // print the hour, minute and second: 
-make all +    // UTC is the time at Greenwich Meridian (GMT) 
-</code>+    Serial.print("The UTC time is ");        
 +    // print the hour (86400 equals secs per day) 
 +    Serial.print((epoch  % 86400L) / 3600);  
 +    Serial.print(':'); 
 +    if ( ((epoch % 3600) / 60) 10 ) { 
 +      // In the first 10 minutes of each hour, we'll want a leading '0' 
 +      Serial.print('0'); 
 +    } 
 +    // print the minute (3600 equals secs per minute) 
 +    Serial.print((epoch  % 3600) / 60);  
 +    Serial.print(':'); 
 +    if ( (epoch % 60) 10 ) { 
 +      // In the first 10 seconds of each minute, we'll want a leading '0' 
 +      Serial.print('0'); 
 +    } 
 +    Serial.println(epoch % 60); // print the second 
 +  } 
 +  // wait ten seconds before asking for the time again 
 +  delay(10000); 
 +}
  
-or +// send an NTP request to the time server at the given address 
 +void sendNTPpacket(IPAddress& address) 
 +
 +  Serial.print("sending NTP packet to: "); 
 +  Serial.println( address ); 
 +  // set all bytes in the buffer to 0 
 +  memset(packetBuffer, 0, NTP_PACKET_SIZE); 
 +  // Initialize values needed to form NTP request 
 +  // (see URL above for details on the packets) 
 +  packetBuffer[0] = 0b11100011;   // LI, Version, Mode 
 +  packetBuffer[1] = 0;     // Stratum, or type of clock 
 +  packetBuffer[2] = 6;     // Polling Interval 
 +  packetBuffer[3] = 0xEC;  // Peer Clock Precision 
 +  // 8 bytes of zero for Root Delay & Root Dispersion 
 +  packetBuffer[12]  = 49; 
 +  packetBuffer[13]  = 0x4E; 
 +  packetBuffer[14]  = 49; 
 +  packetBuffer[15]  = 52;
  
-<code c> +  // all NTP fields have been given values, now 
-make flash +  // you can send a packet requesting a timestamp: 
-</code>+  udp.beginPacket(address, 123); //NTP requests are to port 123 
 +  udp.write(packetBuffer, NTP_PACKET_SIZE); 
 +  udp.endPacket(); 
 +}
  
 +</code>
  
en/iot-open/espressif_arduino.1696849284.txt.gz · Last modified: 2023/10/09 11:01 by ktokarz
CC Attribution-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0