Basic Library
Digital I/O
Analog I/O
Advanced I/O
Time
Math
Trigonometry
Random Numbers
Bits and Bytes
Interrupts
Serial Comm.
Standard Library
Camera
Servo Motor
Stepping Motor
Character LCD
SPI
I2C (Wire)
SD Card
SD (File Operations)
Periodic Operation
Clock (RTC)
Mbed Tips
Wi-Fi
This is a sample using Wi-Fi of ESP32 and TCP socket of Mbed OS.
Example
This is a sample that scans the access point and performs HTTP GET. Change SSID/PASS to yours.
#include <Arduino.h>
#include "TCPSocket.h"
#include "ESP32Interface.h"
#define MBED_CONF_APP_WIFI_SSID "Okamylab7"
#define MBED_CONF_APP_WIFI_PASSWORD "oooooooo"
ESP32Interface wifi;
const char *sec2str(nsapi_security_t sec)
{
switch (sec) {
case NSAPI_SECURITY_NONE:
return "None";
case NSAPI_SECURITY_WEP:
return "WEP";
case NSAPI_SECURITY_WPA:
return "WPA";
case NSAPI_SECURITY_WPA2:
return "WPA2";
case NSAPI_SECURITY_WPA_WPA2:
return "WPA/WPA2";
case NSAPI_SECURITY_UNKNOWN:
default:
return "Unknown";
}
}
int scan_demo(WiFiInterface *wifi)
{
WiFiAccessPoint *ap;
int count = 15; /* Limit number of network arbitrary to 15 */
printf("Scan:\r\n");
ap = new WiFiAccessPoint[count];
count = wifi->scan(ap, count);
for (int i = 0; i < count; i++)
{
printf("Network: %s secured: %s BSSID: %hhX:%hhX:%hhX:%hhx:%hhx:%hhx RSSI: %hhd Ch: %hhd\r\n", ap[i].get_ssid(),
sec2str(ap[i].get_security()), ap[i].get_bssid()[0], ap[i].get_bssid()[1], ap[i].get_bssid()[2],
ap[i].get_bssid()[3], ap[i].get_bssid()[4], ap[i].get_bssid()[5], ap[i].get_rssi(), ap[i].get_channel());
}
printf("%d networks available.\r\n", count);
delete[] ap;
return count;
}
void http_demo(NetworkInterface *net)
{
TCPSocket socket;
printf("Sending HTTP request to www.arm.com...\r\n");
// Open a socket on the network interface, and create a TCP connection to www.arm.com
socket.open(net);
socket.connect("www.arm.com", 80);
// Send a simple http request
char sbuffer[] = "GET / HTTP/1.1\r\nHost: www.arm.com\r\n\r\n";
int scount = socket.send(sbuffer, sizeof sbuffer);
printf("sent %d [%.*s]\r\n", scount, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
// Receive a simple http response and print out the response line
char rbuffer[64];
int rcount = socket.recv(rbuffer, sizeof rbuffer);
printf("recv %d [%.*s]\r\n", rcount, strstr(rbuffer, "\r\n")-rbuffer, rbuffer);
// Close the socket to return its memory and bring down the network interface
socket.close();
}
void setup() {
printf("WiFi example\r\n\r\n");
while (scan_demo(&wifi) == 0);
printf("\r\nConnecting...\r\n");
int ret = wifi.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
if (ret != 0) {
printf("\r\nConnection error\r\n");
while(1);
}
printf("Success\r\n\r\n");
printf("MAC: %s\r\n", wifi.get_mac_address());
printf("IP: %s\r\n", wifi.get_ip_address());
printf("Netmask: %s\r\n", wifi.get_netmask());
printf("Gateway: %s\r\n", wifi.get_gateway());
printf("RSSI: %d\r\n\r\n", wifi.get_rssi());
http_demo(&wifi);
wifi.disconnect();
printf("\r\nDone\r\n");
}
void loop() {
}