mirror of
https://github.com/esp8266/Arduino.git
synced 2025-06-06 05:21:22 +03:00
examples: format all .ino files
This formats all the example source files using Arduino style rules.
This commit is contained in:
parent
e226251b27
commit
61cd8d8385
@ -32,10 +32,11 @@ void setup() {
|
|||||||
|
|
||||||
ArduinoOTA.onStart([]() {
|
ArduinoOTA.onStart([]() {
|
||||||
String type;
|
String type;
|
||||||
if (ArduinoOTA.getCommand() == U_FLASH)
|
if (ArduinoOTA.getCommand() == U_FLASH) {
|
||||||
type = "sketch";
|
type = "sketch";
|
||||||
else // U_SPIFFS
|
} else { // U_SPIFFS
|
||||||
type = "filesystem";
|
type = "filesystem";
|
||||||
|
}
|
||||||
|
|
||||||
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
|
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
|
||||||
Serial.println("Start updating " + type);
|
Serial.println("Start updating " + type);
|
||||||
@ -48,11 +49,17 @@ void setup() {
|
|||||||
});
|
});
|
||||||
ArduinoOTA.onError([](ota_error_t error) {
|
ArduinoOTA.onError([](ota_error_t error) {
|
||||||
Serial.printf("Error[%u]: ", error);
|
Serial.printf("Error[%u]: ", error);
|
||||||
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
|
if (error == OTA_AUTH_ERROR) {
|
||||||
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
|
Serial.println("Auth Failed");
|
||||||
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
|
} else if (error == OTA_BEGIN_ERROR) {
|
||||||
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
|
Serial.println("Begin Failed");
|
||||||
else if (error == OTA_END_ERROR) Serial.println("End Failed");
|
} else if (error == OTA_CONNECT_ERROR) {
|
||||||
|
Serial.println("Connect Failed");
|
||||||
|
} else if (error == OTA_RECEIVE_ERROR) {
|
||||||
|
Serial.println("Receive Failed");
|
||||||
|
} else if (error == OTA_END_ERROR) {
|
||||||
|
Serial.println("End Failed");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
ArduinoOTA.begin();
|
ArduinoOTA.begin();
|
||||||
Serial.println("Ready");
|
Serial.println("Ready");
|
||||||
|
@ -12,54 +12,56 @@ int led_pin = 13;
|
|||||||
int dimmer_pin[] = {14, 5, 15};
|
int dimmer_pin[] = {14, 5, 15};
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
|
|
||||||
/* switch on led */
|
/* switch on led */
|
||||||
pinMode(led_pin, OUTPUT);
|
pinMode(led_pin, OUTPUT);
|
||||||
digitalWrite(led_pin, LOW);
|
digitalWrite(led_pin, LOW);
|
||||||
|
|
||||||
Serial.println("Booting");
|
Serial.println("Booting");
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
|
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
|
|
||||||
while (WiFi.waitForConnectResult() != WL_CONNECTED){
|
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
Serial.println("Retrying connection...");
|
Serial.println("Retrying connection...");
|
||||||
}
|
}
|
||||||
/* switch off led */
|
/* switch off led */
|
||||||
digitalWrite(led_pin, HIGH);
|
digitalWrite(led_pin, HIGH);
|
||||||
|
|
||||||
/* configure dimmers, and OTA server events */
|
/* configure dimmers, and OTA server events */
|
||||||
analogWriteRange(1000);
|
analogWriteRange(1000);
|
||||||
analogWrite(led_pin,990);
|
analogWrite(led_pin, 990);
|
||||||
|
|
||||||
for (int i=0; i<N_DIMMERS; i++)
|
for (int i = 0; i < N_DIMMERS; i++) {
|
||||||
{
|
|
||||||
pinMode(dimmer_pin[i], OUTPUT);
|
pinMode(dimmer_pin[i], OUTPUT);
|
||||||
analogWrite(dimmer_pin[i],50);
|
analogWrite(dimmer_pin[i], 50);
|
||||||
}
|
}
|
||||||
|
|
||||||
ArduinoOTA.setHostname(host);
|
ArduinoOTA.setHostname(host);
|
||||||
ArduinoOTA.onStart([]() { // switch off all the PWMs during upgrade
|
ArduinoOTA.onStart([]() { // switch off all the PWMs during upgrade
|
||||||
for(int i=0; i<N_DIMMERS;i++)
|
for (int i = 0; i < N_DIMMERS; i++) {
|
||||||
analogWrite(dimmer_pin[i], 0);
|
analogWrite(dimmer_pin[i], 0);
|
||||||
analogWrite(led_pin,0);
|
}
|
||||||
});
|
analogWrite(led_pin, 0);
|
||||||
|
});
|
||||||
|
|
||||||
ArduinoOTA.onEnd([]() { // do a fancy thing with our board led at end
|
ArduinoOTA.onEnd([]() { // do a fancy thing with our board led at end
|
||||||
for (int i=0;i<30;i++)
|
for (int i = 0; i < 30; i++) {
|
||||||
{
|
analogWrite(led_pin, (i * 100) % 1001);
|
||||||
analogWrite(led_pin,(i*100) % 1001);
|
delay(50);
|
||||||
delay(50);
|
}
|
||||||
}
|
});
|
||||||
});
|
|
||||||
|
|
||||||
ArduinoOTA.onError([](ota_error_t error) { (void)error; ESP.restart(); });
|
ArduinoOTA.onError([](ota_error_t error) {
|
||||||
|
(void)error;
|
||||||
|
ESP.restart();
|
||||||
|
});
|
||||||
|
|
||||||
/* setup the OTA server */
|
/* setup the OTA server */
|
||||||
ArduinoOTA.begin();
|
ArduinoOTA.begin();
|
||||||
Serial.println("Ready");
|
Serial.println("Ready");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -8,9 +8,9 @@ DNSServer dnsServer;
|
|||||||
ESP8266WebServer webServer(80);
|
ESP8266WebServer webServer(80);
|
||||||
|
|
||||||
String responseHTML = ""
|
String responseHTML = ""
|
||||||
"<!DOCTYPE html><html><head><title>CaptivePortal</title></head><body>"
|
"<!DOCTYPE html><html><head><title>CaptivePortal</title></head><body>"
|
||||||
"<h1>Hello World!</h1><p>This is a captive portal example. All requests will "
|
"<h1>Hello World!</h1><p>This is a captive portal example. All requests will "
|
||||||
"be redirected here.</p></body></html>";
|
"be redirected here.</p></body></html>";
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
WiFi.mode(WIFI_AP);
|
WiFi.mode(WIFI_AP);
|
||||||
|
@ -1,21 +1,21 @@
|
|||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <WiFiClient.h>
|
#include <WiFiClient.h>
|
||||||
#include <ESP8266WebServer.h>
|
#include <ESP8266WebServer.h>
|
||||||
#include <DNSServer.h>
|
#include <DNSServer.h>
|
||||||
#include <ESP8266mDNS.h>
|
#include <ESP8266mDNS.h>
|
||||||
#include <EEPROM.h>
|
#include <EEPROM.h>
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* This example serves a "hello world" on a WLAN and a SoftAP at the same time.
|
This example serves a "hello world" on a WLAN and a SoftAP at the same time.
|
||||||
* The SoftAP allow you to configure WLAN parameters at run time. They are not setup in the sketch but saved on EEPROM.
|
The SoftAP allow you to configure WLAN parameters at run time. They are not setup in the sketch but saved on EEPROM.
|
||||||
*
|
|
||||||
* Connect your computer or cell phone to wifi network ESP_ap with password 12345678. A popup may appear and it allow you to go to WLAN config. If it does not then navigate to http://192.168.4.1/wifi and config it there.
|
Connect your computer or cell phone to wifi network ESP_ap with password 12345678. A popup may appear and it allow you to go to WLAN config. If it does not then navigate to http://192.168.4.1/wifi and config it there.
|
||||||
* Then wait for the module to connect to your wifi and take note of the WLAN IP it got. Then you can disconnect from ESP_ap and return to your regular WLAN.
|
Then wait for the module to connect to your wifi and take note of the WLAN IP it got. Then you can disconnect from ESP_ap and return to your regular WLAN.
|
||||||
*
|
|
||||||
* Now the ESP8266 is in your network. You can reach it through http://192.168.x.x/ (the IP you took note of) or maybe at http://esp8266.local too.
|
Now the ESP8266 is in your network. You can reach it through http://192.168.x.x/ (the IP you took note of) or maybe at http://esp8266.local too.
|
||||||
*
|
|
||||||
* This is a captive portal because through the softAP it will redirect any http request to http://192.168.4.1/
|
This is a captive portal because through the softAP it will redirect any http request to http://192.168.4.1/
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/* Set these to your desired softAP credentials. They are not configurable at runtime */
|
/* Set these to your desired softAP credentials. They are not configurable at runtime */
|
||||||
const char *softAP_ssid = "ESP_ap";
|
const char *softAP_ssid = "ESP_ap";
|
||||||
@ -61,7 +61,7 @@ void setup() {
|
|||||||
Serial.print("AP IP address: ");
|
Serial.print("AP IP address: ");
|
||||||
Serial.println(WiFi.softAPIP());
|
Serial.println(WiFi.softAPIP());
|
||||||
|
|
||||||
/* Setup the DNS server redirecting all the domains to the apIP */
|
/* Setup the DNS server redirecting all the domains to the apIP */
|
||||||
dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
|
dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
|
||||||
dnsServer.start(DNS_PORT, "*", apIP);
|
dnsServer.start(DNS_PORT, "*", apIP);
|
||||||
|
|
||||||
@ -71,7 +71,7 @@ void setup() {
|
|||||||
server.on("/wifisave", handleWifiSave);
|
server.on("/wifisave", handleWifiSave);
|
||||||
server.on("/generate_204", handleRoot); //Android captive portal. Maybe not needed. Might be handled by notFound handler.
|
server.on("/generate_204", handleRoot); //Android captive portal. Maybe not needed. Might be handled by notFound handler.
|
||||||
server.on("/fwlink", handleRoot); //Microsoft captive portal. Maybe not needed. Might be handled by notFound handler.
|
server.on("/fwlink", handleRoot); //Microsoft captive portal. Maybe not needed. Might be handled by notFound handler.
|
||||||
server.onNotFound ( handleNotFound );
|
server.onNotFound(handleNotFound);
|
||||||
server.begin(); // Web server start
|
server.begin(); // Web server start
|
||||||
Serial.println("HTTP server started");
|
Serial.println("HTTP server started");
|
||||||
loadCredentials(); // Load WLAN credentials from network
|
loadCredentials(); // Load WLAN credentials from network
|
||||||
@ -81,37 +81,37 @@ void setup() {
|
|||||||
void connectWifi() {
|
void connectWifi() {
|
||||||
Serial.println("Connecting as wifi client...");
|
Serial.println("Connecting as wifi client...");
|
||||||
WiFi.disconnect();
|
WiFi.disconnect();
|
||||||
WiFi.begin ( ssid, password );
|
WiFi.begin(ssid, password);
|
||||||
int connRes = WiFi.waitForConnectResult();
|
int connRes = WiFi.waitForConnectResult();
|
||||||
Serial.print ( "connRes: " );
|
Serial.print("connRes: ");
|
||||||
Serial.println ( connRes );
|
Serial.println(connRes);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
if (connect) {
|
if (connect) {
|
||||||
Serial.println ( "Connect requested" );
|
Serial.println("Connect requested");
|
||||||
connect = false;
|
connect = false;
|
||||||
connectWifi();
|
connectWifi();
|
||||||
lastConnectTry = millis();
|
lastConnectTry = millis();
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
unsigned int s = WiFi.status();
|
unsigned int s = WiFi.status();
|
||||||
if (s == 0 && millis() > (lastConnectTry + 60000) ) {
|
if (s == 0 && millis() > (lastConnectTry + 60000)) {
|
||||||
/* If WLAN disconnected and idle try to connect */
|
/* If WLAN disconnected and idle try to connect */
|
||||||
/* Don't set retry time too low as retry interfere the softAP operation */
|
/* Don't set retry time too low as retry interfere the softAP operation */
|
||||||
connect = true;
|
connect = true;
|
||||||
}
|
}
|
||||||
if (status != s) { // WLAN status change
|
if (status != s) { // WLAN status change
|
||||||
Serial.print ( "Status: " );
|
Serial.print("Status: ");
|
||||||
Serial.println ( s );
|
Serial.println(s);
|
||||||
status = s;
|
status = s;
|
||||||
if (s == WL_CONNECTED) {
|
if (s == WL_CONNECTED) {
|
||||||
/* Just connected to WLAN */
|
/* Just connected to WLAN */
|
||||||
Serial.println ( "" );
|
Serial.println("");
|
||||||
Serial.print ( "Connected to " );
|
Serial.print("Connected to ");
|
||||||
Serial.println ( ssid );
|
Serial.println(ssid);
|
||||||
Serial.print ( "IP address: " );
|
Serial.print("IP address: ");
|
||||||
Serial.println ( WiFi.localIP() );
|
Serial.println(WiFi.localIP());
|
||||||
|
|
||||||
// Setup MDNS responder
|
// Setup MDNS responder
|
||||||
if (!MDNS.begin(myHostname)) {
|
if (!MDNS.begin(myHostname)) {
|
||||||
|
@ -2,9 +2,9 @@
|
|||||||
void loadCredentials() {
|
void loadCredentials() {
|
||||||
EEPROM.begin(512);
|
EEPROM.begin(512);
|
||||||
EEPROM.get(0, ssid);
|
EEPROM.get(0, ssid);
|
||||||
EEPROM.get(0+sizeof(ssid), password);
|
EEPROM.get(0 + sizeof(ssid), password);
|
||||||
char ok[2+1];
|
char ok[2 + 1];
|
||||||
EEPROM.get(0+sizeof(ssid)+sizeof(password), ok);
|
EEPROM.get(0 + sizeof(ssid) + sizeof(password), ok);
|
||||||
EEPROM.end();
|
EEPROM.end();
|
||||||
if (String(ok) != String("OK")) {
|
if (String(ok) != String("OK")) {
|
||||||
ssid[0] = 0;
|
ssid[0] = 0;
|
||||||
@ -12,16 +12,16 @@ void loadCredentials() {
|
|||||||
}
|
}
|
||||||
Serial.println("Recovered credentials:");
|
Serial.println("Recovered credentials:");
|
||||||
Serial.println(ssid);
|
Serial.println(ssid);
|
||||||
Serial.println(strlen(password)>0?"********":"<no password>");
|
Serial.println(strlen(password) > 0 ? "********" : "<no password>");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Store WLAN credentials to EEPROM */
|
/** Store WLAN credentials to EEPROM */
|
||||||
void saveCredentials() {
|
void saveCredentials() {
|
||||||
EEPROM.begin(512);
|
EEPROM.begin(512);
|
||||||
EEPROM.put(0, ssid);
|
EEPROM.put(0, ssid);
|
||||||
EEPROM.put(0+sizeof(ssid), password);
|
EEPROM.put(0 + sizeof(ssid), password);
|
||||||
char ok[2+1] = "OK";
|
char ok[2 + 1] = "OK";
|
||||||
EEPROM.put(0+sizeof(ssid)+sizeof(password), ok);
|
EEPROM.put(0 + sizeof(ssid) + sizeof(password), ok);
|
||||||
EEPROM.commit();
|
EEPROM.commit();
|
||||||
EEPROM.end();
|
EEPROM.end();
|
||||||
}
|
}
|
||||||
|
@ -26,10 +26,10 @@ void handleRoot() {
|
|||||||
|
|
||||||
/** Redirect to captive portal if we got a request for another domain. Return true in that case so the page handler do not try to handle the request again. */
|
/** Redirect to captive portal if we got a request for another domain. Return true in that case so the page handler do not try to handle the request again. */
|
||||||
boolean captivePortal() {
|
boolean captivePortal() {
|
||||||
if (!isIp(server.hostHeader()) && server.hostHeader() != (String(myHostname)+".local")) {
|
if (!isIp(server.hostHeader()) && server.hostHeader() != (String(myHostname) + ".local")) {
|
||||||
Serial.print("Request redirected to captive portal");
|
Serial.print("Request redirected to captive portal");
|
||||||
server.sendHeader("Location", String("http://") + toStringIp(server.client().localIP()), true);
|
server.sendHeader("Location", String("http://") + toStringIp(server.client().localIP()), true);
|
||||||
server.send ( 302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves.
|
server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves.
|
||||||
server.client().stop(); // Stop is needed because we sent no content length
|
server.client().stop(); // Stop is needed because we sent no content length
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -75,7 +75,7 @@ void handleWifi() {
|
|||||||
Serial.println("scan done");
|
Serial.println("scan done");
|
||||||
if (n > 0) {
|
if (n > 0) {
|
||||||
for (int i = 0; i < n; i++) {
|
for (int i = 0; i < n; i++) {
|
||||||
server.sendContent(String() + "\r\n<tr><td>SSID " + WiFi.SSID(i) + String((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":" *") + " (" + WiFi.RSSI(i) + ")</td></tr>");
|
server.sendContent(String() + "\r\n<tr><td>SSID " + WiFi.SSID(i) + String((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : " *") + " (" + WiFi.RSSI(i) + ")</td></tr>");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
server.sendContent(String() + "<tr><td>No WLAN found</td></tr>");
|
server.sendContent(String() + "<tr><td>No WLAN found</td></tr>");
|
||||||
@ -101,7 +101,7 @@ void handleWifiSave() {
|
|||||||
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
|
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||||
server.sendHeader("Pragma", "no-cache");
|
server.sendHeader("Pragma", "no-cache");
|
||||||
server.sendHeader("Expires", "-1");
|
server.sendHeader("Expires", "-1");
|
||||||
server.send ( 302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves.
|
server.send(302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves.
|
||||||
server.client().stop(); // Stop is needed because we sent no content length
|
server.client().stop(); // Stop is needed because we sent no content length
|
||||||
saveCredentials();
|
saveCredentials();
|
||||||
connect = strlen(ssid) > 0; // Request WLAN connect with new credentials if there is a SSID
|
connect = strlen(ssid) > 0; // Request WLAN connect with new credentials if there is a SSID
|
||||||
@ -115,17 +115,17 @@ void handleNotFound() {
|
|||||||
message += "URI: ";
|
message += "URI: ";
|
||||||
message += server.uri();
|
message += server.uri();
|
||||||
message += "\nMethod: ";
|
message += "\nMethod: ";
|
||||||
message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
|
message += (server.method() == HTTP_GET) ? "GET" : "POST";
|
||||||
message += "\nArguments: ";
|
message += "\nArguments: ";
|
||||||
message += server.args();
|
message += server.args();
|
||||||
message += "\n";
|
message += "\n";
|
||||||
|
|
||||||
for ( uint8_t i = 0; i < server.args(); i++ ) {
|
for (uint8_t i = 0; i < server.args(); i++) {
|
||||||
message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
|
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
|
||||||
}
|
}
|
||||||
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
|
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||||
server.sendHeader("Pragma", "no-cache");
|
server.sendHeader("Pragma", "no-cache");
|
||||||
server.sendHeader("Expires", "-1");
|
server.sendHeader("Expires", "-1");
|
||||||
server.send ( 404, "text/plain", message );
|
server.send(404, "text/plain", message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,19 +1,19 @@
|
|||||||
/*
|
/*
|
||||||
* EEPROM Clear
|
EEPROM Clear
|
||||||
*
|
|
||||||
* Sets all of the bytes of the EEPROM to 0.
|
|
||||||
* This example code is in the public domain.
|
|
||||||
|
|
||||||
*/
|
Sets all of the bytes of the EEPROM to 0.
|
||||||
|
This example code is in the public domain.
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
#include <EEPROM.h>
|
#include <EEPROM.h>
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
EEPROM.begin(512);
|
EEPROM.begin(512);
|
||||||
// write a 0 to all 512 bytes of the EEPROM
|
// write a 0 to all 512 bytes of the EEPROM
|
||||||
for (int i = 0; i < 512; i++)
|
for (int i = 0; i < 512; i++) {
|
||||||
EEPROM.write(i, 0);
|
EEPROM.write(i, 0);
|
||||||
|
}
|
||||||
|
|
||||||
// turn the LED on when we're done
|
// turn the LED on when we're done
|
||||||
pinMode(13, OUTPUT);
|
pinMode(13, OUTPUT);
|
||||||
@ -21,6 +21,5 @@ void setup()
|
|||||||
EEPROM.end();
|
EEPROM.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
/*
|
/*
|
||||||
* EEPROM Read
|
EEPROM Read
|
||||||
*
|
|
||||||
* Reads the value of each byte of the EEPROM and prints it
|
Reads the value of each byte of the EEPROM and prints it
|
||||||
* to the computer.
|
to the computer.
|
||||||
* This example code is in the public domain.
|
This example code is in the public domain.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <EEPROM.h>
|
#include <EEPROM.h>
|
||||||
|
|
||||||
@ -12,8 +12,7 @@
|
|||||||
int address = 0;
|
int address = 0;
|
||||||
byte value;
|
byte value;
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
// initialize serial and wait for port to open:
|
// initialize serial and wait for port to open:
|
||||||
Serial.begin(9600);
|
Serial.begin(9600);
|
||||||
while (!Serial) {
|
while (!Serial) {
|
||||||
@ -22,8 +21,7 @@ void setup()
|
|||||||
EEPROM.begin(512);
|
EEPROM.begin(512);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
// read a byte from the current address of the EEPROM
|
// read a byte from the current address of the EEPROM
|
||||||
value = EEPROM.read(address);
|
value = EEPROM.read(address);
|
||||||
|
|
||||||
@ -37,8 +35,9 @@ void loop()
|
|||||||
|
|
||||||
// there are only 512 bytes of EEPROM, from 0 to 511, so if we're
|
// there are only 512 bytes of EEPROM, from 0 to 511, so if we're
|
||||||
// on address 512, wrap around to address 0
|
// on address 512, wrap around to address 0
|
||||||
if (address == 512)
|
if (address == 512) {
|
||||||
address = 0;
|
address = 0;
|
||||||
|
}
|
||||||
|
|
||||||
delay(500);
|
delay(500);
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
/*
|
/*
|
||||||
* EEPROM Write
|
EEPROM Write
|
||||||
*
|
|
||||||
* Stores values read from analog input 0 into the EEPROM.
|
Stores values read from analog input 0 into the EEPROM.
|
||||||
* These values will stay in the EEPROM when the board is
|
These values will stay in the EEPROM when the board is
|
||||||
* turned off and may be retrieved later by another sketch.
|
turned off and may be retrieved later by another sketch.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <EEPROM.h>
|
#include <EEPROM.h>
|
||||||
|
|
||||||
@ -12,13 +12,11 @@
|
|||||||
// we're going to write to next)
|
// we're going to write to next)
|
||||||
int addr = 0;
|
int addr = 0;
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
EEPROM.begin(512);
|
EEPROM.begin(512);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
// need to divide by 4 because analog inputs range from
|
// need to divide by 4 because analog inputs range from
|
||||||
// 0 to 1023 and each byte of the EEPROM can only hold a
|
// 0 to 1023 and each byte of the EEPROM can only hold a
|
||||||
// value from 0 to 255.
|
// value from 0 to 255.
|
||||||
@ -33,8 +31,7 @@ void loop()
|
|||||||
// the EEPROM, so go back to 0 when we hit 512.
|
// the EEPROM, so go back to 0 when we hit 512.
|
||||||
// save all changes to the flash.
|
// save all changes to the flash.
|
||||||
addr = addr + 1;
|
addr = addr + 1;
|
||||||
if (addr == 512)
|
if (addr == 512) {
|
||||||
{
|
|
||||||
addr = 0;
|
addr = 0;
|
||||||
EEPROM.commit();
|
EEPROM.commit();
|
||||||
}
|
}
|
||||||
|
@ -12,57 +12,57 @@ const uint8_t reset_pin = 5;
|
|||||||
ESP8266AVRISP avrprog(port, reset_pin);
|
ESP8266AVRISP avrprog(port, reset_pin);
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
Serial.println("");
|
Serial.println("");
|
||||||
Serial.println("Arduino AVR-ISP over TCP");
|
Serial.println("Arduino AVR-ISP over TCP");
|
||||||
avrprog.setReset(false); // let the AVR run
|
avrprog.setReset(false); // let the AVR run
|
||||||
|
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(ssid, pass);
|
WiFi.begin(ssid, pass);
|
||||||
while (WiFi.waitForConnectResult() != WL_CONNECTED);
|
while (WiFi.waitForConnectResult() != WL_CONNECTED);
|
||||||
|
|
||||||
MDNS.begin(host);
|
MDNS.begin(host);
|
||||||
MDNS.addService("avrisp", "tcp", port);
|
MDNS.addService("avrisp", "tcp", port);
|
||||||
|
|
||||||
IPAddress local_ip = WiFi.localIP();
|
IPAddress local_ip = WiFi.localIP();
|
||||||
Serial.print("IP address: ");
|
Serial.print("IP address: ");
|
||||||
Serial.println(local_ip);
|
Serial.println(local_ip);
|
||||||
Serial.println("Use your avrdude:");
|
Serial.println("Use your avrdude:");
|
||||||
Serial.print("avrdude -c arduino -p <device> -P net:");
|
Serial.print("avrdude -c arduino -p <device> -P net:");
|
||||||
Serial.print(local_ip);
|
Serial.print(local_ip);
|
||||||
Serial.print(":");
|
Serial.print(":");
|
||||||
Serial.print(port);
|
Serial.print(port);
|
||||||
Serial.println(" -t # or -U ...");
|
Serial.println(" -t # or -U ...");
|
||||||
|
|
||||||
// listen for avrdudes
|
// listen for avrdudes
|
||||||
avrprog.begin();
|
avrprog.begin();
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
static AVRISPState_t last_state = AVRISP_STATE_IDLE;
|
static AVRISPState_t last_state = AVRISP_STATE_IDLE;
|
||||||
AVRISPState_t new_state = avrprog.update();
|
AVRISPState_t new_state = avrprog.update();
|
||||||
if (last_state != new_state) {
|
if (last_state != new_state) {
|
||||||
switch (new_state) {
|
switch (new_state) {
|
||||||
case AVRISP_STATE_IDLE: {
|
case AVRISP_STATE_IDLE: {
|
||||||
Serial.printf("[AVRISP] now idle\r\n");
|
Serial.printf("[AVRISP] now idle\r\n");
|
||||||
// Use the SPI bus for other purposes
|
// Use the SPI bus for other purposes
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case AVRISP_STATE_PENDING: {
|
case AVRISP_STATE_PENDING: {
|
||||||
Serial.printf("[AVRISP] connection pending\r\n");
|
Serial.printf("[AVRISP] connection pending\r\n");
|
||||||
// Clean up your other purposes and prepare for programming mode
|
// Clean up your other purposes and prepare for programming mode
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case AVRISP_STATE_ACTIVE: {
|
case AVRISP_STATE_ACTIVE: {
|
||||||
Serial.printf("[AVRISP] programming mode\r\n");
|
Serial.printf("[AVRISP] programming mode\r\n");
|
||||||
// Stand by for completion
|
// Stand by for completion
|
||||||
break;
|
break;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
last_state = new_state;
|
|
||||||
}
|
|
||||||
// Serve the client
|
|
||||||
if (last_state != AVRISP_STATE_IDLE) {
|
|
||||||
avrprog.serve();
|
|
||||||
}
|
}
|
||||||
|
last_state = new_state;
|
||||||
|
}
|
||||||
|
// Serve the client
|
||||||
|
if (last_state != AVRISP_STATE_IDLE) {
|
||||||
|
avrprog.serve();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
/**
|
/**
|
||||||
* Authorization.ino
|
Authorization.ino
|
||||||
*
|
|
||||||
* Created on: 09.12.2015
|
Created on: 09.12.2015
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
|
|
||||||
@ -18,68 +18,68 @@ ESP8266WiFiMulti WiFiMulti;
|
|||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
|
|
||||||
USE_SERIAL.begin(115200);
|
USE_SERIAL.begin(115200);
|
||||||
// USE_SERIAL.setDebugOutput(true);
|
// USE_SERIAL.setDebugOutput(true);
|
||||||
|
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
|
|
||||||
for(uint8_t t = 4; t > 0; t--) {
|
for (uint8_t t = 4; t > 0; t--) {
|
||||||
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
||||||
USE_SERIAL.flush();
|
USE_SERIAL.flush();
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFiMulti.addAP("SSID", "PASSWORD");
|
WiFiMulti.addAP("SSID", "PASSWORD");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
// wait for WiFi connection
|
// wait for WiFi connection
|
||||||
if((WiFiMulti.run() == WL_CONNECTED)) {
|
if ((WiFiMulti.run() == WL_CONNECTED)) {
|
||||||
|
|
||||||
HTTPClient http;
|
HTTPClient http;
|
||||||
|
|
||||||
USE_SERIAL.print("[HTTP] begin...\n");
|
USE_SERIAL.print("[HTTP] begin...\n");
|
||||||
// configure traged server and url
|
// configure traged server and url
|
||||||
|
|
||||||
|
|
||||||
http.begin("http://user:password@192.168.1.12/test.html");
|
http.begin("http://user:password@192.168.1.12/test.html");
|
||||||
|
|
||||||
/*
|
/*
|
||||||
// or
|
// or
|
||||||
http.begin("http://192.168.1.12/test.html");
|
http.begin("http://192.168.1.12/test.html");
|
||||||
http.setAuthorization("user", "password");
|
http.setAuthorization("user", "password");
|
||||||
|
|
||||||
// or
|
// or
|
||||||
http.begin("http://192.168.1.12/test.html");
|
http.begin("http://192.168.1.12/test.html");
|
||||||
http.setAuthorization("dXNlcjpwYXN3b3Jk");
|
http.setAuthorization("dXNlcjpwYXN3b3Jk");
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
USE_SERIAL.print("[HTTP] GET...\n");
|
USE_SERIAL.print("[HTTP] GET...\n");
|
||||||
// start connection and send HTTP header
|
// start connection and send HTTP header
|
||||||
int httpCode = http.GET();
|
int httpCode = http.GET();
|
||||||
|
|
||||||
// httpCode will be negative on error
|
// httpCode will be negative on error
|
||||||
if(httpCode > 0) {
|
if (httpCode > 0) {
|
||||||
// HTTP header has been send and Server response header has been handled
|
// HTTP header has been send and Server response header has been handled
|
||||||
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
|
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
|
||||||
|
|
||||||
// file found at server
|
// file found at server
|
||||||
if(httpCode == HTTP_CODE_OK) {
|
if (httpCode == HTTP_CODE_OK) {
|
||||||
String payload = http.getString();
|
String payload = http.getString();
|
||||||
USE_SERIAL.println(payload);
|
USE_SERIAL.println(payload);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
|
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
|
||||||
}
|
|
||||||
|
|
||||||
http.end();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
delay(10000);
|
http.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
delay(10000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
/**
|
/**
|
||||||
* BasicHTTPClient.ino
|
BasicHTTPClient.ino
|
||||||
*
|
|
||||||
* Created on: 24.05.2015
|
Created on: 24.05.2015
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
|
|
||||||
@ -18,56 +18,56 @@ ESP8266WiFiMulti WiFiMulti;
|
|||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
|
|
||||||
USE_SERIAL.begin(115200);
|
USE_SERIAL.begin(115200);
|
||||||
// USE_SERIAL.setDebugOutput(true);
|
// USE_SERIAL.setDebugOutput(true);
|
||||||
|
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
|
|
||||||
for(uint8_t t = 4; t > 0; t--) {
|
for (uint8_t t = 4; t > 0; t--) {
|
||||||
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
||||||
USE_SERIAL.flush();
|
USE_SERIAL.flush();
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFiMulti.addAP("SSID", "PASSWORD");
|
WiFiMulti.addAP("SSID", "PASSWORD");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
// wait for WiFi connection
|
// wait for WiFi connection
|
||||||
if((WiFiMulti.run() == WL_CONNECTED)) {
|
if ((WiFiMulti.run() == WL_CONNECTED)) {
|
||||||
|
|
||||||
HTTPClient http;
|
HTTPClient http;
|
||||||
|
|
||||||
USE_SERIAL.print("[HTTP] begin...\n");
|
USE_SERIAL.print("[HTTP] begin...\n");
|
||||||
// configure traged server and url
|
// configure traged server and url
|
||||||
//http.begin("https://192.168.1.12/test.html", "7a 9c f4 db 40 d3 62 5a 6e 21 bc 5c cc 66 c8 3e a1 45 59 38"); //HTTPS
|
//http.begin("https://192.168.1.12/test.html", "7a 9c f4 db 40 d3 62 5a 6e 21 bc 5c cc 66 c8 3e a1 45 59 38"); //HTTPS
|
||||||
http.begin("http://192.168.1.12/test.html"); //HTTP
|
http.begin("http://192.168.1.12/test.html"); //HTTP
|
||||||
|
|
||||||
USE_SERIAL.print("[HTTP] GET...\n");
|
USE_SERIAL.print("[HTTP] GET...\n");
|
||||||
// start connection and send HTTP header
|
// start connection and send HTTP header
|
||||||
int httpCode = http.GET();
|
int httpCode = http.GET();
|
||||||
|
|
||||||
// httpCode will be negative on error
|
// httpCode will be negative on error
|
||||||
if(httpCode > 0) {
|
if (httpCode > 0) {
|
||||||
// HTTP header has been send and Server response header has been handled
|
// HTTP header has been send and Server response header has been handled
|
||||||
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
|
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
|
||||||
|
|
||||||
// file found at server
|
// file found at server
|
||||||
if(httpCode == HTTP_CODE_OK) {
|
if (httpCode == HTTP_CODE_OK) {
|
||||||
String payload = http.getString();
|
String payload = http.getString();
|
||||||
USE_SERIAL.println(payload);
|
USE_SERIAL.println(payload);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
|
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
|
||||||
}
|
|
||||||
|
|
||||||
http.end();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
delay(10000);
|
http.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
delay(10000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
This example is released into public domain,
|
This example is released into public domain,
|
||||||
or, at your option, CC0 licensed.
|
or, at your option, CC0 licensed.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
|
|
||||||
@ -20,24 +20,26 @@ const char *password = "admin";
|
|||||||
const char *server = "http://httpbin.org";
|
const char *server = "http://httpbin.org";
|
||||||
const char *uri = "/digest-auth/auth/admin/admin/MD5";
|
const char *uri = "/digest-auth/auth/admin/admin/MD5";
|
||||||
|
|
||||||
String exractParam(String& authReq, const String& param, const char delimit){
|
String exractParam(String& authReq, const String& param, const char delimit) {
|
||||||
int _begin = authReq.indexOf(param);
|
int _begin = authReq.indexOf(param);
|
||||||
if (_begin==-1) return "";
|
if (_begin == -1) {
|
||||||
return authReq.substring(_begin+param.length(),authReq.indexOf(delimit,_begin+param.length()));
|
return "";
|
||||||
|
}
|
||||||
|
return authReq.substring(_begin + param.length(), authReq.indexOf(delimit, _begin + param.length()));
|
||||||
}
|
}
|
||||||
|
|
||||||
String getCNonce(const int len) {
|
String getCNonce(const int len) {
|
||||||
static const char alphanum[] =
|
static const char alphanum[] =
|
||||||
"0123456789"
|
"0123456789"
|
||||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||||
"abcdefghijklmnopqrstuvwxyz";
|
"abcdefghijklmnopqrstuvwxyz";
|
||||||
String s = "";
|
String s = "";
|
||||||
|
|
||||||
for (int i = 0; i < len; ++i) {
|
for (int i = 0; i < len; ++i) {
|
||||||
s += alphanum[rand() % (sizeof(alphanum) - 1)];
|
s += alphanum[rand() % (sizeof(alphanum) - 1)];
|
||||||
}
|
}
|
||||||
|
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
String getDigestAuth(String& authReq, const String& username, const String& password, const String& uri, unsigned int counter) {
|
String getDigestAuth(String& authReq, const String& username, const String& password, const String& uri, unsigned int counter) {
|
||||||
@ -67,7 +69,7 @@ String getDigestAuth(String& authReq, const String& username, const String& pass
|
|||||||
String response = md5.toString();
|
String response = md5.toString();
|
||||||
|
|
||||||
String authorization = "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce +
|
String authorization = "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce +
|
||||||
"\", uri=\"" + uri + "\", algorithm=\"MD5\", qop=auth, nc=" + String(nc) + ", cnonce=\"" + cNonce + "\", response=\"" + response + "\"";
|
"\", uri=\"" + uri + "\", algorithm=\"MD5\", qop=auth, nc=" + String(nc) + ", cnonce=\"" + cNonce + "\", response=\"" + response + "\"";
|
||||||
Serial.println(authorization);
|
Serial.println(authorization);
|
||||||
|
|
||||||
return authorization;
|
return authorization;
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
/**
|
/**
|
||||||
* reuseConnection.ino
|
reuseConnection.ino
|
||||||
*
|
|
||||||
* Created on: 22.11.2015
|
Created on: 22.11.2015
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
@ -21,49 +21,49 @@ HTTPClient http;
|
|||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
|
|
||||||
USE_SERIAL.begin(115200);
|
USE_SERIAL.begin(115200);
|
||||||
// USE_SERIAL.setDebugOutput(true);
|
// USE_SERIAL.setDebugOutput(true);
|
||||||
|
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
|
|
||||||
for(uint8_t t = 4; t > 0; t--) {
|
for (uint8_t t = 4; t > 0; t--) {
|
||||||
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
||||||
USE_SERIAL.flush();
|
USE_SERIAL.flush();
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFiMulti.addAP("SSID", "PASSWORD");
|
WiFiMulti.addAP("SSID", "PASSWORD");
|
||||||
|
|
||||||
// allow reuse (if server supports it)
|
// allow reuse (if server supports it)
|
||||||
http.setReuse(true);
|
http.setReuse(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
// wait for WiFi connection
|
// wait for WiFi connection
|
||||||
if((WiFiMulti.run() == WL_CONNECTED)) {
|
if ((WiFiMulti.run() == WL_CONNECTED)) {
|
||||||
|
|
||||||
http.begin("http://192.168.1.12/test.html");
|
http.begin("http://192.168.1.12/test.html");
|
||||||
//http.begin("192.168.1.12", 80, "/test.html");
|
//http.begin("192.168.1.12", 80, "/test.html");
|
||||||
|
|
||||||
int httpCode = http.GET();
|
int httpCode = http.GET();
|
||||||
if(httpCode > 0) {
|
if (httpCode > 0) {
|
||||||
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
|
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
|
||||||
|
|
||||||
// file found at server
|
// file found at server
|
||||||
if(httpCode == HTTP_CODE_OK) {
|
if (httpCode == HTTP_CODE_OK) {
|
||||||
http.writeToStream(&USE_SERIAL);
|
http.writeToStream(&USE_SERIAL);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
|
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
|
||||||
}
|
|
||||||
|
|
||||||
http.end();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
delay(1000);
|
http.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
delay(1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
/**
|
/**
|
||||||
* StreamHTTPClient.ino
|
StreamHTTPClient.ino
|
||||||
*
|
|
||||||
* Created on: 24.05.2015
|
Created on: 24.05.2015
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
|
|
||||||
@ -18,85 +18,85 @@ ESP8266WiFiMulti WiFiMulti;
|
|||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
|
|
||||||
USE_SERIAL.begin(115200);
|
USE_SERIAL.begin(115200);
|
||||||
// USE_SERIAL.setDebugOutput(true);
|
// USE_SERIAL.setDebugOutput(true);
|
||||||
|
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
|
|
||||||
for(uint8_t t = 4; t > 0; t--) {
|
for (uint8_t t = 4; t > 0; t--) {
|
||||||
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
||||||
USE_SERIAL.flush();
|
USE_SERIAL.flush();
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFiMulti.addAP("SSID", "PASSWORD");
|
WiFiMulti.addAP("SSID", "PASSWORD");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
// wait for WiFi connection
|
// wait for WiFi connection
|
||||||
if((WiFiMulti.run() == WL_CONNECTED)) {
|
if ((WiFiMulti.run() == WL_CONNECTED)) {
|
||||||
|
|
||||||
HTTPClient http;
|
HTTPClient http;
|
||||||
|
|
||||||
USE_SERIAL.print("[HTTP] begin...\n");
|
USE_SERIAL.print("[HTTP] begin...\n");
|
||||||
|
|
||||||
// configure server and url
|
// configure server and url
|
||||||
http.begin("http://192.168.1.12/test.html");
|
http.begin("http://192.168.1.12/test.html");
|
||||||
//http.begin("192.168.1.12", 80, "/test.html");
|
//http.begin("192.168.1.12", 80, "/test.html");
|
||||||
|
|
||||||
USE_SERIAL.print("[HTTP] GET...\n");
|
USE_SERIAL.print("[HTTP] GET...\n");
|
||||||
// start connection and send HTTP header
|
// start connection and send HTTP header
|
||||||
int httpCode = http.GET();
|
int httpCode = http.GET();
|
||||||
if(httpCode > 0) {
|
if (httpCode > 0) {
|
||||||
// HTTP header has been send and Server response header has been handled
|
// HTTP header has been send and Server response header has been handled
|
||||||
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
|
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
|
||||||
|
|
||||||
// file found at server
|
// file found at server
|
||||||
if(httpCode == HTTP_CODE_OK) {
|
if (httpCode == HTTP_CODE_OK) {
|
||||||
|
|
||||||
// get lenght of document (is -1 when Server sends no Content-Length header)
|
// get lenght of document (is -1 when Server sends no Content-Length header)
|
||||||
int len = http.getSize();
|
int len = http.getSize();
|
||||||
|
|
||||||
// create buffer for read
|
// create buffer for read
|
||||||
uint8_t buff[128] = { 0 };
|
uint8_t buff[128] = { 0 };
|
||||||
|
|
||||||
// get tcp stream
|
// get tcp stream
|
||||||
WiFiClient * stream = http.getStreamPtr();
|
WiFiClient * stream = http.getStreamPtr();
|
||||||
|
|
||||||
// read all data from server
|
// read all data from server
|
||||||
while(http.connected() && (len > 0 || len == -1)) {
|
while (http.connected() && (len > 0 || len == -1)) {
|
||||||
// get available data size
|
// get available data size
|
||||||
size_t size = stream->available();
|
size_t size = stream->available();
|
||||||
|
|
||||||
if(size) {
|
if (size) {
|
||||||
// read up to 128 byte
|
// read up to 128 byte
|
||||||
int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));
|
int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));
|
||||||
|
|
||||||
// write it to Serial
|
// write it to Serial
|
||||||
USE_SERIAL.write(buff, c);
|
USE_SERIAL.write(buff, c);
|
||||||
|
|
||||||
if(len > 0) {
|
|
||||||
len -= c;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
delay(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
USE_SERIAL.println();
|
|
||||||
USE_SERIAL.print("[HTTP] connection closed or file end.\n");
|
|
||||||
|
|
||||||
|
if (len > 0) {
|
||||||
|
len -= c;
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
|
delay(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
http.end();
|
USE_SERIAL.println();
|
||||||
|
USE_SERIAL.print("[HTTP] connection closed or file end.\n");
|
||||||
|
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
delay(10000);
|
http.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
delay(10000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -58,7 +58,7 @@ const char* password = "........";
|
|||||||
ESP8266WebServerSecure httpServer(443);
|
ESP8266WebServerSecure httpServer(443);
|
||||||
ESP8266HTTPUpdateServer httpUpdater;
|
ESP8266HTTPUpdateServer httpUpdater;
|
||||||
|
|
||||||
// The certificate is stored in PMEM
|
// The certificate is stored in PMEM
|
||||||
static const uint8_t x509[] PROGMEM = {
|
static const uint8_t x509[] PROGMEM = {
|
||||||
0x30, 0x82, 0x01, 0xc9, 0x30, 0x82, 0x01, 0x32, 0x02, 0x09, 0x00, 0xe6,
|
0x30, 0x82, 0x01, 0xc9, 0x30, 0x82, 0x01, 0x32, 0x02, 0x09, 0x00, 0xe6,
|
||||||
0x60, 0x8d, 0xa3, 0x47, 0x8f, 0x57, 0x7a, 0x30, 0x0d, 0x06, 0x09, 0x2a,
|
0x60, 0x8d, 0xa3, 0x47, 0x8f, 0x57, 0x7a, 0x30, 0x0d, 0x06, 0x09, 0x2a,
|
||||||
@ -156,8 +156,7 @@ static const uint8_t rsakey[] PROGMEM = {
|
|||||||
0xe1, 0x40, 0x2b, 0xe3, 0xbd, 0x98, 0x44, 0xad
|
0xe1, 0x40, 0x2b, 0xe3, 0xbd, 0x98, 0x44, 0xad
|
||||||
};
|
};
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
|
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
Serial.println();
|
Serial.println();
|
||||||
@ -165,7 +164,7 @@ void setup()
|
|||||||
WiFi.mode(WIFI_AP_STA);
|
WiFi.mode(WIFI_AP_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
|
|
||||||
while(WiFi.waitForConnectResult() != WL_CONNECTED){
|
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
Serial.println("WiFi failed, retrying.");
|
Serial.println("WiFi failed, retrying.");
|
||||||
}
|
}
|
||||||
@ -182,7 +181,6 @@ void setup()
|
|||||||
"'%s'\n", host, update_path, update_username, update_password);
|
"'%s'\n", host, update_path, update_username, update_password);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
httpServer.handleClient();
|
httpServer.handleClient();
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,7 @@ const char* password = "........";
|
|||||||
ESP8266WebServer httpServer(80);
|
ESP8266WebServer httpServer(80);
|
||||||
ESP8266HTTPUpdateServer httpUpdater;
|
ESP8266HTTPUpdateServer httpUpdater;
|
||||||
|
|
||||||
void setup(void){
|
void setup(void) {
|
||||||
|
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
Serial.println();
|
Serial.println();
|
||||||
@ -26,7 +26,7 @@ void setup(void){
|
|||||||
WiFi.mode(WIFI_AP_STA);
|
WiFi.mode(WIFI_AP_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
|
|
||||||
while(WiFi.waitForConnectResult() != WL_CONNECTED){
|
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
Serial.println("WiFi failed, retrying.");
|
Serial.println("WiFi failed, retrying.");
|
||||||
}
|
}
|
||||||
@ -40,6 +40,6 @@ void setup(void){
|
|||||||
Serial.printf("HTTPUpdateServer ready! Open http://%s.local%s in your browser and login with username '%s' and password '%s'\n", host, update_path, update_username, update_password);
|
Serial.printf("HTTPUpdateServer ready! Open http://%s.local%s in your browser and login with username '%s' and password '%s'\n", host, update_path, update_username, update_password);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop(void){
|
void loop(void) {
|
||||||
httpServer.handleClient();
|
httpServer.handleClient();
|
||||||
}
|
}
|
||||||
|
@ -15,7 +15,7 @@ const char* password = "........";
|
|||||||
ESP8266WebServer httpServer(80);
|
ESP8266WebServer httpServer(80);
|
||||||
ESP8266HTTPUpdateServer httpUpdater;
|
ESP8266HTTPUpdateServer httpUpdater;
|
||||||
|
|
||||||
void setup(void){
|
void setup(void) {
|
||||||
|
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
Serial.println();
|
Serial.println();
|
||||||
@ -23,7 +23,7 @@ void setup(void){
|
|||||||
WiFi.mode(WIFI_AP_STA);
|
WiFi.mode(WIFI_AP_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
|
|
||||||
while(WiFi.waitForConnectResult() != WL_CONNECTED){
|
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
Serial.println("WiFi failed, retrying.");
|
Serial.println("WiFi failed, retrying.");
|
||||||
}
|
}
|
||||||
@ -37,6 +37,6 @@ void setup(void){
|
|||||||
Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host);
|
Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop(void){
|
void loop(void) {
|
||||||
httpServer.handleClient();
|
httpServer.handleClient();
|
||||||
}
|
}
|
||||||
|
@ -1,59 +1,59 @@
|
|||||||
/*
|
/*
|
||||||
* ESP8266 LLMNR responder sample
|
ESP8266 LLMNR responder sample
|
||||||
* Copyright (C) 2017 Stephen Warren <swarren@wwwdotorg.org>
|
Copyright (C) 2017 Stephen Warren <swarren@wwwdotorg.org>
|
||||||
*
|
|
||||||
* Based on:
|
Based on:
|
||||||
* ESP8266 Multicast DNS (port of CC3000 Multicast DNS library)
|
ESP8266 Multicast DNS (port of CC3000 Multicast DNS library)
|
||||||
* Version 1.1
|
Version 1.1
|
||||||
* Copyright (c) 2013 Tony DiCola (tony@tonydicola.com)
|
Copyright (c) 2013 Tony DiCola (tony@tonydicola.com)
|
||||||
* ESP8266 port (c) 2015 Ivan Grokhotkov (ivan@esp8266.com)
|
ESP8266 port (c) 2015 Ivan Grokhotkov (ivan@esp8266.com)
|
||||||
* MDNS-SD Suport 2015 Hristo Gochkov
|
MDNS-SD Suport 2015 Hristo Gochkov
|
||||||
* Extended MDNS-SD support 2016 Lars Englund (lars.englund@gmail.com)
|
Extended MDNS-SD support 2016 Lars Englund (lars.englund@gmail.com)
|
||||||
*
|
|
||||||
* License (MIT license):
|
License (MIT license):
|
||||||
*
|
|
||||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
* of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
* in the Software without restriction, including without limitation the rights
|
in the Software without restriction, including without limitation the rights
|
||||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
* copies of the Software, and to permit persons to whom the Software is
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
* furnished to do so, subject to the following conditions:
|
furnished to do so, subject to the following conditions:
|
||||||
*
|
|
||||||
* The above copyright notice and this permission notice shall be included in
|
The above copyright notice and this permission notice shall be included in
|
||||||
* all copies or substantial portions of the Software.
|
all copies or substantial portions of the Software.
|
||||||
*
|
|
||||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
* THE SOFTWARE.
|
THE SOFTWARE.
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
/*
|
/*
|
||||||
* This is an example of an HTTP server that is accessible via http://esp8266/
|
This is an example of an HTTP server that is accessible via http://esp8266/
|
||||||
* (or perhaps http://esp8266.local/) thanks to the LLMNR responder.
|
(or perhaps http://esp8266.local/) thanks to the LLMNR responder.
|
||||||
*
|
|
||||||
* Instructions:
|
Instructions:
|
||||||
* - Update WiFi SSID and password as necessary.
|
- Update WiFi SSID and password as necessary.
|
||||||
* - Flash the sketch to the ESP8266 board.
|
- Flash the sketch to the ESP8266 board.
|
||||||
* - Windows:
|
- Windows:
|
||||||
* - No additional software is necessary.
|
- No additional software is necessary.
|
||||||
* - Point your browser to http://esp8266/, you should see a response. In most
|
- Point your browser to http://esp8266/, you should see a response. In most
|
||||||
* cases, it is important that you manually type the "http://" to force the
|
cases, it is important that you manually type the "http://" to force the
|
||||||
* browser to search for a hostname to connect to, rather than perform a web
|
browser to search for a hostname to connect to, rather than perform a web
|
||||||
* search.
|
search.
|
||||||
* - Alternatively, run the following command from the command prompt:
|
- Alternatively, run the following command from the command prompt:
|
||||||
* ping esp8266
|
ping esp8266
|
||||||
* - Linux:
|
- Linux:
|
||||||
* - To validate LLMNR, install the systemd-resolve utility.
|
- To validate LLMNR, install the systemd-resolve utility.
|
||||||
* - Execute the following command:
|
- Execute the following command:
|
||||||
* systemd-resolve -4 -p llmnr esp8266
|
systemd-resolve -4 -p llmnr esp8266
|
||||||
* - It may be possible to configure your system to use LLMNR for all name
|
- It may be possible to configure your system to use LLMNR for all name
|
||||||
* lookups. However, that is beyond the scope of this description.
|
lookups. However, that is beyond the scope of this description.
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <ESP8266LLMNR.h>
|
#include <ESP8266LLMNR.h>
|
||||||
|
@ -8,43 +8,40 @@ const char* password = "..............";
|
|||||||
ESP8266WebServer wwwserver(80);
|
ESP8266WebServer wwwserver(80);
|
||||||
String content;
|
String content;
|
||||||
|
|
||||||
static void handleRoot(void)
|
static void handleRoot(void) {
|
||||||
{
|
content = F("<!DOCTYPE HTML>\n<html>Hello world from ESP8266");
|
||||||
content = F("<!DOCTYPE HTML>\n<html>Hello world from ESP8266");
|
content += F("<p>");
|
||||||
content += F("<p>");
|
content += F("</html>");
|
||||||
content += F("</html>");
|
|
||||||
|
|
||||||
wwwserver.send(200, F("text/html"), content);
|
wwwserver.send(200, F("text/html"), content);
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
Serial.begin(115200);
|
||||||
Serial.begin(115200);
|
|
||||||
|
|
||||||
// Connect to WiFi network
|
// Connect to WiFi network
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
Serial.println("");
|
Serial.println("");
|
||||||
|
|
||||||
// Wait for connection
|
// Wait for connection
|
||||||
while (WiFi.status() != WL_CONNECTED) {
|
while (WiFi.status() != WL_CONNECTED) {
|
||||||
delay(500);
|
delay(500);
|
||||||
Serial.print(".");
|
Serial.print(".");
|
||||||
}
|
}
|
||||||
Serial.println("");
|
Serial.println("");
|
||||||
Serial.print("Connected to ");
|
Serial.print("Connected to ");
|
||||||
Serial.println(ssid);
|
Serial.println(ssid);
|
||||||
Serial.print("IP address: ");
|
Serial.print("IP address: ");
|
||||||
Serial.println(WiFi.localIP());
|
Serial.println(WiFi.localIP());
|
||||||
|
|
||||||
|
|
||||||
wwwserver.on("/", handleRoot);
|
wwwserver.on("/", handleRoot);
|
||||||
wwwserver.begin();
|
wwwserver.begin();
|
||||||
|
|
||||||
NBNS.begin("ESP");
|
NBNS.begin("ESP");
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
wwwserver.handleClient();
|
||||||
wwwserver.handleClient();
|
|
||||||
}
|
}
|
||||||
|
@ -14,13 +14,13 @@ void setup() {
|
|||||||
|
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
if(WiFi.waitForConnectResult() == WL_CONNECTED){
|
if (WiFi.waitForConnectResult() == WL_CONNECTED) {
|
||||||
|
|
||||||
Serial.printf("Starting HTTP...\n");
|
Serial.printf("Starting HTTP...\n");
|
||||||
HTTP.on("/index.html", HTTP_GET, [](){
|
HTTP.on("/index.html", HTTP_GET, []() {
|
||||||
HTTP.send(200, "text/plain", "Hello World!");
|
HTTP.send(200, "text/plain", "Hello World!");
|
||||||
});
|
});
|
||||||
HTTP.on("/description.xml", HTTP_GET, [](){
|
HTTP.on("/description.xml", HTTP_GET, []() {
|
||||||
SSDP.schema(HTTP.client());
|
SSDP.schema(HTTP.client());
|
||||||
});
|
});
|
||||||
HTTP.begin();
|
HTTP.begin();
|
||||||
@ -41,7 +41,9 @@ void setup() {
|
|||||||
Serial.printf("Ready!\n");
|
Serial.printf("Ready!\n");
|
||||||
} else {
|
} else {
|
||||||
Serial.printf("WiFi Failed\n");
|
Serial.printf("WiFi Failed\n");
|
||||||
while(1) delay(100);
|
while (1) {
|
||||||
|
delay(100);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,32 +1,32 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2015, Majenko Technologies
|
Copyright (c) 2015, Majenko Technologies
|
||||||
* All rights reserved.
|
All rights reserved.
|
||||||
*
|
|
||||||
* Redistribution and use in source and binary forms, with or without modification,
|
Redistribution and use in source and binary forms, with or without modification,
|
||||||
* are permitted provided that the following conditions are met:
|
are permitted provided that the following conditions are met:
|
||||||
*
|
|
||||||
* * Redistributions of source code must retain the above copyright notice, this
|
* * Redistributions of source code must retain the above copyright notice, this
|
||||||
* list of conditions and the following disclaimer.
|
list of conditions and the following disclaimer.
|
||||||
*
|
|
||||||
* * Redistributions in binary form must reproduce the above copyright notice, this
|
* * Redistributions in binary form must reproduce the above copyright notice, this
|
||||||
* list of conditions and the following disclaimer in the documentation and/or
|
list of conditions and the following disclaimer in the documentation and/or
|
||||||
* other materials provided with the distribution.
|
other materials provided with the distribution.
|
||||||
*
|
|
||||||
* * Neither the name of Majenko Technologies nor the names of its
|
* * Neither the name of Majenko Technologies nor the names of its
|
||||||
* contributors may be used to endorse or promote products derived from
|
contributors may be used to endorse or promote products derived from
|
||||||
* this software without specific prior written permission.
|
this software without specific prior written permission.
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||||
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||||
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||||
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <WiFiClient.h>
|
#include <WiFiClient.h>
|
||||||
@ -36,20 +36,20 @@
|
|||||||
const char *ssid = "YourSSIDHere";
|
const char *ssid = "YourSSIDHere";
|
||||||
const char *password = "YourPSKHere";
|
const char *password = "YourPSKHere";
|
||||||
|
|
||||||
ESP8266WebServer server ( 80 );
|
ESP8266WebServer server(80);
|
||||||
|
|
||||||
const int led = 13;
|
const int led = 13;
|
||||||
|
|
||||||
void handleRoot() {
|
void handleRoot() {
|
||||||
digitalWrite ( led, 1 );
|
digitalWrite(led, 1);
|
||||||
char temp[400];
|
char temp[400];
|
||||||
int sec = millis() / 1000;
|
int sec = millis() / 1000;
|
||||||
int min = sec / 60;
|
int min = sec / 60;
|
||||||
int hr = min / 60;
|
int hr = min / 60;
|
||||||
|
|
||||||
snprintf ( temp, 400,
|
snprintf(temp, 400,
|
||||||
|
|
||||||
"<html>\
|
"<html>\
|
||||||
<head>\
|
<head>\
|
||||||
<meta http-equiv='refresh' content='5'/>\
|
<meta http-equiv='refresh' content='5'/>\
|
||||||
<title>ESP8266 Demo</title>\
|
<title>ESP8266 Demo</title>\
|
||||||
@ -64,83 +64,83 @@ void handleRoot() {
|
|||||||
</body>\
|
</body>\
|
||||||
</html>",
|
</html>",
|
||||||
|
|
||||||
hr, min % 60, sec % 60
|
hr, min % 60, sec % 60
|
||||||
);
|
);
|
||||||
server.send ( 200, "text/html", temp );
|
server.send(200, "text/html", temp);
|
||||||
digitalWrite ( led, 0 );
|
digitalWrite(led, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleNotFound() {
|
void handleNotFound() {
|
||||||
digitalWrite ( led, 1 );
|
digitalWrite(led, 1);
|
||||||
String message = "File Not Found\n\n";
|
String message = "File Not Found\n\n";
|
||||||
message += "URI: ";
|
message += "URI: ";
|
||||||
message += server.uri();
|
message += server.uri();
|
||||||
message += "\nMethod: ";
|
message += "\nMethod: ";
|
||||||
message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
|
message += (server.method() == HTTP_GET) ? "GET" : "POST";
|
||||||
message += "\nArguments: ";
|
message += "\nArguments: ";
|
||||||
message += server.args();
|
message += server.args();
|
||||||
message += "\n";
|
message += "\n";
|
||||||
|
|
||||||
for ( uint8_t i = 0; i < server.args(); i++ ) {
|
for (uint8_t i = 0; i < server.args(); i++) {
|
||||||
message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
|
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
server.send ( 404, "text/plain", message );
|
server.send(404, "text/plain", message);
|
||||||
digitalWrite ( led, 0 );
|
digitalWrite(led, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup ( void ) {
|
void setup(void) {
|
||||||
pinMode ( led, OUTPUT );
|
pinMode(led, OUTPUT);
|
||||||
digitalWrite ( led, 0 );
|
digitalWrite(led, 0);
|
||||||
Serial.begin ( 115200 );
|
Serial.begin(115200);
|
||||||
WiFi.mode ( WIFI_STA );
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin ( ssid, password );
|
WiFi.begin(ssid, password);
|
||||||
Serial.println ( "" );
|
Serial.println("");
|
||||||
|
|
||||||
// Wait for connection
|
// Wait for connection
|
||||||
while ( WiFi.status() != WL_CONNECTED ) {
|
while (WiFi.status() != WL_CONNECTED) {
|
||||||
delay ( 500 );
|
delay(500);
|
||||||
Serial.print ( "." );
|
Serial.print(".");
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.println ( "" );
|
Serial.println("");
|
||||||
Serial.print ( "Connected to " );
|
Serial.print("Connected to ");
|
||||||
Serial.println ( ssid );
|
Serial.println(ssid);
|
||||||
Serial.print ( "IP address: " );
|
Serial.print("IP address: ");
|
||||||
Serial.println ( WiFi.localIP() );
|
Serial.println(WiFi.localIP());
|
||||||
|
|
||||||
if ( MDNS.begin ( "esp8266" ) ) {
|
if (MDNS.begin("esp8266")) {
|
||||||
Serial.println ( "MDNS responder started" );
|
Serial.println("MDNS responder started");
|
||||||
}
|
}
|
||||||
|
|
||||||
server.on ( "/", handleRoot );
|
server.on("/", handleRoot);
|
||||||
server.on ( "/test.svg", drawGraph );
|
server.on("/test.svg", drawGraph);
|
||||||
server.on ( "/inline", []() {
|
server.on("/inline", []() {
|
||||||
server.send ( 200, "text/plain", "this works as well" );
|
server.send(200, "text/plain", "this works as well");
|
||||||
} );
|
});
|
||||||
server.onNotFound ( handleNotFound );
|
server.onNotFound(handleNotFound);
|
||||||
server.begin();
|
server.begin();
|
||||||
Serial.println ( "HTTP server started" );
|
Serial.println("HTTP server started");
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop ( void ) {
|
void loop(void) {
|
||||||
server.handleClient();
|
server.handleClient();
|
||||||
}
|
}
|
||||||
|
|
||||||
void drawGraph() {
|
void drawGraph() {
|
||||||
String out = "";
|
String out = "";
|
||||||
char temp[100];
|
char temp[100];
|
||||||
out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"400\" height=\"150\">\n";
|
out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"400\" height=\"150\">\n";
|
||||||
out += "<rect width=\"400\" height=\"150\" fill=\"rgb(250, 230, 210)\" stroke-width=\"1\" stroke=\"rgb(0, 0, 0)\" />\n";
|
out += "<rect width=\"400\" height=\"150\" fill=\"rgb(250, 230, 210)\" stroke-width=\"1\" stroke=\"rgb(0, 0, 0)\" />\n";
|
||||||
out += "<g stroke=\"black\">\n";
|
out += "<g stroke=\"black\">\n";
|
||||||
int y = rand() % 130;
|
int y = rand() % 130;
|
||||||
for (int x = 10; x < 390; x+= 10) {
|
for (int x = 10; x < 390; x += 10) {
|
||||||
int y2 = rand() % 130;
|
int y2 = rand() % 130;
|
||||||
sprintf(temp, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" stroke-width=\"1\" />\n", x, 140 - y, x + 10, 140 - y2);
|
sprintf(temp, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" stroke-width=\"1\" />\n", x, 140 - y, x + 10, 140 - y2);
|
||||||
out += temp;
|
out += temp;
|
||||||
y = y2;
|
y = y2;
|
||||||
}
|
}
|
||||||
out += "</g>\n</svg>\n";
|
out += "</g>\n</svg>\n";
|
||||||
|
|
||||||
server.send ( 200, "image/svg+xml", out);
|
server.send(200, "image/svg+xml", out);
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
/*
|
/*
|
||||||
FSWebServer - Example WebServer with SPIFFS backend for esp8266
|
FSWebServer - Example WebServer with SPIFFS backend for esp8266
|
||||||
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
|
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
|
||||||
This file is part of the ESP8266WebServer library for Arduino environment.
|
This file is part of the ESP8266WebServer library for Arduino environment.
|
||||||
|
|
||||||
This library is free software; you can redistribute it and/or
|
This library is free software; you can redistribute it and/or
|
||||||
modify it under the terms of the GNU Lesser General Public
|
modify it under the terms of the GNU Lesser General Public
|
||||||
License as published by the Free Software Foundation; either
|
License as published by the Free Software Foundation; either
|
||||||
@ -14,11 +14,11 @@
|
|||||||
You should have received a copy of the GNU Lesser General Public
|
You should have received a copy of the GNU Lesser General Public
|
||||||
License along with this library; if not, write to the Free Software
|
License along with this library; if not, write to the Free Software
|
||||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||||
|
|
||||||
upload the contents of the data folder with MkSPIFFS Tool ("ESP8266 Sketch Data Upload" in Tools menu in Arduino IDE)
|
upload the contents of the data folder with MkSPIFFS Tool ("ESP8266 Sketch Data Upload" in Tools menu in Arduino IDE)
|
||||||
or you can upload the contents of a folder if you CD in that folder and run the following command:
|
or you can upload the contents of a folder if you CD in that folder and run the following command:
|
||||||
for file in `ls -A1`; do curl -F "file=@$PWD/$file" esp8266fs.local/edit; done
|
for file in `ls -A1`; do curl -F "file=@$PWD/$file" esp8266fs.local/edit; done
|
||||||
|
|
||||||
access the sample web page at http://esp8266fs.local
|
access the sample web page at http://esp8266fs.local
|
||||||
edit the page by going to http://esp8266fs.local/edit
|
edit the page by going to http://esp8266fs.local/edit
|
||||||
*/
|
*/
|
||||||
@ -39,43 +39,60 @@ ESP8266WebServer server(80);
|
|||||||
File fsUploadFile;
|
File fsUploadFile;
|
||||||
|
|
||||||
//format bytes
|
//format bytes
|
||||||
String formatBytes(size_t bytes){
|
String formatBytes(size_t bytes) {
|
||||||
if (bytes < 1024){
|
if (bytes < 1024) {
|
||||||
return String(bytes)+"B";
|
return String(bytes) + "B";
|
||||||
} else if(bytes < (1024 * 1024)){
|
} else if (bytes < (1024 * 1024)) {
|
||||||
return String(bytes/1024.0)+"KB";
|
return String(bytes / 1024.0) + "KB";
|
||||||
} else if(bytes < (1024 * 1024 * 1024)){
|
} else if (bytes < (1024 * 1024 * 1024)) {
|
||||||
return String(bytes/1024.0/1024.0)+"MB";
|
return String(bytes / 1024.0 / 1024.0) + "MB";
|
||||||
} else {
|
} else {
|
||||||
return String(bytes/1024.0/1024.0/1024.0)+"GB";
|
return String(bytes / 1024.0 / 1024.0 / 1024.0) + "GB";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
String getContentType(String filename){
|
String getContentType(String filename) {
|
||||||
if(server.hasArg("download")) return "application/octet-stream";
|
if (server.hasArg("download")) {
|
||||||
else if(filename.endsWith(".htm")) return "text/html";
|
return "application/octet-stream";
|
||||||
else if(filename.endsWith(".html")) return "text/html";
|
} else if (filename.endsWith(".htm")) {
|
||||||
else if(filename.endsWith(".css")) return "text/css";
|
return "text/html";
|
||||||
else if(filename.endsWith(".js")) return "application/javascript";
|
} else if (filename.endsWith(".html")) {
|
||||||
else if(filename.endsWith(".png")) return "image/png";
|
return "text/html";
|
||||||
else if(filename.endsWith(".gif")) return "image/gif";
|
} else if (filename.endsWith(".css")) {
|
||||||
else if(filename.endsWith(".jpg")) return "image/jpeg";
|
return "text/css";
|
||||||
else if(filename.endsWith(".ico")) return "image/x-icon";
|
} else if (filename.endsWith(".js")) {
|
||||||
else if(filename.endsWith(".xml")) return "text/xml";
|
return "application/javascript";
|
||||||
else if(filename.endsWith(".pdf")) return "application/x-pdf";
|
} else if (filename.endsWith(".png")) {
|
||||||
else if(filename.endsWith(".zip")) return "application/x-zip";
|
return "image/png";
|
||||||
else if(filename.endsWith(".gz")) return "application/x-gzip";
|
} else if (filename.endsWith(".gif")) {
|
||||||
|
return "image/gif";
|
||||||
|
} else if (filename.endsWith(".jpg")) {
|
||||||
|
return "image/jpeg";
|
||||||
|
} else if (filename.endsWith(".ico")) {
|
||||||
|
return "image/x-icon";
|
||||||
|
} else if (filename.endsWith(".xml")) {
|
||||||
|
return "text/xml";
|
||||||
|
} else if (filename.endsWith(".pdf")) {
|
||||||
|
return "application/x-pdf";
|
||||||
|
} else if (filename.endsWith(".zip")) {
|
||||||
|
return "application/x-zip";
|
||||||
|
} else if (filename.endsWith(".gz")) {
|
||||||
|
return "application/x-gzip";
|
||||||
|
}
|
||||||
return "text/plain";
|
return "text/plain";
|
||||||
}
|
}
|
||||||
|
|
||||||
bool handleFileRead(String path){
|
bool handleFileRead(String path) {
|
||||||
DBG_OUTPUT_PORT.println("handleFileRead: " + path);
|
DBG_OUTPUT_PORT.println("handleFileRead: " + path);
|
||||||
if(path.endsWith("/")) path += "index.htm";
|
if (path.endsWith("/")) {
|
||||||
|
path += "index.htm";
|
||||||
|
}
|
||||||
String contentType = getContentType(path);
|
String contentType = getContentType(path);
|
||||||
String pathWithGz = path + ".gz";
|
String pathWithGz = path + ".gz";
|
||||||
if(SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)){
|
if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) {
|
||||||
if(SPIFFS.exists(pathWithGz))
|
if (SPIFFS.exists(pathWithGz)) {
|
||||||
path += ".gz";
|
path += ".gz";
|
||||||
|
}
|
||||||
File file = SPIFFS.open(path, "r");
|
File file = SPIFFS.open(path, "r");
|
||||||
server.streamFile(file, contentType);
|
server.streamFile(file, contentType);
|
||||||
file.close();
|
file.close();
|
||||||
@ -84,97 +101,116 @@ bool handleFileRead(String path){
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleFileUpload(){
|
void handleFileUpload() {
|
||||||
if(server.uri() != "/edit") return;
|
if (server.uri() != "/edit") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
HTTPUpload& upload = server.upload();
|
HTTPUpload& upload = server.upload();
|
||||||
if(upload.status == UPLOAD_FILE_START){
|
if (upload.status == UPLOAD_FILE_START) {
|
||||||
String filename = upload.filename;
|
String filename = upload.filename;
|
||||||
if(!filename.startsWith("/")) filename = "/"+filename;
|
if (!filename.startsWith("/")) {
|
||||||
|
filename = "/" + filename;
|
||||||
|
}
|
||||||
DBG_OUTPUT_PORT.print("handleFileUpload Name: "); DBG_OUTPUT_PORT.println(filename);
|
DBG_OUTPUT_PORT.print("handleFileUpload Name: "); DBG_OUTPUT_PORT.println(filename);
|
||||||
fsUploadFile = SPIFFS.open(filename, "w");
|
fsUploadFile = SPIFFS.open(filename, "w");
|
||||||
filename = String();
|
filename = String();
|
||||||
} else if(upload.status == UPLOAD_FILE_WRITE){
|
} else if (upload.status == UPLOAD_FILE_WRITE) {
|
||||||
//DBG_OUTPUT_PORT.print("handleFileUpload Data: "); DBG_OUTPUT_PORT.println(upload.currentSize);
|
//DBG_OUTPUT_PORT.print("handleFileUpload Data: "); DBG_OUTPUT_PORT.println(upload.currentSize);
|
||||||
if(fsUploadFile)
|
if (fsUploadFile) {
|
||||||
fsUploadFile.write(upload.buf, upload.currentSize);
|
fsUploadFile.write(upload.buf, upload.currentSize);
|
||||||
} else if(upload.status == UPLOAD_FILE_END){
|
}
|
||||||
if(fsUploadFile)
|
} else if (upload.status == UPLOAD_FILE_END) {
|
||||||
|
if (fsUploadFile) {
|
||||||
fsUploadFile.close();
|
fsUploadFile.close();
|
||||||
|
}
|
||||||
DBG_OUTPUT_PORT.print("handleFileUpload Size: "); DBG_OUTPUT_PORT.println(upload.totalSize);
|
DBG_OUTPUT_PORT.print("handleFileUpload Size: "); DBG_OUTPUT_PORT.println(upload.totalSize);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleFileDelete(){
|
void handleFileDelete() {
|
||||||
if(server.args() == 0) return server.send(500, "text/plain", "BAD ARGS");
|
if (server.args() == 0) {
|
||||||
|
return server.send(500, "text/plain", "BAD ARGS");
|
||||||
|
}
|
||||||
String path = server.arg(0);
|
String path = server.arg(0);
|
||||||
DBG_OUTPUT_PORT.println("handleFileDelete: " + path);
|
DBG_OUTPUT_PORT.println("handleFileDelete: " + path);
|
||||||
if(path == "/")
|
if (path == "/") {
|
||||||
return server.send(500, "text/plain", "BAD PATH");
|
return server.send(500, "text/plain", "BAD PATH");
|
||||||
if(!SPIFFS.exists(path))
|
}
|
||||||
|
if (!SPIFFS.exists(path)) {
|
||||||
return server.send(404, "text/plain", "FileNotFound");
|
return server.send(404, "text/plain", "FileNotFound");
|
||||||
|
}
|
||||||
SPIFFS.remove(path);
|
SPIFFS.remove(path);
|
||||||
server.send(200, "text/plain", "");
|
server.send(200, "text/plain", "");
|
||||||
path = String();
|
path = String();
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleFileCreate(){
|
void handleFileCreate() {
|
||||||
if(server.args() == 0)
|
if (server.args() == 0) {
|
||||||
return server.send(500, "text/plain", "BAD ARGS");
|
return server.send(500, "text/plain", "BAD ARGS");
|
||||||
|
}
|
||||||
String path = server.arg(0);
|
String path = server.arg(0);
|
||||||
DBG_OUTPUT_PORT.println("handleFileCreate: " + path);
|
DBG_OUTPUT_PORT.println("handleFileCreate: " + path);
|
||||||
if(path == "/")
|
if (path == "/") {
|
||||||
return server.send(500, "text/plain", "BAD PATH");
|
return server.send(500, "text/plain", "BAD PATH");
|
||||||
if(SPIFFS.exists(path))
|
}
|
||||||
|
if (SPIFFS.exists(path)) {
|
||||||
return server.send(500, "text/plain", "FILE EXISTS");
|
return server.send(500, "text/plain", "FILE EXISTS");
|
||||||
|
}
|
||||||
File file = SPIFFS.open(path, "w");
|
File file = SPIFFS.open(path, "w");
|
||||||
if(file)
|
if (file) {
|
||||||
file.close();
|
file.close();
|
||||||
else
|
} else {
|
||||||
return server.send(500, "text/plain", "CREATE FAILED");
|
return server.send(500, "text/plain", "CREATE FAILED");
|
||||||
|
}
|
||||||
server.send(200, "text/plain", "");
|
server.send(200, "text/plain", "");
|
||||||
path = String();
|
path = String();
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleFileList() {
|
void handleFileList() {
|
||||||
if(!server.hasArg("dir")) {server.send(500, "text/plain", "BAD ARGS"); return;}
|
if (!server.hasArg("dir")) {
|
||||||
|
server.send(500, "text/plain", "BAD ARGS");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
String path = server.arg("dir");
|
String path = server.arg("dir");
|
||||||
DBG_OUTPUT_PORT.println("handleFileList: " + path);
|
DBG_OUTPUT_PORT.println("handleFileList: " + path);
|
||||||
Dir dir = SPIFFS.openDir(path);
|
Dir dir = SPIFFS.openDir(path);
|
||||||
path = String();
|
path = String();
|
||||||
|
|
||||||
String output = "[";
|
String output = "[";
|
||||||
while(dir.next()){
|
while (dir.next()) {
|
||||||
File entry = dir.openFile("r");
|
File entry = dir.openFile("r");
|
||||||
if (output != "[") output += ',';
|
if (output != "[") {
|
||||||
|
output += ',';
|
||||||
|
}
|
||||||
bool isDir = false;
|
bool isDir = false;
|
||||||
output += "{\"type\":\"";
|
output += "{\"type\":\"";
|
||||||
output += (isDir)?"dir":"file";
|
output += (isDir) ? "dir" : "file";
|
||||||
output += "\",\"name\":\"";
|
output += "\",\"name\":\"";
|
||||||
output += String(entry.name()).substring(1);
|
output += String(entry.name()).substring(1);
|
||||||
output += "\"}";
|
output += "\"}";
|
||||||
entry.close();
|
entry.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
output += "]";
|
output += "]";
|
||||||
server.send(200, "text/json", output);
|
server.send(200, "text/json", output);
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup(void){
|
void setup(void) {
|
||||||
DBG_OUTPUT_PORT.begin(115200);
|
DBG_OUTPUT_PORT.begin(115200);
|
||||||
DBG_OUTPUT_PORT.print("\n");
|
DBG_OUTPUT_PORT.print("\n");
|
||||||
DBG_OUTPUT_PORT.setDebugOutput(true);
|
DBG_OUTPUT_PORT.setDebugOutput(true);
|
||||||
SPIFFS.begin();
|
SPIFFS.begin();
|
||||||
{
|
{
|
||||||
Dir dir = SPIFFS.openDir("/");
|
Dir dir = SPIFFS.openDir("/");
|
||||||
while (dir.next()) {
|
while (dir.next()) {
|
||||||
String fileName = dir.fileName();
|
String fileName = dir.fileName();
|
||||||
size_t fileSize = dir.fileSize();
|
size_t fileSize = dir.fileSize();
|
||||||
DBG_OUTPUT_PORT.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str());
|
DBG_OUTPUT_PORT.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str());
|
||||||
}
|
}
|
||||||
DBG_OUTPUT_PORT.printf("\n");
|
DBG_OUTPUT_PORT.printf("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//WIFI INIT
|
//WIFI INIT
|
||||||
DBG_OUTPUT_PORT.printf("Connecting to %s\n", ssid);
|
DBG_OUTPUT_PORT.printf("Connecting to %s\n", ssid);
|
||||||
@ -182,7 +218,7 @@ void setup(void){
|
|||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
}
|
}
|
||||||
|
|
||||||
while (WiFi.status() != WL_CONNECTED) {
|
while (WiFi.status() != WL_CONNECTED) {
|
||||||
delay(500);
|
delay(500);
|
||||||
DBG_OUTPUT_PORT.print(".");
|
DBG_OUTPUT_PORT.print(".");
|
||||||
@ -195,14 +231,16 @@ void setup(void){
|
|||||||
DBG_OUTPUT_PORT.print("Open http://");
|
DBG_OUTPUT_PORT.print("Open http://");
|
||||||
DBG_OUTPUT_PORT.print(host);
|
DBG_OUTPUT_PORT.print(host);
|
||||||
DBG_OUTPUT_PORT.println(".local/edit to see the file browser");
|
DBG_OUTPUT_PORT.println(".local/edit to see the file browser");
|
||||||
|
|
||||||
|
|
||||||
//SERVER INIT
|
//SERVER INIT
|
||||||
//list directory
|
//list directory
|
||||||
server.on("/list", HTTP_GET, handleFileList);
|
server.on("/list", HTTP_GET, handleFileList);
|
||||||
//load editor
|
//load editor
|
||||||
server.on("/edit", HTTP_GET, [](){
|
server.on("/edit", HTTP_GET, []() {
|
||||||
if(!handleFileRead("/edit.htm")) server.send(404, "text/plain", "FileNotFound");
|
if (!handleFileRead("/edit.htm")) {
|
||||||
|
server.send(404, "text/plain", "FileNotFound");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
//create file
|
//create file
|
||||||
server.on("/edit", HTTP_PUT, handleFileCreate);
|
server.on("/edit", HTTP_PUT, handleFileCreate);
|
||||||
@ -210,21 +248,24 @@ void setup(void){
|
|||||||
server.on("/edit", HTTP_DELETE, handleFileDelete);
|
server.on("/edit", HTTP_DELETE, handleFileDelete);
|
||||||
//first callback is called after the request has ended with all parsed arguments
|
//first callback is called after the request has ended with all parsed arguments
|
||||||
//second callback handles file uploads at that location
|
//second callback handles file uploads at that location
|
||||||
server.on("/edit", HTTP_POST, [](){ server.send(200, "text/plain", ""); }, handleFileUpload);
|
server.on("/edit", HTTP_POST, []() {
|
||||||
|
server.send(200, "text/plain", "");
|
||||||
|
}, handleFileUpload);
|
||||||
|
|
||||||
//called when the url is not defined here
|
//called when the url is not defined here
|
||||||
//use it to load content from SPIFFS
|
//use it to load content from SPIFFS
|
||||||
server.onNotFound([](){
|
server.onNotFound([]() {
|
||||||
if(!handleFileRead(server.uri()))
|
if (!handleFileRead(server.uri())) {
|
||||||
server.send(404, "text/plain", "FileNotFound");
|
server.send(404, "text/plain", "FileNotFound");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
//get heap status, analog input value and all GPIO statuses in one json call
|
//get heap status, analog input value and all GPIO statuses in one json call
|
||||||
server.on("/all", HTTP_GET, [](){
|
server.on("/all", HTTP_GET, []() {
|
||||||
String json = "{";
|
String json = "{";
|
||||||
json += "\"heap\":"+String(ESP.getFreeHeap());
|
json += "\"heap\":" + String(ESP.getFreeHeap());
|
||||||
json += ", \"analog\":"+String(analogRead(A0));
|
json += ", \"analog\":" + String(analogRead(A0));
|
||||||
json += ", \"gpio\":"+String((uint32_t)(((GPI | GPO) & 0xFFFF) | ((GP16I & 0x01) << 16)));
|
json += ", \"gpio\":" + String((uint32_t)(((GPI | GPO) & 0xFFFF) | ((GP16I & 0x01) << 16)));
|
||||||
json += "}";
|
json += "}";
|
||||||
server.send(200, "text/json", json);
|
server.send(200, "text/json", json);
|
||||||
json = String();
|
json = String();
|
||||||
@ -233,7 +274,7 @@ void setup(void){
|
|||||||
DBG_OUTPUT_PORT.println("HTTP server started");
|
DBG_OUTPUT_PORT.println("HTTP server started");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop(void){
|
void loop(void) {
|
||||||
server.handleClient();
|
server.handleClient();
|
||||||
}
|
}
|
||||||
|
@ -16,24 +16,24 @@ void handleRoot() {
|
|||||||
digitalWrite(led, 0);
|
digitalWrite(led, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleNotFound(){
|
void handleNotFound() {
|
||||||
digitalWrite(led, 1);
|
digitalWrite(led, 1);
|
||||||
String message = "File Not Found\n\n";
|
String message = "File Not Found\n\n";
|
||||||
message += "URI: ";
|
message += "URI: ";
|
||||||
message += server.uri();
|
message += server.uri();
|
||||||
message += "\nMethod: ";
|
message += "\nMethod: ";
|
||||||
message += (server.method() == HTTP_GET)?"GET":"POST";
|
message += (server.method() == HTTP_GET) ? "GET" : "POST";
|
||||||
message += "\nArguments: ";
|
message += "\nArguments: ";
|
||||||
message += server.args();
|
message += server.args();
|
||||||
message += "\n";
|
message += "\n";
|
||||||
for (uint8_t i=0; i<server.args(); i++){
|
for (uint8_t i = 0; i < server.args(); i++) {
|
||||||
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
|
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
|
||||||
}
|
}
|
||||||
server.send(404, "text/plain", message);
|
server.send(404, "text/plain", message);
|
||||||
digitalWrite(led, 0);
|
digitalWrite(led, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup(void){
|
void setup(void) {
|
||||||
pinMode(led, OUTPUT);
|
pinMode(led, OUTPUT);
|
||||||
digitalWrite(led, 0);
|
digitalWrite(led, 0);
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
@ -58,7 +58,7 @@ void setup(void){
|
|||||||
|
|
||||||
server.on("/", handleRoot);
|
server.on("/", handleRoot);
|
||||||
|
|
||||||
server.on("/inline", [](){
|
server.on("/inline", []() {
|
||||||
server.send(200, "text/plain", "this works as well");
|
server.send(200, "text/plain", "this works as well");
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -68,6 +68,6 @@ void setup(void){
|
|||||||
Serial.println("HTTP server started");
|
Serial.println("HTTP server started");
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop(void){
|
void loop(void) {
|
||||||
server.handleClient();
|
server.handleClient();
|
||||||
}
|
}
|
||||||
|
@ -51,7 +51,7 @@ const char* password = "........";
|
|||||||
|
|
||||||
ESP8266WebServerSecure server(443);
|
ESP8266WebServerSecure server(443);
|
||||||
|
|
||||||
// The certificate is stored in PMEM
|
// The certificate is stored in PMEM
|
||||||
static const uint8_t x509[] PROGMEM = {
|
static const uint8_t x509[] PROGMEM = {
|
||||||
0x30, 0x82, 0x01, 0x3d, 0x30, 0x81, 0xe8, 0x02, 0x09, 0x00, 0xfe, 0x56,
|
0x30, 0x82, 0x01, 0x3d, 0x30, 0x81, 0xe8, 0x02, 0x09, 0x00, 0xfe, 0x56,
|
||||||
0x46, 0xf2, 0x78, 0xc6, 0x51, 0x17, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86,
|
0x46, 0xf2, 0x78, 0xc6, 0x51, 0x17, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86,
|
||||||
@ -121,24 +121,24 @@ void handleRoot() {
|
|||||||
digitalWrite(led, 0);
|
digitalWrite(led, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleNotFound(){
|
void handleNotFound() {
|
||||||
digitalWrite(led, 1);
|
digitalWrite(led, 1);
|
||||||
String message = "File Not Found\n\n";
|
String message = "File Not Found\n\n";
|
||||||
message += "URI: ";
|
message += "URI: ";
|
||||||
message += server.uri();
|
message += server.uri();
|
||||||
message += "\nMethod: ";
|
message += "\nMethod: ";
|
||||||
message += (server.method() == HTTP_GET)?"GET":"POST";
|
message += (server.method() == HTTP_GET) ? "GET" : "POST";
|
||||||
message += "\nArguments: ";
|
message += "\nArguments: ";
|
||||||
message += server.args();
|
message += server.args();
|
||||||
message += "\n";
|
message += "\n";
|
||||||
for (uint8_t i=0; i<server.args(); i++){
|
for (uint8_t i = 0; i < server.args(); i++) {
|
||||||
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
|
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
|
||||||
}
|
}
|
||||||
server.send(404, "text/plain", message);
|
server.send(404, "text/plain", message);
|
||||||
digitalWrite(led, 0);
|
digitalWrite(led, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup(void){
|
void setup(void) {
|
||||||
pinMode(led, OUTPUT);
|
pinMode(led, OUTPUT);
|
||||||
digitalWrite(led, 0);
|
digitalWrite(led, 0);
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
@ -164,7 +164,7 @@ void setup(void){
|
|||||||
|
|
||||||
server.on("/", handleRoot);
|
server.on("/", handleRoot);
|
||||||
|
|
||||||
server.on("/inline", [](){
|
server.on("/inline", []() {
|
||||||
server.send(200, "text/plain", "this works as well");
|
server.send(200, "text/plain", "this works as well");
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -174,6 +174,6 @@ void setup(void){
|
|||||||
Serial.println("HTTPS server started");
|
Serial.println("HTTPS server started");
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop(void){
|
void loop(void) {
|
||||||
server.handleClient();
|
server.handleClient();
|
||||||
}
|
}
|
||||||
|
@ -16,7 +16,7 @@ ESP8266WebServer server(80);
|
|||||||
|
|
||||||
const char* www_username = "admin";
|
const char* www_username = "admin";
|
||||||
const char* www_password = "esp8266";
|
const char* www_password = "esp8266";
|
||||||
// allows you to set the realm of authentication Default:"Login Required"
|
// allows you to set the realm of authentication Default:"Login Required"
|
||||||
const char* www_realm = "Custom Auth Realm";
|
const char* www_realm = "Custom Auth Realm";
|
||||||
// the Content of the HTML response in case of Unautherized Access Default:empty
|
// the Content of the HTML response in case of Unautherized Access Default:empty
|
||||||
String authFailResponse = "Authentication Failed";
|
String authFailResponse = "Authentication Failed";
|
||||||
@ -25,23 +25,25 @@ void setup() {
|
|||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
if(WiFi.waitForConnectResult() != WL_CONNECTED) {
|
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
|
||||||
Serial.println("WiFi Connect Failed! Rebooting...");
|
Serial.println("WiFi Connect Failed! Rebooting...");
|
||||||
delay(1000);
|
delay(1000);
|
||||||
ESP.restart();
|
ESP.restart();
|
||||||
}
|
}
|
||||||
ArduinoOTA.begin();
|
ArduinoOTA.begin();
|
||||||
|
|
||||||
server.on("/", [](){
|
server.on("/", []() {
|
||||||
if(!server.authenticate(www_username, www_password))
|
if (!server.authenticate(www_username, www_password))
|
||||||
//Basic Auth Method with Custom realm and Failure Response
|
//Basic Auth Method with Custom realm and Failure Response
|
||||||
//return server.requestAuthentication(BASIC_AUTH, www_realm, authFailResponse);
|
//return server.requestAuthentication(BASIC_AUTH, www_realm, authFailResponse);
|
||||||
//Digest Auth Method with realm="Login Required" and empty Failure Response
|
//Digest Auth Method with realm="Login Required" and empty Failure Response
|
||||||
//return server.requestAuthentication(DIGEST_AUTH);
|
//return server.requestAuthentication(DIGEST_AUTH);
|
||||||
//Digest Auth Method with Custom realm and empty Failure Response
|
//Digest Auth Method with Custom realm and empty Failure Response
|
||||||
//return server.requestAuthentication(DIGEST_AUTH, www_realm);
|
//return server.requestAuthentication(DIGEST_AUTH, www_realm);
|
||||||
//Digest Auth Method with Custom realm and Failure Response
|
//Digest Auth Method with Custom realm and Failure Response
|
||||||
|
{
|
||||||
return server.requestAuthentication(DIGEST_AUTH, www_realm, authFailResponse);
|
return server.requestAuthentication(DIGEST_AUTH, www_realm, authFailResponse);
|
||||||
|
}
|
||||||
server.send(200, "text/plain", "Login OK");
|
server.send(200, "text/plain", "Login OK");
|
||||||
});
|
});
|
||||||
server.begin();
|
server.begin();
|
||||||
|
@ -15,16 +15,17 @@ void setup() {
|
|||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
if(WiFi.waitForConnectResult() != WL_CONNECTED) {
|
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
|
||||||
Serial.println("WiFi Connect Failed! Rebooting...");
|
Serial.println("WiFi Connect Failed! Rebooting...");
|
||||||
delay(1000);
|
delay(1000);
|
||||||
ESP.restart();
|
ESP.restart();
|
||||||
}
|
}
|
||||||
ArduinoOTA.begin();
|
ArduinoOTA.begin();
|
||||||
|
|
||||||
server.on("/", [](){
|
server.on("/", []() {
|
||||||
if(!server.authenticate(www_username, www_password))
|
if (!server.authenticate(www_username, www_password)) {
|
||||||
return server.requestAuthentication();
|
return server.requestAuthentication();
|
||||||
|
}
|
||||||
server.send(200, "text/plain", "Login OK");
|
server.send(200, "text/plain", "Login OK");
|
||||||
});
|
});
|
||||||
server.begin();
|
server.begin();
|
||||||
|
@ -54,33 +54,50 @@ void returnFail(String msg) {
|
|||||||
server.send(500, "text/plain", msg + "\r\n");
|
server.send(500, "text/plain", msg + "\r\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
bool loadFromSdCard(String path){
|
bool loadFromSdCard(String path) {
|
||||||
String dataType = "text/plain";
|
String dataType = "text/plain";
|
||||||
if(path.endsWith("/")) path += "index.htm";
|
if (path.endsWith("/")) {
|
||||||
|
path += "index.htm";
|
||||||
|
}
|
||||||
|
|
||||||
if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf("."));
|
if (path.endsWith(".src")) {
|
||||||
else if(path.endsWith(".htm")) dataType = "text/html";
|
path = path.substring(0, path.lastIndexOf("."));
|
||||||
else if(path.endsWith(".css")) dataType = "text/css";
|
} else if (path.endsWith(".htm")) {
|
||||||
else if(path.endsWith(".js")) dataType = "application/javascript";
|
dataType = "text/html";
|
||||||
else if(path.endsWith(".png")) dataType = "image/png";
|
} else if (path.endsWith(".css")) {
|
||||||
else if(path.endsWith(".gif")) dataType = "image/gif";
|
dataType = "text/css";
|
||||||
else if(path.endsWith(".jpg")) dataType = "image/jpeg";
|
} else if (path.endsWith(".js")) {
|
||||||
else if(path.endsWith(".ico")) dataType = "image/x-icon";
|
dataType = "application/javascript";
|
||||||
else if(path.endsWith(".xml")) dataType = "text/xml";
|
} else if (path.endsWith(".png")) {
|
||||||
else if(path.endsWith(".pdf")) dataType = "application/pdf";
|
dataType = "image/png";
|
||||||
else if(path.endsWith(".zip")) dataType = "application/zip";
|
} else if (path.endsWith(".gif")) {
|
||||||
|
dataType = "image/gif";
|
||||||
|
} else if (path.endsWith(".jpg")) {
|
||||||
|
dataType = "image/jpeg";
|
||||||
|
} else if (path.endsWith(".ico")) {
|
||||||
|
dataType = "image/x-icon";
|
||||||
|
} else if (path.endsWith(".xml")) {
|
||||||
|
dataType = "text/xml";
|
||||||
|
} else if (path.endsWith(".pdf")) {
|
||||||
|
dataType = "application/pdf";
|
||||||
|
} else if (path.endsWith(".zip")) {
|
||||||
|
dataType = "application/zip";
|
||||||
|
}
|
||||||
|
|
||||||
File dataFile = SD.open(path.c_str());
|
File dataFile = SD.open(path.c_str());
|
||||||
if(dataFile.isDirectory()){
|
if (dataFile.isDirectory()) {
|
||||||
path += "/index.htm";
|
path += "/index.htm";
|
||||||
dataType = "text/html";
|
dataType = "text/html";
|
||||||
dataFile = SD.open(path.c_str());
|
dataFile = SD.open(path.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!dataFile)
|
if (!dataFile) {
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if (server.hasArg("download")) dataType = "application/octet-stream";
|
if (server.hasArg("download")) {
|
||||||
|
dataType = "application/octet-stream";
|
||||||
|
}
|
||||||
|
|
||||||
if (server.streamFile(dataFile, dataType) != dataFile.size()) {
|
if (server.streamFile(dataFile, dataType) != dataFile.size()) {
|
||||||
DBG_OUTPUT_PORT.println("Sent less data than expected!");
|
DBG_OUTPUT_PORT.println("Sent less data than expected!");
|
||||||
@ -90,36 +107,46 @@ bool loadFromSdCard(String path){
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleFileUpload(){
|
void handleFileUpload() {
|
||||||
if(server.uri() != "/edit") return;
|
if (server.uri() != "/edit") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
HTTPUpload& upload = server.upload();
|
HTTPUpload& upload = server.upload();
|
||||||
if(upload.status == UPLOAD_FILE_START){
|
if (upload.status == UPLOAD_FILE_START) {
|
||||||
if(SD.exists((char *)upload.filename.c_str())) SD.remove((char *)upload.filename.c_str());
|
if (SD.exists((char *)upload.filename.c_str())) {
|
||||||
|
SD.remove((char *)upload.filename.c_str());
|
||||||
|
}
|
||||||
uploadFile = SD.open(upload.filename.c_str(), FILE_WRITE);
|
uploadFile = SD.open(upload.filename.c_str(), FILE_WRITE);
|
||||||
DBG_OUTPUT_PORT.print("Upload: START, filename: "); DBG_OUTPUT_PORT.println(upload.filename);
|
DBG_OUTPUT_PORT.print("Upload: START, filename: "); DBG_OUTPUT_PORT.println(upload.filename);
|
||||||
} else if(upload.status == UPLOAD_FILE_WRITE){
|
} else if (upload.status == UPLOAD_FILE_WRITE) {
|
||||||
if(uploadFile) uploadFile.write(upload.buf, upload.currentSize);
|
if (uploadFile) {
|
||||||
|
uploadFile.write(upload.buf, upload.currentSize);
|
||||||
|
}
|
||||||
DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: "); DBG_OUTPUT_PORT.println(upload.currentSize);
|
DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: "); DBG_OUTPUT_PORT.println(upload.currentSize);
|
||||||
} else if(upload.status == UPLOAD_FILE_END){
|
} else if (upload.status == UPLOAD_FILE_END) {
|
||||||
if(uploadFile) uploadFile.close();
|
if (uploadFile) {
|
||||||
|
uploadFile.close();
|
||||||
|
}
|
||||||
DBG_OUTPUT_PORT.print("Upload: END, Size: "); DBG_OUTPUT_PORT.println(upload.totalSize);
|
DBG_OUTPUT_PORT.print("Upload: END, Size: "); DBG_OUTPUT_PORT.println(upload.totalSize);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void deleteRecursive(String path){
|
void deleteRecursive(String path) {
|
||||||
File file = SD.open((char *)path.c_str());
|
File file = SD.open((char *)path.c_str());
|
||||||
if(!file.isDirectory()){
|
if (!file.isDirectory()) {
|
||||||
file.close();
|
file.close();
|
||||||
SD.remove((char *)path.c_str());
|
SD.remove((char *)path.c_str());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
file.rewindDirectory();
|
file.rewindDirectory();
|
||||||
while(true) {
|
while (true) {
|
||||||
File entry = file.openNextFile();
|
File entry = file.openNextFile();
|
||||||
if (!entry) break;
|
if (!entry) {
|
||||||
String entryPath = path + "/" +entry.name();
|
break;
|
||||||
if(entry.isDirectory()){
|
}
|
||||||
|
String entryPath = path + "/" + entry.name();
|
||||||
|
if (entry.isDirectory()) {
|
||||||
entry.close();
|
entry.close();
|
||||||
deleteRecursive(entryPath);
|
deleteRecursive(entryPath);
|
||||||
} else {
|
} else {
|
||||||
@ -133,10 +160,12 @@ void deleteRecursive(String path){
|
|||||||
file.close();
|
file.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleDelete(){
|
void handleDelete() {
|
||||||
if(server.args() == 0) return returnFail("BAD ARGS");
|
if (server.args() == 0) {
|
||||||
|
return returnFail("BAD ARGS");
|
||||||
|
}
|
||||||
String path = server.arg(0);
|
String path = server.arg(0);
|
||||||
if(path == "/" || !SD.exists((char *)path.c_str())) {
|
if (path == "/" || !SD.exists((char *)path.c_str())) {
|
||||||
returnFail("BAD PATH");
|
returnFail("BAD PATH");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -144,17 +173,19 @@ void handleDelete(){
|
|||||||
returnOK();
|
returnOK();
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleCreate(){
|
void handleCreate() {
|
||||||
if(server.args() == 0) return returnFail("BAD ARGS");
|
if (server.args() == 0) {
|
||||||
|
return returnFail("BAD ARGS");
|
||||||
|
}
|
||||||
String path = server.arg(0);
|
String path = server.arg(0);
|
||||||
if(path == "/" || SD.exists((char *)path.c_str())) {
|
if (path == "/" || SD.exists((char *)path.c_str())) {
|
||||||
returnFail("BAD PATH");
|
returnFail("BAD PATH");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(path.indexOf('.') > 0){
|
if (path.indexOf('.') > 0) {
|
||||||
File file = SD.open((char *)path.c_str(), FILE_WRITE);
|
File file = SD.open((char *)path.c_str(), FILE_WRITE);
|
||||||
if(file){
|
if (file) {
|
||||||
file.write((const char *)0);
|
file.write((const char *)0);
|
||||||
file.close();
|
file.close();
|
||||||
}
|
}
|
||||||
@ -165,12 +196,16 @@ void handleCreate(){
|
|||||||
}
|
}
|
||||||
|
|
||||||
void printDirectory() {
|
void printDirectory() {
|
||||||
if(!server.hasArg("dir")) return returnFail("BAD ARGS");
|
if (!server.hasArg("dir")) {
|
||||||
|
return returnFail("BAD ARGS");
|
||||||
|
}
|
||||||
String path = server.arg("dir");
|
String path = server.arg("dir");
|
||||||
if(path != "/" && !SD.exists((char *)path.c_str())) return returnFail("BAD PATH");
|
if (path != "/" && !SD.exists((char *)path.c_str())) {
|
||||||
|
return returnFail("BAD PATH");
|
||||||
|
}
|
||||||
File dir = SD.open((char *)path.c_str());
|
File dir = SD.open((char *)path.c_str());
|
||||||
path = String();
|
path = String();
|
||||||
if(!dir.isDirectory()){
|
if (!dir.isDirectory()) {
|
||||||
dir.close();
|
dir.close();
|
||||||
return returnFail("NOT DIR");
|
return returnFail("NOT DIR");
|
||||||
}
|
}
|
||||||
@ -182,12 +217,14 @@ void printDirectory() {
|
|||||||
server.sendContent("[");
|
server.sendContent("[");
|
||||||
for (int cnt = 0; true; ++cnt) {
|
for (int cnt = 0; true; ++cnt) {
|
||||||
File entry = dir.openNextFile();
|
File entry = dir.openNextFile();
|
||||||
if (!entry)
|
if (!entry) {
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
String output;
|
String output;
|
||||||
if (cnt > 0)
|
if (cnt > 0) {
|
||||||
output = ',';
|
output = ',';
|
||||||
|
}
|
||||||
|
|
||||||
output += "{\"type\":\"";
|
output += "{\"type\":\"";
|
||||||
output += (entry.isDirectory()) ? "dir" : "file";
|
output += (entry.isDirectory()) ? "dir" : "file";
|
||||||
@ -197,29 +234,31 @@ void printDirectory() {
|
|||||||
output += "}";
|
output += "}";
|
||||||
server.sendContent(output);
|
server.sendContent(output);
|
||||||
entry.close();
|
entry.close();
|
||||||
}
|
}
|
||||||
server.sendContent("]");
|
server.sendContent("]");
|
||||||
dir.close();
|
dir.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
void handleNotFound(){
|
void handleNotFound() {
|
||||||
if(hasSD && loadFromSdCard(server.uri())) return;
|
if (hasSD && loadFromSdCard(server.uri())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
String message = "SDCARD Not Detected\n\n";
|
String message = "SDCARD Not Detected\n\n";
|
||||||
message += "URI: ";
|
message += "URI: ";
|
||||||
message += server.uri();
|
message += server.uri();
|
||||||
message += "\nMethod: ";
|
message += "\nMethod: ";
|
||||||
message += (server.method() == HTTP_GET)?"GET":"POST";
|
message += (server.method() == HTTP_GET) ? "GET" : "POST";
|
||||||
message += "\nArguments: ";
|
message += "\nArguments: ";
|
||||||
message += server.args();
|
message += server.args();
|
||||||
message += "\n";
|
message += "\n";
|
||||||
for (uint8_t i=0; i<server.args(); i++){
|
for (uint8_t i = 0; i < server.args(); i++) {
|
||||||
message += " NAME:"+server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
|
message += " NAME:" + server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
|
||||||
}
|
}
|
||||||
server.send(404, "text/plain", message);
|
server.send(404, "text/plain", message);
|
||||||
DBG_OUTPUT_PORT.print(message);
|
DBG_OUTPUT_PORT.print(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup(void){
|
void setup(void) {
|
||||||
DBG_OUTPUT_PORT.begin(115200);
|
DBG_OUTPUT_PORT.begin(115200);
|
||||||
DBG_OUTPUT_PORT.setDebugOutput(true);
|
DBG_OUTPUT_PORT.setDebugOutput(true);
|
||||||
DBG_OUTPUT_PORT.print("\n");
|
DBG_OUTPUT_PORT.print("\n");
|
||||||
@ -233,10 +272,12 @@ void setup(void){
|
|||||||
while (WiFi.status() != WL_CONNECTED && i++ < 20) {//wait 10 seconds
|
while (WiFi.status() != WL_CONNECTED && i++ < 20) {//wait 10 seconds
|
||||||
delay(500);
|
delay(500);
|
||||||
}
|
}
|
||||||
if(i == 21){
|
if (i == 21) {
|
||||||
DBG_OUTPUT_PORT.print("Could not connect to");
|
DBG_OUTPUT_PORT.print("Could not connect to");
|
||||||
DBG_OUTPUT_PORT.println(ssid);
|
DBG_OUTPUT_PORT.println(ssid);
|
||||||
while(1) delay(500);
|
while (1) {
|
||||||
|
delay(500);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
DBG_OUTPUT_PORT.print("Connected! IP address: ");
|
DBG_OUTPUT_PORT.print("Connected! IP address: ");
|
||||||
DBG_OUTPUT_PORT.println(WiFi.localIP());
|
DBG_OUTPUT_PORT.println(WiFi.localIP());
|
||||||
@ -253,18 +294,20 @@ void setup(void){
|
|||||||
server.on("/list", HTTP_GET, printDirectory);
|
server.on("/list", HTTP_GET, printDirectory);
|
||||||
server.on("/edit", HTTP_DELETE, handleDelete);
|
server.on("/edit", HTTP_DELETE, handleDelete);
|
||||||
server.on("/edit", HTTP_PUT, handleCreate);
|
server.on("/edit", HTTP_PUT, handleCreate);
|
||||||
server.on("/edit", HTTP_POST, [](){ returnOK(); }, handleFileUpload);
|
server.on("/edit", HTTP_POST, []() {
|
||||||
|
returnOK();
|
||||||
|
}, handleFileUpload);
|
||||||
server.onNotFound(handleNotFound);
|
server.onNotFound(handleNotFound);
|
||||||
|
|
||||||
server.begin();
|
server.begin();
|
||||||
DBG_OUTPUT_PORT.println("HTTP server started");
|
DBG_OUTPUT_PORT.println("HTTP server started");
|
||||||
|
|
||||||
if (SD.begin(SS)){
|
if (SD.begin(SS)) {
|
||||||
DBG_OUTPUT_PORT.println("SD Card initialized.");
|
DBG_OUTPUT_PORT.println("SD Card initialized.");
|
||||||
hasSD = true;
|
hasSD = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop(void){
|
void loop(void) {
|
||||||
server.handleClient();
|
server.handleClient();
|
||||||
}
|
}
|
||||||
|
@ -8,9 +8,9 @@ const char* password = "........";
|
|||||||
ESP8266WebServer server(80);
|
ESP8266WebServer server(80);
|
||||||
|
|
||||||
//Check if header is present and correct
|
//Check if header is present and correct
|
||||||
bool is_authentified(){
|
bool is_authentified() {
|
||||||
Serial.println("Enter is_authentified");
|
Serial.println("Enter is_authentified");
|
||||||
if (server.hasHeader("Cookie")){
|
if (server.hasHeader("Cookie")) {
|
||||||
Serial.print("Found cookie: ");
|
Serial.print("Found cookie: ");
|
||||||
String cookie = server.header("Cookie");
|
String cookie = server.header("Cookie");
|
||||||
Serial.println(cookie);
|
Serial.println(cookie);
|
||||||
@ -24,32 +24,32 @@ bool is_authentified(){
|
|||||||
}
|
}
|
||||||
|
|
||||||
//login page, also called for disconnect
|
//login page, also called for disconnect
|
||||||
void handleLogin(){
|
void handleLogin() {
|
||||||
String msg;
|
String msg;
|
||||||
if (server.hasHeader("Cookie")){
|
if (server.hasHeader("Cookie")) {
|
||||||
Serial.print("Found cookie: ");
|
Serial.print("Found cookie: ");
|
||||||
String cookie = server.header("Cookie");
|
String cookie = server.header("Cookie");
|
||||||
Serial.println(cookie);
|
Serial.println(cookie);
|
||||||
}
|
}
|
||||||
if (server.hasArg("DISCONNECT")){
|
if (server.hasArg("DISCONNECT")) {
|
||||||
Serial.println("Disconnection");
|
Serial.println("Disconnection");
|
||||||
server.sendHeader("Location","/login");
|
server.sendHeader("Location", "/login");
|
||||||
server.sendHeader("Cache-Control","no-cache");
|
server.sendHeader("Cache-Control", "no-cache");
|
||||||
server.sendHeader("Set-Cookie","ESPSESSIONID=0");
|
server.sendHeader("Set-Cookie", "ESPSESSIONID=0");
|
||||||
server.send(301);
|
server.send(301);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (server.hasArg("USERNAME") && server.hasArg("PASSWORD")){
|
if (server.hasArg("USERNAME") && server.hasArg("PASSWORD")) {
|
||||||
if (server.arg("USERNAME") == "admin" && server.arg("PASSWORD") == "admin" ){
|
if (server.arg("USERNAME") == "admin" && server.arg("PASSWORD") == "admin") {
|
||||||
server.sendHeader("Location","/");
|
server.sendHeader("Location", "/");
|
||||||
server.sendHeader("Cache-Control","no-cache");
|
server.sendHeader("Cache-Control", "no-cache");
|
||||||
server.sendHeader("Set-Cookie","ESPSESSIONID=1");
|
server.sendHeader("Set-Cookie", "ESPSESSIONID=1");
|
||||||
server.send(301);
|
server.send(301);
|
||||||
Serial.println("Log in Successful");
|
Serial.println("Log in Successful");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
msg = "Wrong username/password! try again.";
|
msg = "Wrong username/password! try again.";
|
||||||
Serial.println("Log in Failed");
|
Serial.println("Log in Failed");
|
||||||
}
|
}
|
||||||
String content = "<html><body><form action='/login' method='POST'>To log in, please use : admin/admin<br>";
|
String content = "<html><body><form action='/login' method='POST'>To log in, please use : admin/admin<br>";
|
||||||
content += "User:<input type='text' name='USERNAME' placeholder='user name'><br>";
|
content += "User:<input type='text' name='USERNAME' placeholder='user name'><br>";
|
||||||
@ -60,17 +60,17 @@ void handleLogin(){
|
|||||||
}
|
}
|
||||||
|
|
||||||
//root page can be accessed only if authentification is ok
|
//root page can be accessed only if authentification is ok
|
||||||
void handleRoot(){
|
void handleRoot() {
|
||||||
Serial.println("Enter handleRoot");
|
Serial.println("Enter handleRoot");
|
||||||
String header;
|
String header;
|
||||||
if (!is_authentified()){
|
if (!is_authentified()) {
|
||||||
server.sendHeader("Location","/login");
|
server.sendHeader("Location", "/login");
|
||||||
server.sendHeader("Cache-Control","no-cache");
|
server.sendHeader("Cache-Control", "no-cache");
|
||||||
server.send(301);
|
server.send(301);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String content = "<html><body><H2>hello, you successfully connected to esp8266!</H2><br>";
|
String content = "<html><body><H2>hello, you successfully connected to esp8266!</H2><br>";
|
||||||
if (server.hasHeader("User-Agent")){
|
if (server.hasHeader("User-Agent")) {
|
||||||
content += "the user agent used is : " + server.header("User-Agent") + "<br><br>";
|
content += "the user agent used is : " + server.header("User-Agent") + "<br><br>";
|
||||||
}
|
}
|
||||||
content += "You can access this page until you <a href=\"/login?DISCONNECT=YES\">disconnect</a></body></html>";
|
content += "You can access this page until you <a href=\"/login?DISCONNECT=YES\">disconnect</a></body></html>";
|
||||||
@ -78,22 +78,22 @@ void handleRoot(){
|
|||||||
}
|
}
|
||||||
|
|
||||||
//no need authentification
|
//no need authentification
|
||||||
void handleNotFound(){
|
void handleNotFound() {
|
||||||
String message = "File Not Found\n\n";
|
String message = "File Not Found\n\n";
|
||||||
message += "URI: ";
|
message += "URI: ";
|
||||||
message += server.uri();
|
message += server.uri();
|
||||||
message += "\nMethod: ";
|
message += "\nMethod: ";
|
||||||
message += (server.method() == HTTP_GET)?"GET":"POST";
|
message += (server.method() == HTTP_GET) ? "GET" : "POST";
|
||||||
message += "\nArguments: ";
|
message += "\nArguments: ";
|
||||||
message += server.args();
|
message += server.args();
|
||||||
message += "\n";
|
message += "\n";
|
||||||
for (uint8_t i=0; i<server.args(); i++){
|
for (uint8_t i = 0; i < server.args(); i++) {
|
||||||
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
|
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
|
||||||
}
|
}
|
||||||
server.send(404, "text/plain", message);
|
server.send(404, "text/plain", message);
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup(void){
|
void setup(void) {
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
@ -113,20 +113,20 @@ void setup(void){
|
|||||||
|
|
||||||
server.on("/", handleRoot);
|
server.on("/", handleRoot);
|
||||||
server.on("/login", handleLogin);
|
server.on("/login", handleLogin);
|
||||||
server.on("/inline", [](){
|
server.on("/inline", []() {
|
||||||
server.send(200, "text/plain", "this works without need of authentification");
|
server.send(200, "text/plain", "this works without need of authentification");
|
||||||
});
|
});
|
||||||
|
|
||||||
server.onNotFound(handleNotFound);
|
server.onNotFound(handleNotFound);
|
||||||
//here the list of headers to be recorded
|
//here the list of headers to be recorded
|
||||||
const char * headerkeys[] = {"User-Agent","Cookie"} ;
|
const char * headerkeys[] = {"User-Agent", "Cookie"} ;
|
||||||
size_t headerkeyssize = sizeof(headerkeys)/sizeof(char*);
|
size_t headerkeyssize = sizeof(headerkeys) / sizeof(char*);
|
||||||
//ask server to track these headers
|
//ask server to track these headers
|
||||||
server.collectHeaders(headerkeys, headerkeyssize );
|
server.collectHeaders(headerkeys, headerkeyssize);
|
||||||
server.begin();
|
server.begin();
|
||||||
Serial.println("HTTP server started");
|
Serial.println("HTTP server started");
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop(void){
|
void loop(void) {
|
||||||
server.handleClient();
|
server.handleClient();
|
||||||
}
|
}
|
||||||
|
@ -14,38 +14,38 @@ const char* password = "........";
|
|||||||
ESP8266WebServer server(80);
|
ESP8266WebServer server(80);
|
||||||
const char* serverIndex = "<form method='POST' action='/update' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";
|
const char* serverIndex = "<form method='POST' action='/update' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";
|
||||||
|
|
||||||
void setup(void){
|
void setup(void) {
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.println("Booting Sketch...");
|
Serial.println("Booting Sketch...");
|
||||||
WiFi.mode(WIFI_AP_STA);
|
WiFi.mode(WIFI_AP_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
if(WiFi.waitForConnectResult() == WL_CONNECTED){
|
if (WiFi.waitForConnectResult() == WL_CONNECTED) {
|
||||||
MDNS.begin(host);
|
MDNS.begin(host);
|
||||||
server.on("/", HTTP_GET, [](){
|
server.on("/", HTTP_GET, []() {
|
||||||
server.sendHeader("Connection", "close");
|
server.sendHeader("Connection", "close");
|
||||||
server.send(200, "text/html", serverIndex);
|
server.send(200, "text/html", serverIndex);
|
||||||
});
|
});
|
||||||
server.on("/update", HTTP_POST, [](){
|
server.on("/update", HTTP_POST, []() {
|
||||||
server.sendHeader("Connection", "close");
|
server.sendHeader("Connection", "close");
|
||||||
server.send(200, "text/plain", (Update.hasError())?"FAIL":"OK");
|
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
|
||||||
ESP.restart();
|
ESP.restart();
|
||||||
},[](){
|
}, []() {
|
||||||
HTTPUpload& upload = server.upload();
|
HTTPUpload& upload = server.upload();
|
||||||
if(upload.status == UPLOAD_FILE_START){
|
if (upload.status == UPLOAD_FILE_START) {
|
||||||
Serial.setDebugOutput(true);
|
Serial.setDebugOutput(true);
|
||||||
WiFiUDP::stopAll();
|
WiFiUDP::stopAll();
|
||||||
Serial.printf("Update: %s\n", upload.filename.c_str());
|
Serial.printf("Update: %s\n", upload.filename.c_str());
|
||||||
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
|
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
|
||||||
if(!Update.begin(maxSketchSpace)){//start with max available size
|
if (!Update.begin(maxSketchSpace)) { //start with max available size
|
||||||
Update.printError(Serial);
|
Update.printError(Serial);
|
||||||
}
|
}
|
||||||
} else if(upload.status == UPLOAD_FILE_WRITE){
|
} else if (upload.status == UPLOAD_FILE_WRITE) {
|
||||||
if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
|
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
|
||||||
Update.printError(Serial);
|
Update.printError(Serial);
|
||||||
}
|
}
|
||||||
} else if(upload.status == UPLOAD_FILE_END){
|
} else if (upload.status == UPLOAD_FILE_END) {
|
||||||
if(Update.end(true)){ //true to set the size to the current progress
|
if (Update.end(true)) { //true to set the size to the current progress
|
||||||
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
|
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
|
||||||
} else {
|
} else {
|
||||||
Update.printError(Serial);
|
Update.printError(Serial);
|
||||||
@ -63,7 +63,7 @@ void setup(void){
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop(void){
|
void loop(void) {
|
||||||
server.handleClient();
|
server.handleClient();
|
||||||
delay(1);
|
delay(1);
|
||||||
}
|
}
|
||||||
|
@ -1,20 +1,20 @@
|
|||||||
/*
|
/*
|
||||||
* HTTP over TLS (HTTPS) example sketch
|
HTTP over TLS (HTTPS) example sketch
|
||||||
*
|
|
||||||
* This example demonstrates how to use
|
This example demonstrates how to use
|
||||||
* WiFiClientSecure class to access HTTPS API.
|
WiFiClientSecure class to access HTTPS API.
|
||||||
* We fetch and display the status of
|
We fetch and display the status of
|
||||||
* esp8266/Arduino project continuous integration
|
esp8266/Arduino project continuous integration
|
||||||
* build.
|
build.
|
||||||
*
|
|
||||||
* Limitations:
|
Limitations:
|
||||||
* only RSA certificates
|
only RSA certificates
|
||||||
* no support of Perfect Forward Secrecy (PFS)
|
no support of Perfect Forward Secrecy (PFS)
|
||||||
* TLSv1.2 is supported since version 2.4.0-rc1
|
TLSv1.2 is supported since version 2.4.0-rc1
|
||||||
*
|
|
||||||
* Created by Ivan Grokhotkov, 2015.
|
Created by Ivan Grokhotkov, 2015.
|
||||||
* This example is in public domain.
|
This example is in public domain.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <WiFiClientSecure.h>
|
#include <WiFiClientSecure.h>
|
||||||
|
@ -1,22 +1,22 @@
|
|||||||
/*
|
/*
|
||||||
|
|
||||||
Udp NTP Client
|
Udp NTP Client
|
||||||
|
|
||||||
Get the time from a Network Time Protocol (NTP) time server
|
Get the time from a Network Time Protocol (NTP) time server
|
||||||
Demonstrates use of UDP sendPacket and ReceivePacket
|
Demonstrates use of UDP sendPacket and ReceivePacket
|
||||||
For more on NTP time servers and the messages needed to communicate with them,
|
For more on NTP time servers and the messages needed to communicate with them,
|
||||||
see http://en.wikipedia.org/wiki/Network_Time_Protocol
|
see http://en.wikipedia.org/wiki/Network_Time_Protocol
|
||||||
|
|
||||||
created 4 Sep 2010
|
created 4 Sep 2010
|
||||||
by Michael Margolis
|
by Michael Margolis
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
updated for the ESP8266 12 Apr 2015
|
updated for the ESP8266 12 Apr 2015
|
||||||
by Ivan Grokhotkov
|
by Ivan Grokhotkov
|
||||||
|
|
||||||
This code is in the public domain.
|
This code is in the public domain.
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <WiFiUdp.h>
|
#include <WiFiUdp.h>
|
||||||
@ -28,7 +28,7 @@ char pass[] = "********"; // your network password
|
|||||||
unsigned int localPort = 2390; // local port to listen for UDP packets
|
unsigned int localPort = 2390; // local port to listen for UDP packets
|
||||||
|
|
||||||
/* Don't hardwire the IP address or we won't get the benefits of the pool.
|
/* Don't hardwire the IP address or we won't get the benefits of the pool.
|
||||||
* Lookup the IP address for the host name instead */
|
Lookup the IP address for the host name instead */
|
||||||
//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
|
//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
|
||||||
IPAddress timeServerIP; // time.nist.gov NTP server address
|
IPAddress timeServerIP; // time.nist.gov NTP server address
|
||||||
const char* ntpServerName = "time.nist.gov";
|
const char* ntpServerName = "time.nist.gov";
|
||||||
@ -40,8 +40,7 @@ byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing pack
|
|||||||
// A UDP instance to let us send and receive packets over UDP
|
// A UDP instance to let us send and receive packets over UDP
|
||||||
WiFiUDP udp;
|
WiFiUDP udp;
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.println();
|
Serial.println();
|
||||||
@ -51,13 +50,13 @@ void setup()
|
|||||||
Serial.println(ssid);
|
Serial.println(ssid);
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(ssid, pass);
|
WiFi.begin(ssid, pass);
|
||||||
|
|
||||||
while (WiFi.status() != WL_CONNECTED) {
|
while (WiFi.status() != WL_CONNECTED) {
|
||||||
delay(500);
|
delay(500);
|
||||||
Serial.print(".");
|
Serial.print(".");
|
||||||
}
|
}
|
||||||
Serial.println("");
|
Serial.println("");
|
||||||
|
|
||||||
Serial.println("WiFi connected");
|
Serial.println("WiFi connected");
|
||||||
Serial.println("IP address: ");
|
Serial.println("IP address: ");
|
||||||
Serial.println(WiFi.localIP());
|
Serial.println(WiFi.localIP());
|
||||||
@ -68,20 +67,18 @@ void setup()
|
|||||||
Serial.println(udp.localPort());
|
Serial.println(udp.localPort());
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
//get a random server from the pool
|
//get a random server from the pool
|
||||||
WiFi.hostByName(ntpServerName, timeServerIP);
|
WiFi.hostByName(ntpServerName, timeServerIP);
|
||||||
|
|
||||||
sendNTPpacket(timeServerIP); // send an NTP packet to a time server
|
sendNTPpacket(timeServerIP); // send an NTP packet to a time server
|
||||||
// wait to see if a reply is available
|
// wait to see if a reply is available
|
||||||
delay(1000);
|
delay(1000);
|
||||||
|
|
||||||
int cb = udp.parsePacket();
|
int cb = udp.parsePacket();
|
||||||
if (!cb) {
|
if (!cb) {
|
||||||
Serial.println("no packet yet");
|
Serial.println("no packet yet");
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
Serial.print("packet received, length=");
|
Serial.print("packet received, length=");
|
||||||
Serial.println(cb);
|
Serial.println(cb);
|
||||||
// We've received a packet, read the data from it
|
// We've received a packet, read the data from it
|
||||||
@ -95,7 +92,7 @@ void loop()
|
|||||||
// combine the four bytes (two words) into a long integer
|
// combine the four bytes (two words) into a long integer
|
||||||
// this is NTP time (seconds since Jan 1 1900):
|
// this is NTP time (seconds since Jan 1 1900):
|
||||||
unsigned long secsSince1900 = highWord << 16 | lowWord;
|
unsigned long secsSince1900 = highWord << 16 | lowWord;
|
||||||
Serial.print("Seconds since Jan 1 1900 = " );
|
Serial.print("Seconds since Jan 1 1900 = ");
|
||||||
Serial.println(secsSince1900);
|
Serial.println(secsSince1900);
|
||||||
|
|
||||||
// now convert NTP time into everyday time:
|
// now convert NTP time into everyday time:
|
||||||
@ -112,13 +109,13 @@ void loop()
|
|||||||
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
|
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
|
||||||
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
|
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
|
||||||
Serial.print(':');
|
Serial.print(':');
|
||||||
if ( ((epoch % 3600) / 60) < 10 ) {
|
if (((epoch % 3600) / 60) < 10) {
|
||||||
// In the first 10 minutes of each hour, we'll want a leading '0'
|
// In the first 10 minutes of each hour, we'll want a leading '0'
|
||||||
Serial.print('0');
|
Serial.print('0');
|
||||||
}
|
}
|
||||||
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
|
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
|
||||||
Serial.print(':');
|
Serial.print(':');
|
||||||
if ( (epoch % 60) < 10 ) {
|
if ((epoch % 60) < 10) {
|
||||||
// In the first 10 seconds of each minute, we'll want a leading '0'
|
// In the first 10 seconds of each minute, we'll want a leading '0'
|
||||||
Serial.print('0');
|
Serial.print('0');
|
||||||
}
|
}
|
||||||
@ -129,8 +126,7 @@ void loop()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// send an NTP request to the time server at the given address
|
// send an NTP request to the time server at the given address
|
||||||
void sendNTPpacket(IPAddress& address)
|
void sendNTPpacket(IPAddress& address) {
|
||||||
{
|
|
||||||
Serial.println("sending NTP packet...");
|
Serial.println("sending NTP packet...");
|
||||||
// set all bytes in the buffer to 0
|
// set all bytes in the buffer to 0
|
||||||
memset(packetBuffer, 0, NTP_PACKET_SIZE);
|
memset(packetBuffer, 0, NTP_PACKET_SIZE);
|
||||||
|
@ -1,37 +1,37 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright (c) 2015, Majenko Technologies
|
Copyright (c) 2015, Majenko Technologies
|
||||||
* All rights reserved.
|
All rights reserved.
|
||||||
*
|
|
||||||
* Redistribution and use in source and binary forms, with or without modification,
|
Redistribution and use in source and binary forms, with or without modification,
|
||||||
* are permitted provided that the following conditions are met:
|
are permitted provided that the following conditions are met:
|
||||||
*
|
|
||||||
* * Redistributions of source code must retain the above copyright notice, this
|
* * Redistributions of source code must retain the above copyright notice, this
|
||||||
* list of conditions and the following disclaimer.
|
list of conditions and the following disclaimer.
|
||||||
*
|
|
||||||
* * Redistributions in binary form must reproduce the above copyright notice, this
|
* * Redistributions in binary form must reproduce the above copyright notice, this
|
||||||
* list of conditions and the following disclaimer in the documentation and/or
|
list of conditions and the following disclaimer in the documentation and/or
|
||||||
* other materials provided with the distribution.
|
other materials provided with the distribution.
|
||||||
*
|
|
||||||
* * Neither the name of Majenko Technologies nor the names of its
|
* * Neither the name of Majenko Technologies nor the names of its
|
||||||
* contributors may be used to endorse or promote products derived from
|
contributors may be used to endorse or promote products derived from
|
||||||
* this software without specific prior written permission.
|
this software without specific prior written permission.
|
||||||
*
|
|
||||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||||
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||||
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||||
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||||
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/* Create a WiFi access point and provide a web server on it. */
|
/* Create a WiFi access point and provide a web server on it. */
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <WiFiClient.h>
|
#include <WiFiClient.h>
|
||||||
#include <ESP8266WebServer.h>
|
#include <ESP8266WebServer.h>
|
||||||
|
|
||||||
/* Set these to your desired credentials. */
|
/* Set these to your desired credentials. */
|
||||||
@ -41,28 +41,28 @@ const char *password = "thereisnospoon";
|
|||||||
ESP8266WebServer server(80);
|
ESP8266WebServer server(80);
|
||||||
|
|
||||||
/* Just a little test message. Go to http://192.168.4.1 in a web browser
|
/* Just a little test message. Go to http://192.168.4.1 in a web browser
|
||||||
* connected to this access point to see it.
|
connected to this access point to see it.
|
||||||
*/
|
*/
|
||||||
void handleRoot() {
|
void handleRoot() {
|
||||||
server.send(200, "text/html", "<h1>You are connected</h1>");
|
server.send(200, "text/html", "<h1>You are connected</h1>");
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
delay(1000);
|
delay(1000);
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.print("Configuring access point...");
|
Serial.print("Configuring access point...");
|
||||||
/* You can remove the password parameter if you want the AP to be open. */
|
/* You can remove the password parameter if you want the AP to be open. */
|
||||||
WiFi.softAP(ssid, password);
|
WiFi.softAP(ssid, password);
|
||||||
|
|
||||||
IPAddress myIP = WiFi.softAPIP();
|
IPAddress myIP = WiFi.softAPIP();
|
||||||
Serial.print("AP IP address: ");
|
Serial.print("AP IP address: ");
|
||||||
Serial.println(myIP);
|
Serial.println(myIP);
|
||||||
server.on("/", handleRoot);
|
server.on("/", handleRoot);
|
||||||
server.begin();
|
server.begin();
|
||||||
Serial.println("HTTP server started");
|
Serial.println("HTTP server started");
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
server.handleClient();
|
server.handleClient();
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
/*
|
/*
|
||||||
* This sketch sends data via HTTP GET requests to data.sparkfun.com service.
|
This sketch sends data via HTTP GET requests to data.sparkfun.com service.
|
||||||
*
|
|
||||||
* You need to get streamId and privateKey at data.sparkfun.com and paste them
|
You need to get streamId and privateKey at data.sparkfun.com and paste them
|
||||||
* below. Or just customize this script to talk to other HTTP servers.
|
below. Or just customize this script to talk to other HTTP servers.
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
|
|
||||||
@ -25,20 +25,20 @@ void setup() {
|
|||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.print("Connecting to ");
|
Serial.print("Connecting to ");
|
||||||
Serial.println(ssid);
|
Serial.println(ssid);
|
||||||
|
|
||||||
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
|
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
|
||||||
would try to act as both a client and an access-point and could cause
|
would try to act as both a client and an access-point and could cause
|
||||||
network-issues with your other WiFi-devices on your WiFi-network. */
|
network-issues with your other WiFi-devices on your WiFi-network. */
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
|
|
||||||
while (WiFi.status() != WL_CONNECTED) {
|
while (WiFi.status() != WL_CONNECTED) {
|
||||||
delay(500);
|
delay(500);
|
||||||
Serial.print(".");
|
Serial.print(".");
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.println("");
|
Serial.println("");
|
||||||
Serial.println("WiFi connected");
|
Serial.println("WiFi connected");
|
||||||
Serial.println("IP address: ");
|
Serial.println("IP address: ");
|
||||||
Serial.println(WiFi.localIP());
|
Serial.println(WiFi.localIP());
|
||||||
}
|
}
|
||||||
@ -51,7 +51,7 @@ void loop() {
|
|||||||
|
|
||||||
Serial.print("connecting to ");
|
Serial.print("connecting to ");
|
||||||
Serial.println(host);
|
Serial.println(host);
|
||||||
|
|
||||||
// Use WiFiClient class to create TCP connections
|
// Use WiFiClient class to create TCP connections
|
||||||
WiFiClient client;
|
WiFiClient client;
|
||||||
const int httpPort = 80;
|
const int httpPort = 80;
|
||||||
@ -59,7 +59,7 @@ void loop() {
|
|||||||
Serial.println("connection failed");
|
Serial.println("connection failed");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// We now create a URI for the request
|
// We now create a URI for the request
|
||||||
String url = "/input/";
|
String url = "/input/";
|
||||||
url += streamId;
|
url += streamId;
|
||||||
@ -67,13 +67,13 @@ void loop() {
|
|||||||
url += privateKey;
|
url += privateKey;
|
||||||
url += "&value=";
|
url += "&value=";
|
||||||
url += value;
|
url += value;
|
||||||
|
|
||||||
Serial.print("Requesting URL: ");
|
Serial.print("Requesting URL: ");
|
||||||
Serial.println(url);
|
Serial.println(url);
|
||||||
|
|
||||||
// This will send the request to the server
|
// This will send the request to the server
|
||||||
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
|
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
|
||||||
"Host: " + host + "\r\n" +
|
"Host: " + host + "\r\n" +
|
||||||
"Connection: close\r\n\r\n");
|
"Connection: close\r\n\r\n");
|
||||||
unsigned long timeout = millis();
|
unsigned long timeout = millis();
|
||||||
while (client.available() == 0) {
|
while (client.available() == 0) {
|
||||||
@ -83,13 +83,13 @@ void loop() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read all the lines of the reply from server and print them to Serial
|
// Read all the lines of the reply from server and print them to Serial
|
||||||
while(client.available()){
|
while (client.available()) {
|
||||||
String line = client.readStringUntil('\r');
|
String line = client.readStringUntil('\r');
|
||||||
Serial.print(line);
|
Serial.print(line);
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.println("closing connection");
|
Serial.println("closing connection");
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
* This sketch sends a message to a TCP server
|
This sketch sends a message to a TCP server
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <ESP8266WiFiMulti.h>
|
#include <ESP8266WiFiMulti.h>
|
||||||
@ -9,61 +9,61 @@
|
|||||||
ESP8266WiFiMulti WiFiMulti;
|
ESP8266WiFiMulti WiFiMulti;
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
delay(10);
|
delay(10);
|
||||||
|
|
||||||
// We start by connecting to a WiFi network
|
// We start by connecting to a WiFi network
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFiMulti.addAP("SSID", "passpasspass");
|
WiFiMulti.addAP("SSID", "passpasspass");
|
||||||
|
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.print("Wait for WiFi... ");
|
Serial.print("Wait for WiFi... ");
|
||||||
|
|
||||||
while(WiFiMulti.run() != WL_CONNECTED) {
|
|
||||||
Serial.print(".");
|
|
||||||
delay(500);
|
|
||||||
}
|
|
||||||
|
|
||||||
Serial.println("");
|
|
||||||
Serial.println("WiFi connected");
|
|
||||||
Serial.println("IP address: ");
|
|
||||||
Serial.println(WiFi.localIP());
|
|
||||||
|
|
||||||
|
while (WiFiMulti.run() != WL_CONNECTED) {
|
||||||
|
Serial.print(".");
|
||||||
delay(500);
|
delay(500);
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.println("");
|
||||||
|
Serial.println("WiFi connected");
|
||||||
|
Serial.println("IP address: ");
|
||||||
|
Serial.println(WiFi.localIP());
|
||||||
|
|
||||||
|
delay(500);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
const uint16_t port = 80;
|
const uint16_t port = 80;
|
||||||
const char * host = "192.168.1.1"; // ip or dns
|
const char * host = "192.168.1.1"; // ip or dns
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Serial.print("connecting to ");
|
|
||||||
Serial.println(host);
|
|
||||||
|
|
||||||
// Use WiFiClient class to create TCP connections
|
|
||||||
WiFiClient client;
|
|
||||||
|
|
||||||
if (!client.connect(host, port)) {
|
Serial.print("connecting to ");
|
||||||
Serial.println("connection failed");
|
Serial.println(host);
|
||||||
Serial.println("wait 5 sec...");
|
|
||||||
delay(5000);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// This will send the request to the server
|
// Use WiFiClient class to create TCP connections
|
||||||
client.println("Send this data to server");
|
WiFiClient client;
|
||||||
|
|
||||||
//read back one line from server
|
if (!client.connect(host, port)) {
|
||||||
String line = client.readStringUntil('\r');
|
Serial.println("connection failed");
|
||||||
Serial.println(line);
|
|
||||||
|
|
||||||
Serial.println("closing connection");
|
|
||||||
client.stop();
|
|
||||||
|
|
||||||
Serial.println("wait 5 sec...");
|
Serial.println("wait 5 sec...");
|
||||||
delay(5000);
|
delay(5000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// This will send the request to the server
|
||||||
|
client.println("Send this data to server");
|
||||||
|
|
||||||
|
//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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,99 +1,99 @@
|
|||||||
/*
|
/*
|
||||||
This sketch shows how to use WiFi event handlers.
|
This sketch shows how to use WiFi event handlers.
|
||||||
|
|
||||||
In this example, ESP8266 works in AP mode.
|
In this example, ESP8266 works in AP mode.
|
||||||
Three event handlers are demonstrated:
|
Three event handlers are demonstrated:
|
||||||
- station connects to the ESP8266 AP
|
- station connects to the ESP8266 AP
|
||||||
- station disconnects from the ESP8266 AP
|
- station disconnects from the ESP8266 AP
|
||||||
- ESP8266 AP receives a probe request from a station
|
- ESP8266 AP receives a probe request from a station
|
||||||
|
|
||||||
Written by Markus Sattler, 2015-12-29.
|
Written by Markus Sattler, 2015-12-29.
|
||||||
Updated for new event handlers by Ivan Grokhotkov, 2017-02-02.
|
Updated for new event handlers by Ivan Grokhotkov, 2017-02-02.
|
||||||
This example is released into public domain,
|
This example is released into public domain,
|
||||||
or, at your option, CC0 licensed.
|
or, at your option, CC0 licensed.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
|
||||||
const char* ssid = "ap-ssid";
|
const char* ssid = "ap-ssid";
|
||||||
const char* password = "ap-password";
|
const char* password = "ap-password";
|
||||||
|
|
||||||
WiFiEventHandler stationConnectedHandler;
|
WiFiEventHandler stationConnectedHandler;
|
||||||
WiFiEventHandler stationDisconnectedHandler;
|
WiFiEventHandler stationDisconnectedHandler;
|
||||||
WiFiEventHandler probeRequestPrintHandler;
|
WiFiEventHandler probeRequestPrintHandler;
|
||||||
WiFiEventHandler probeRequestBlinkHandler;
|
WiFiEventHandler probeRequestBlinkHandler;
|
||||||
|
|
||||||
bool blinkFlag;
|
bool blinkFlag;
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
pinMode(LED_BUILTIN, OUTPUT);
|
pinMode(LED_BUILTIN, OUTPUT);
|
||||||
digitalWrite(LED_BUILTIN, HIGH);
|
digitalWrite(LED_BUILTIN, HIGH);
|
||||||
|
|
||||||
// Don't save WiFi configuration in flash - optional
|
// Don't save WiFi configuration in flash - optional
|
||||||
WiFi.persistent(false);
|
WiFi.persistent(false);
|
||||||
|
|
||||||
// Set up an access point
|
// Set up an access point
|
||||||
WiFi.mode(WIFI_AP);
|
WiFi.mode(WIFI_AP);
|
||||||
WiFi.softAP(ssid, password);
|
WiFi.softAP(ssid, password);
|
||||||
|
|
||||||
// Register event handlers.
|
// Register event handlers.
|
||||||
// Callback functions will be called as long as these handler objects exist.
|
// Callback functions will be called as long as these handler objects exist.
|
||||||
// Call "onStationConnected" each time a station connects
|
// Call "onStationConnected" each time a station connects
|
||||||
stationConnectedHandler = WiFi.onSoftAPModeStationConnected(&onStationConnected);
|
stationConnectedHandler = WiFi.onSoftAPModeStationConnected(&onStationConnected);
|
||||||
// Call "onStationDisconnected" each time a station disconnects
|
// Call "onStationDisconnected" each time a station disconnects
|
||||||
stationDisconnectedHandler = WiFi.onSoftAPModeStationDisconnected(&onStationDisconnected);
|
stationDisconnectedHandler = WiFi.onSoftAPModeStationDisconnected(&onStationDisconnected);
|
||||||
// Call "onProbeRequestPrint" and "onProbeRequestBlink" each time
|
// Call "onProbeRequestPrint" and "onProbeRequestBlink" each time
|
||||||
// a probe request is received.
|
// a probe request is received.
|
||||||
// Former will print MAC address of the station and RSSI to Serial,
|
// Former will print MAC address of the station and RSSI to Serial,
|
||||||
// latter will blink an LED.
|
// latter will blink an LED.
|
||||||
probeRequestPrintHandler = WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestPrint);
|
probeRequestPrintHandler = WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestPrint);
|
||||||
probeRequestBlinkHandler = WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestBlink);
|
probeRequestBlinkHandler = WiFi.onSoftAPModeProbeRequestReceived(&onProbeRequestBlink);
|
||||||
}
|
}
|
||||||
|
|
||||||
void onStationConnected(const WiFiEventSoftAPModeStationConnected& evt) {
|
void onStationConnected(const WiFiEventSoftAPModeStationConnected& evt) {
|
||||||
Serial.print("Station connected: ");
|
Serial.print("Station connected: ");
|
||||||
Serial.println(macToString(evt.mac));
|
Serial.println(macToString(evt.mac));
|
||||||
}
|
}
|
||||||
|
|
||||||
void onStationDisconnected(const WiFiEventSoftAPModeStationDisconnected& evt) {
|
void onStationDisconnected(const WiFiEventSoftAPModeStationDisconnected& evt) {
|
||||||
Serial.print("Station disconnected: ");
|
Serial.print("Station disconnected: ");
|
||||||
Serial.println(macToString(evt.mac));
|
Serial.println(macToString(evt.mac));
|
||||||
}
|
}
|
||||||
|
|
||||||
void onProbeRequestPrint(const WiFiEventSoftAPModeProbeRequestReceived& evt) {
|
void onProbeRequestPrint(const WiFiEventSoftAPModeProbeRequestReceived& evt) {
|
||||||
Serial.print("Probe request from: ");
|
Serial.print("Probe request from: ");
|
||||||
Serial.print(macToString(evt.mac));
|
Serial.print(macToString(evt.mac));
|
||||||
Serial.print(" RSSI: ");
|
Serial.print(" RSSI: ");
|
||||||
Serial.println(evt.rssi);
|
Serial.println(evt.rssi);
|
||||||
}
|
}
|
||||||
|
|
||||||
void onProbeRequestBlink(const WiFiEventSoftAPModeProbeRequestReceived&) {
|
void onProbeRequestBlink(const WiFiEventSoftAPModeProbeRequestReceived&) {
|
||||||
// We can't use "delay" or other blocking functions in the event handler.
|
// We can't use "delay" or other blocking functions in the event handler.
|
||||||
// Therefore we set a flag here and then check it inside "loop" function.
|
// Therefore we set a flag here and then check it inside "loop" function.
|
||||||
blinkFlag = true;
|
blinkFlag = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
if (millis() > 10000 && probeRequestPrintHandler) {
|
if (millis() > 10000 && probeRequestPrintHandler) {
|
||||||
// After 10 seconds, disable the probe request event handler which prints.
|
// After 10 seconds, disable the probe request event handler which prints.
|
||||||
// Other three event handlers remain active.
|
// Other three event handlers remain active.
|
||||||
Serial.println("Not printing probe requests any more (LED should still blink)");
|
Serial.println("Not printing probe requests any more (LED should still blink)");
|
||||||
probeRequestPrintHandler = WiFiEventHandler();
|
probeRequestPrintHandler = WiFiEventHandler();
|
||||||
}
|
}
|
||||||
if (blinkFlag) {
|
if (blinkFlag) {
|
||||||
blinkFlag = false;
|
blinkFlag = false;
|
||||||
digitalWrite(LED_BUILTIN, LOW);
|
digitalWrite(LED_BUILTIN, LOW);
|
||||||
delay(100);
|
delay(100);
|
||||||
digitalWrite(LED_BUILTIN, HIGH);
|
digitalWrite(LED_BUILTIN, HIGH);
|
||||||
}
|
}
|
||||||
delay(10);
|
delay(10);
|
||||||
}
|
}
|
||||||
|
|
||||||
String macToString(const unsigned char* mac) {
|
String macToString(const unsigned char* mac) {
|
||||||
char buf[20];
|
char buf[20];
|
||||||
snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
|
snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x",
|
||||||
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||||
return String(buf);
|
return String(buf);
|
||||||
}
|
}
|
||||||
|
@ -46,7 +46,7 @@
|
|||||||
const char* ssid = "your-ssid";
|
const char* ssid = "your-ssid";
|
||||||
const char* password = "your-password";
|
const char* password = "your-password";
|
||||||
|
|
||||||
// The certificate is stored in PMEM
|
// The certificate is stored in PMEM
|
||||||
static const uint8_t x509[] PROGMEM = {
|
static const uint8_t x509[] PROGMEM = {
|
||||||
0x30, 0x82, 0x01, 0x3d, 0x30, 0x81, 0xe8, 0x02, 0x09, 0x00, 0xfe, 0x56,
|
0x30, 0x82, 0x01, 0x3d, 0x30, 0x81, 0xe8, 0x02, 0x09, 0x00, 0xfe, 0x56,
|
||||||
0x46, 0xf2, 0x78, 0xc6, 0x51, 0x17, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86,
|
0x46, 0xf2, 0x78, 0xc6, 0x51, 0x17, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86,
|
||||||
@ -107,7 +107,7 @@ static const uint8_t rsakey[] PROGMEM = {
|
|||||||
0x2c, 0x3a, 0xcd, 0x0a, 0x9a, 0x4d, 0x7c, 0xad, 0x29, 0xd6, 0x36, 0x57,
|
0x2c, 0x3a, 0xcd, 0x0a, 0x9a, 0x4d, 0x7c, 0xad, 0x29, 0xd6, 0x36, 0x57,
|
||||||
0xd5, 0xdf, 0x34, 0xeb, 0x26, 0x03
|
0xd5, 0xdf, 0x34, 0xeb, 0x26, 0x03
|
||||||
};
|
};
|
||||||
|
|
||||||
// Create an instance of the server
|
// Create an instance of the server
|
||||||
// specify the port to listen on as an argument
|
// specify the port to listen on as an argument
|
||||||
WiFiServerSecure server(443);
|
WiFiServerSecure server(443);
|
||||||
@ -119,15 +119,15 @@ void setup() {
|
|||||||
// prepare GPIO2
|
// prepare GPIO2
|
||||||
pinMode(2, OUTPUT);
|
pinMode(2, OUTPUT);
|
||||||
digitalWrite(2, 0);
|
digitalWrite(2, 0);
|
||||||
|
|
||||||
// Connect to WiFi network
|
// Connect to WiFi network
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.print("Connecting to ");
|
Serial.print("Connecting to ");
|
||||||
Serial.println(ssid);
|
Serial.println(ssid);
|
||||||
|
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
|
|
||||||
while (WiFi.status() != WL_CONNECTED) {
|
while (WiFi.status() != WL_CONNECTED) {
|
||||||
delay(500);
|
delay(500);
|
||||||
Serial.print(".");
|
Serial.print(".");
|
||||||
@ -135,7 +135,7 @@ void setup() {
|
|||||||
Serial.println("");
|
Serial.println("");
|
||||||
Serial.println("WiFi connected");
|
Serial.println("WiFi connected");
|
||||||
|
|
||||||
// Set the certificates from PMEM (if using DRAM remove the _P from the call)
|
// Set the certificates from PMEM (if using DRAM remove the _P from the call)
|
||||||
server.setServerKeyAndCert_P(rsakey, sizeof(rsakey), x509, sizeof(x509));
|
server.setServerKeyAndCert_P(rsakey, sizeof(rsakey), x509, sizeof(x509));
|
||||||
|
|
||||||
// Start the server
|
// Start the server
|
||||||
@ -152,11 +152,11 @@ void loop() {
|
|||||||
if (!client) {
|
if (!client) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait until the client sends some data
|
// Wait until the client sends some data
|
||||||
Serial.println("new client");
|
Serial.println("new client");
|
||||||
unsigned long timeout = millis() + 3000;
|
unsigned long timeout = millis() + 3000;
|
||||||
while(!client.available() && millis() < timeout){
|
while (!client.available() && millis() < timeout) {
|
||||||
delay(1);
|
delay(1);
|
||||||
}
|
}
|
||||||
if (millis() > timeout) {
|
if (millis() > timeout) {
|
||||||
@ -170,14 +170,14 @@ void loop() {
|
|||||||
String req = client.readStringUntil('\r');
|
String req = client.readStringUntil('\r');
|
||||||
Serial.println(req);
|
Serial.println(req);
|
||||||
client.flush();
|
client.flush();
|
||||||
|
|
||||||
// Match the request
|
// Match the request
|
||||||
int val;
|
int val;
|
||||||
if (req.indexOf("/gpio/0") != -1)
|
if (req.indexOf("/gpio/0") != -1) {
|
||||||
val = 0;
|
val = 0;
|
||||||
else if (req.indexOf("/gpio/1") != -1)
|
} else if (req.indexOf("/gpio/1") != -1) {
|
||||||
val = 1;
|
val = 1;
|
||||||
else {
|
} else {
|
||||||
Serial.println("invalid request");
|
Serial.println("invalid request");
|
||||||
client.print("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html><body>Not found</body></html>");
|
client.print("HTTP/1.1 404 Not Found\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html><body>Not found</body></html>");
|
||||||
return;
|
return;
|
||||||
@ -185,12 +185,12 @@ void loop() {
|
|||||||
|
|
||||||
// Set GPIO2 according to the request
|
// Set GPIO2 according to the request
|
||||||
digitalWrite(2, val);
|
digitalWrite(2, val);
|
||||||
|
|
||||||
client.flush();
|
client.flush();
|
||||||
|
|
||||||
// Prepare the response
|
// Prepare the response
|
||||||
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
|
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
|
||||||
s += (val)?"high":"low";
|
s += (val) ? "high" : "low";
|
||||||
s += "</html>\n";
|
s += "</html>\n";
|
||||||
|
|
||||||
// Send the response to the client
|
// Send the response to the client
|
||||||
@ -198,7 +198,7 @@ void loop() {
|
|||||||
delay(1);
|
delay(1);
|
||||||
Serial.println("Client disconnected");
|
Serial.println("Client disconnected");
|
||||||
|
|
||||||
// The client will actually be disconnected
|
// The client will actually be disconnected
|
||||||
// when the function returns and 'client' object is detroyed
|
// when the function returns and 'client' object is detroyed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
/*
|
/*
|
||||||
* This sketch trys to Connect to the best AP based on a given list
|
This sketch trys to Connect to the best AP based on a given list
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <ESP8266WiFiMulti.h>
|
#include <ESP8266WiFiMulti.h>
|
||||||
@ -9,26 +9,26 @@
|
|||||||
ESP8266WiFiMulti wifiMulti;
|
ESP8266WiFiMulti wifiMulti;
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
delay(10);
|
delay(10);
|
||||||
|
|
||||||
WiFi.mode(WIFI_STA);
|
|
||||||
wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
|
|
||||||
wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
|
|
||||||
wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");
|
|
||||||
|
|
||||||
Serial.println("Connecting Wifi...");
|
WiFi.mode(WIFI_STA);
|
||||||
if(wifiMulti.run() == WL_CONNECTED) {
|
wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
|
||||||
Serial.println("");
|
wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
|
||||||
Serial.println("WiFi connected");
|
wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");
|
||||||
Serial.println("IP address: ");
|
|
||||||
Serial.println(WiFi.localIP());
|
Serial.println("Connecting Wifi...");
|
||||||
}
|
if (wifiMulti.run() == WL_CONNECTED) {
|
||||||
|
Serial.println("");
|
||||||
|
Serial.println("WiFi connected");
|
||||||
|
Serial.println("IP address: ");
|
||||||
|
Serial.println(WiFi.localIP());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
if(wifiMulti.run() != WL_CONNECTED) {
|
if (wifiMulti.run() != WL_CONNECTED) {
|
||||||
Serial.println("WiFi not connected!");
|
Serial.println("WiFi not connected!");
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
/*
|
/*
|
||||||
* This sketch demonstrates how to scan WiFi networks.
|
This sketch demonstrates how to scan WiFi networks.
|
||||||
* The API is almost the same as with the WiFi Shield library,
|
The API is almost the same as with the WiFi Shield library,
|
||||||
* the most obvious difference being the different file you need to include:
|
the most obvious difference being the different file you need to include:
|
||||||
*/
|
*/
|
||||||
#include "ESP8266WiFi.h"
|
#include "ESP8266WiFi.h"
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
@ -22,14 +22,12 @@ void loop() {
|
|||||||
// WiFi.scanNetworks will return the number of networks found
|
// WiFi.scanNetworks will return the number of networks found
|
||||||
int n = WiFi.scanNetworks();
|
int n = WiFi.scanNetworks();
|
||||||
Serial.println("scan done");
|
Serial.println("scan done");
|
||||||
if (n == 0)
|
if (n == 0) {
|
||||||
Serial.println("no networks found");
|
Serial.println("no networks found");
|
||||||
else
|
} else {
|
||||||
{
|
|
||||||
Serial.print(n);
|
Serial.print(n);
|
||||||
Serial.println(" networks found");
|
Serial.println(" networks found");
|
||||||
for (int i = 0; i < n; ++i)
|
for (int i = 0; i < n; ++i) {
|
||||||
{
|
|
||||||
// Print SSID and RSSI for each network found
|
// Print SSID and RSSI for each network found
|
||||||
Serial.print(i + 1);
|
Serial.print(i + 1);
|
||||||
Serial.print(": ");
|
Serial.print(": ");
|
||||||
@ -37,7 +35,7 @@ void loop() {
|
|||||||
Serial.print(" (");
|
Serial.print(" (");
|
||||||
Serial.print(WiFi.RSSI(i));
|
Serial.print(WiFi.RSSI(i));
|
||||||
Serial.print(")");
|
Serial.print(")");
|
||||||
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
|
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
|
||||||
delay(10);
|
delay(10);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
/*
|
/*
|
||||||
WiFiTelnetToSerial - Example Transparent UART to Telnet Server for esp8266
|
WiFiTelnetToSerial - Example Transparent UART to Telnet Server for esp8266
|
||||||
|
|
||||||
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
|
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
|
||||||
This file is part of the ESP8266WiFi library for Arduino environment.
|
This file is part of the ESP8266WiFi library for Arduino environment.
|
||||||
|
|
||||||
This library is free software; you can redistribute it and/or
|
This library is free software; you can redistribute it and/or
|
||||||
modify it under the terms of the GNU Lesser General Public
|
modify it under the terms of the GNU Lesser General Public
|
||||||
License as published by the Free Software Foundation; either
|
License as published by the Free Software Foundation; either
|
||||||
@ -34,16 +34,20 @@ void setup() {
|
|||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
Serial1.print("\nConnecting to "); Serial1.println(ssid);
|
Serial1.print("\nConnecting to "); Serial1.println(ssid);
|
||||||
uint8_t i = 0;
|
uint8_t i = 0;
|
||||||
while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
|
while (WiFi.status() != WL_CONNECTED && i++ < 20) {
|
||||||
if(i == 21){
|
delay(500);
|
||||||
|
}
|
||||||
|
if (i == 21) {
|
||||||
Serial1.print("Could not connect to"); Serial1.println(ssid);
|
Serial1.print("Could not connect to"); Serial1.println(ssid);
|
||||||
while(1) delay(500);
|
while (1) {
|
||||||
|
delay(500);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
//start UART and the server
|
//start UART and the server
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
server.begin();
|
server.begin();
|
||||||
server.setNoDelay(true);
|
server.setNoDelay(true);
|
||||||
|
|
||||||
Serial1.print("Ready! Use 'telnet ");
|
Serial1.print("Ready! Use 'telnet ");
|
||||||
Serial1.print(WiFi.localIP());
|
Serial1.print(WiFi.localIP());
|
||||||
Serial1.println(" 23' to connect");
|
Serial1.println(" 23' to connect");
|
||||||
@ -52,40 +56,44 @@ void setup() {
|
|||||||
void loop() {
|
void loop() {
|
||||||
uint8_t i;
|
uint8_t i;
|
||||||
//check if there are any new clients
|
//check if there are any new clients
|
||||||
if (server.hasClient()){
|
if (server.hasClient()) {
|
||||||
for(i = 0; i < MAX_SRV_CLIENTS; i++){
|
for (i = 0; i < MAX_SRV_CLIENTS; i++) {
|
||||||
//find free/disconnected spot
|
//find free/disconnected spot
|
||||||
if (!serverClients[i] || !serverClients[i].connected()){
|
if (!serverClients[i] || !serverClients[i].connected()) {
|
||||||
if(serverClients[i]) serverClients[i].stop();
|
if (serverClients[i]) {
|
||||||
|
serverClients[i].stop();
|
||||||
|
}
|
||||||
serverClients[i] = server.available();
|
serverClients[i] = server.available();
|
||||||
Serial1.print("New client: "); Serial1.print(i);
|
Serial1.print("New client: "); Serial1.print(i);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//no free/disconnected spot so reject
|
//no free/disconnected spot so reject
|
||||||
if ( i == MAX_SRV_CLIENTS) {
|
if (i == MAX_SRV_CLIENTS) {
|
||||||
WiFiClient serverClient = server.available();
|
WiFiClient serverClient = server.available();
|
||||||
serverClient.stop();
|
serverClient.stop();
|
||||||
Serial1.println("Connection rejected ");
|
Serial1.println("Connection rejected ");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//check clients for data
|
//check clients for data
|
||||||
for(i = 0; i < MAX_SRV_CLIENTS; i++){
|
for (i = 0; i < MAX_SRV_CLIENTS; i++) {
|
||||||
if (serverClients[i] && serverClients[i].connected()){
|
if (serverClients[i] && serverClients[i].connected()) {
|
||||||
if(serverClients[i].available()){
|
if (serverClients[i].available()) {
|
||||||
//get data from the telnet client and push it to the UART
|
//get data from the telnet client and push it to the UART
|
||||||
while(serverClients[i].available()) Serial.write(serverClients[i].read());
|
while (serverClients[i].available()) {
|
||||||
|
Serial.write(serverClients[i].read());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//check UART for data
|
//check UART for data
|
||||||
if(Serial.available()){
|
if (Serial.available()) {
|
||||||
size_t len = Serial.available();
|
size_t len = Serial.available();
|
||||||
uint8_t sbuf[len];
|
uint8_t sbuf[len];
|
||||||
Serial.readBytes(sbuf, len);
|
Serial.readBytes(sbuf, len);
|
||||||
//push UART data to all connected telnet clients
|
//push UART data to all connected telnet clients
|
||||||
for(i = 0; i < MAX_SRV_CLIENTS; i++){
|
for (i = 0; i < MAX_SRV_CLIENTS; i++) {
|
||||||
if (serverClients[i] && serverClients[i].connected()){
|
if (serverClients[i] && serverClients[i].connected()) {
|
||||||
serverClients[i].write(sbuf, len);
|
serverClients[i].write(sbuf, len);
|
||||||
delay(1);
|
delay(1);
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
/*
|
/*
|
||||||
* This sketch demonstrates how to set up a simple HTTP-like server.
|
This sketch demonstrates how to set up a simple HTTP-like server.
|
||||||
* The server will set a GPIO pin depending on the request
|
The server will set a GPIO pin depending on the request
|
||||||
* http://server_ip/gpio/0 will set the GPIO2 low,
|
http://server_ip/gpio/0 will set the GPIO2 low,
|
||||||
* http://server_ip/gpio/1 will set the GPIO2 high
|
http://server_ip/gpio/1 will set the GPIO2 high
|
||||||
* server_ip is the IP address of the ESP8266 module, will be
|
server_ip is the IP address of the ESP8266 module, will be
|
||||||
* printed to Serial when the module is connected.
|
printed to Serial when the module is connected.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
|
|
||||||
@ -23,23 +23,23 @@ void setup() {
|
|||||||
// prepare GPIO2
|
// prepare GPIO2
|
||||||
pinMode(2, OUTPUT);
|
pinMode(2, OUTPUT);
|
||||||
digitalWrite(2, 0);
|
digitalWrite(2, 0);
|
||||||
|
|
||||||
// Connect to WiFi network
|
// Connect to WiFi network
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.print("Connecting to ");
|
Serial.print("Connecting to ");
|
||||||
Serial.println(ssid);
|
Serial.println(ssid);
|
||||||
|
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
|
|
||||||
while (WiFi.status() != WL_CONNECTED) {
|
while (WiFi.status() != WL_CONNECTED) {
|
||||||
delay(500);
|
delay(500);
|
||||||
Serial.print(".");
|
Serial.print(".");
|
||||||
}
|
}
|
||||||
Serial.println("");
|
Serial.println("");
|
||||||
Serial.println("WiFi connected");
|
Serial.println("WiFi connected");
|
||||||
|
|
||||||
// Start the server
|
// Start the server
|
||||||
server.begin();
|
server.begin();
|
||||||
Serial.println("Server started");
|
Serial.println("Server started");
|
||||||
@ -54,25 +54,25 @@ void loop() {
|
|||||||
if (!client) {
|
if (!client) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait until the client sends some data
|
// Wait until the client sends some data
|
||||||
Serial.println("new client");
|
Serial.println("new client");
|
||||||
while(!client.available()){
|
while (!client.available()) {
|
||||||
delay(1);
|
delay(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the first line of the request
|
// Read the first line of the request
|
||||||
String req = client.readStringUntil('\r');
|
String req = client.readStringUntil('\r');
|
||||||
Serial.println(req);
|
Serial.println(req);
|
||||||
client.flush();
|
client.flush();
|
||||||
|
|
||||||
// Match the request
|
// Match the request
|
||||||
int val;
|
int val;
|
||||||
if (req.indexOf("/gpio/0") != -1)
|
if (req.indexOf("/gpio/0") != -1) {
|
||||||
val = 0;
|
val = 0;
|
||||||
else if (req.indexOf("/gpio/1") != -1)
|
} else if (req.indexOf("/gpio/1") != -1) {
|
||||||
val = 1;
|
val = 1;
|
||||||
else {
|
} else {
|
||||||
Serial.println("invalid request");
|
Serial.println("invalid request");
|
||||||
client.stop();
|
client.stop();
|
||||||
return;
|
return;
|
||||||
@ -80,12 +80,12 @@ void loop() {
|
|||||||
|
|
||||||
// Set GPIO2 according to the request
|
// Set GPIO2 according to the request
|
||||||
digitalWrite(2, val);
|
digitalWrite(2, val);
|
||||||
|
|
||||||
client.flush();
|
client.flush();
|
||||||
|
|
||||||
// Prepare the response
|
// Prepare the response
|
||||||
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
|
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
|
||||||
s += (val)?"high":"low";
|
s += (val) ? "high" : "low";
|
||||||
s += "</html>\n";
|
s += "</html>\n";
|
||||||
|
|
||||||
// Send the response to the client
|
// Send the response to the client
|
||||||
@ -93,7 +93,7 @@ void loop() {
|
|||||||
delay(1);
|
delay(1);
|
||||||
Serial.println("Client disonnected");
|
Serial.println("Client disonnected");
|
||||||
|
|
||||||
// The client will actually be disconnected
|
// The client will actually be disconnected
|
||||||
// when the function returns and 'client' object is detroyed
|
// when the function returns and 'client' object is detroyed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -10,44 +10,41 @@ String manageRequest(String request);
|
|||||||
ESP8266WiFiMesh mesh_node = ESP8266WiFiMesh(ESP.getChipId(), manageRequest);
|
ESP8266WiFiMesh mesh_node = ESP8266WiFiMesh(ESP.getChipId(), manageRequest);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Callback for when other nodes send you data
|
Callback for when other nodes send you data
|
||||||
*
|
|
||||||
* @request The string received from another node in the mesh
|
|
||||||
* @returns The string to send back to the other node
|
|
||||||
*/
|
|
||||||
String manageRequest(String request)
|
|
||||||
{
|
|
||||||
/* Print out received message */
|
|
||||||
Serial.print("received: ");
|
|
||||||
Serial.println(request);
|
|
||||||
|
|
||||||
/* return a string to send back */
|
@request The string received from another node in the mesh
|
||||||
char response[60];
|
@returns The string to send back to the other node
|
||||||
sprintf(response, "Hello world response #%d from Mesh_Node%d.", response_i++, ESP.getChipId());
|
*/
|
||||||
return response;
|
String manageRequest(String request) {
|
||||||
|
/* Print out received message */
|
||||||
|
Serial.print("received: ");
|
||||||
|
Serial.println(request);
|
||||||
|
|
||||||
|
/* return a string to send back */
|
||||||
|
char response[60];
|
||||||
|
sprintf(response, "Hello world response #%d from Mesh_Node%d.", response_i++, ESP.getChipId());
|
||||||
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
Serial.begin(115200);
|
||||||
Serial.begin(115200);
|
delay(10);
|
||||||
delay(10);
|
|
||||||
|
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.println();
|
Serial.println();
|
||||||
Serial.println("Setting up mesh node...");
|
Serial.println("Setting up mesh node...");
|
||||||
|
|
||||||
/* Initialise the mesh node */
|
/* Initialise the mesh node */
|
||||||
mesh_node.begin();
|
mesh_node.begin();
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
/* Accept any incoming connections */
|
||||||
/* Accept any incoming connections */
|
mesh_node.acceptRequest();
|
||||||
mesh_node.acceptRequest();
|
|
||||||
|
|
||||||
/* Scan for other nodes and send them a message */
|
/* Scan for other nodes and send them a message */
|
||||||
char request[60];
|
char request[60];
|
||||||
sprintf(request, "Hello world request #%d from Mesh_Node%d.", request_i++, ESP.getChipId());
|
sprintf(request, "Hello world request #%d from Mesh_Node%d.", request_i++, ESP.getChipId());
|
||||||
mesh_node.attemptScan(request);
|
mesh_node.attemptScan(request);
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
|
@ -1,62 +1,62 @@
|
|||||||
/**
|
/**
|
||||||
* httpUpdate.ino
|
httpUpdate.ino
|
||||||
*
|
|
||||||
* Created on: 27.11.2015
|
Created on: 27.11.2015
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <ESP8266WiFiMulti.h>
|
#include <ESP8266WiFiMulti.h>
|
||||||
|
|
||||||
#include <ESP8266HTTPClient.h>
|
#include <ESP8266HTTPClient.h>
|
||||||
#include <ESP8266httpUpdate.h>
|
#include <ESP8266httpUpdate.h>
|
||||||
|
|
||||||
#define USE_SERIAL Serial
|
#define USE_SERIAL Serial
|
||||||
|
|
||||||
ESP8266WiFiMulti WiFiMulti;
|
ESP8266WiFiMulti WiFiMulti;
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
|
|
||||||
USE_SERIAL.begin(115200);
|
USE_SERIAL.begin(115200);
|
||||||
// USE_SERIAL.setDebugOutput(true);
|
// USE_SERIAL.setDebugOutput(true);
|
||||||
|
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
|
|
||||||
for(uint8_t t = 4; t > 0; t--) {
|
for (uint8_t t = 4; t > 0; t--) {
|
||||||
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
||||||
USE_SERIAL.flush();
|
USE_SERIAL.flush();
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFiMulti.addAP("SSID", "PASSWORD");
|
WiFiMulti.addAP("SSID", "PASSWORD");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
// wait for WiFi connection
|
// wait for WiFi connection
|
||||||
if((WiFiMulti.run() == WL_CONNECTED)) {
|
if ((WiFiMulti.run() == WL_CONNECTED)) {
|
||||||
|
|
||||||
t_httpUpdate_return ret = ESPhttpUpdate.update("http://server/file.bin");
|
t_httpUpdate_return ret = ESPhttpUpdate.update("http://server/file.bin");
|
||||||
//t_httpUpdate_return ret = ESPhttpUpdate.update("https://server/file.bin");
|
//t_httpUpdate_return ret = ESPhttpUpdate.update("https://server/file.bin");
|
||||||
|
|
||||||
switch(ret) {
|
switch (ret) {
|
||||||
case HTTP_UPDATE_FAILED:
|
case HTTP_UPDATE_FAILED:
|
||||||
USE_SERIAL.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
USE_SERIAL.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case HTTP_UPDATE_NO_UPDATES:
|
case HTTP_UPDATE_NO_UPDATES:
|
||||||
USE_SERIAL.println("HTTP_UPDATE_NO_UPDATES");
|
USE_SERIAL.println("HTTP_UPDATE_NO_UPDATES");
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case HTTP_UPDATE_OK:
|
case HTTP_UPDATE_OK:
|
||||||
USE_SERIAL.println("HTTP_UPDATE_OK");
|
USE_SERIAL.println("HTTP_UPDATE_OK");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,66 +1,66 @@
|
|||||||
/**
|
/**
|
||||||
* httpUpdateSPIFFS.ino
|
httpUpdateSPIFFS.ino
|
||||||
*
|
|
||||||
* Created on: 05.12.2015
|
Created on: 05.12.2015
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <ESP8266WiFiMulti.h>
|
#include <ESP8266WiFiMulti.h>
|
||||||
|
|
||||||
#include <ESP8266HTTPClient.h>
|
#include <ESP8266HTTPClient.h>
|
||||||
#include <ESP8266httpUpdate.h>
|
#include <ESP8266httpUpdate.h>
|
||||||
|
|
||||||
#define USE_SERIAL Serial
|
#define USE_SERIAL Serial
|
||||||
|
|
||||||
ESP8266WiFiMulti WiFiMulti;
|
ESP8266WiFiMulti WiFiMulti;
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
|
|
||||||
USE_SERIAL.begin(115200);
|
USE_SERIAL.begin(115200);
|
||||||
// USE_SERIAL.setDebugOutput(true);
|
// USE_SERIAL.setDebugOutput(true);
|
||||||
|
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
USE_SERIAL.println();
|
USE_SERIAL.println();
|
||||||
|
|
||||||
for(uint8_t t = 4; t > 0; t--) {
|
for (uint8_t t = 4; t > 0; t--) {
|
||||||
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
|
||||||
USE_SERIAL.flush();
|
USE_SERIAL.flush();
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFiMulti.addAP("SSID", "PASSWORD");
|
WiFiMulti.addAP("SSID", "PASSWORD");
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
// wait for WiFi connection
|
// wait for WiFi connection
|
||||||
if((WiFiMulti.run() == WL_CONNECTED)) {
|
if ((WiFiMulti.run() == WL_CONNECTED)) {
|
||||||
|
|
||||||
USE_SERIAL.println("Update SPIFFS...");
|
USE_SERIAL.println("Update SPIFFS...");
|
||||||
t_httpUpdate_return ret = ESPhttpUpdate.updateSpiffs("http://server/spiffs.bin");
|
t_httpUpdate_return ret = ESPhttpUpdate.updateSpiffs("http://server/spiffs.bin");
|
||||||
if(ret == HTTP_UPDATE_OK) {
|
if (ret == HTTP_UPDATE_OK) {
|
||||||
USE_SERIAL.println("Update sketch...");
|
USE_SERIAL.println("Update sketch...");
|
||||||
ret = ESPhttpUpdate.update("http://server/file.bin");
|
ret = ESPhttpUpdate.update("http://server/file.bin");
|
||||||
|
|
||||||
switch(ret) {
|
switch (ret) {
|
||||||
case HTTP_UPDATE_FAILED:
|
case HTTP_UPDATE_FAILED:
|
||||||
USE_SERIAL.printf("HTTP_UPDATE_FAILED Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
USE_SERIAL.printf("HTTP_UPDATE_FAILED Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case HTTP_UPDATE_NO_UPDATES:
|
case HTTP_UPDATE_NO_UPDATES:
|
||||||
USE_SERIAL.println("HTTP_UPDATE_NO_UPDATES");
|
USE_SERIAL.println("HTTP_UPDATE_NO_UPDATES");
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case HTTP_UPDATE_OK:
|
case HTTP_UPDATE_OK:
|
||||||
USE_SERIAL.println("HTTP_UPDATE_OK");
|
USE_SERIAL.println("HTTP_UPDATE_OK");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,16 +1,16 @@
|
|||||||
/**
|
/**
|
||||||
* @file OTA-mDNS-SPIFFS.ino
|
@file OTA-mDNS-SPIFFS.ino
|
||||||
*
|
|
||||||
* @author Pascal Gollor (http://www.pgollor.de/cms/)
|
@author Pascal Gollor (http://www.pgollor.de/cms/)
|
||||||
* @date 2015-09-18
|
@date 2015-09-18
|
||||||
*
|
|
||||||
* changelog:
|
changelog:
|
||||||
* 2015-10-22:
|
2015-10-22:
|
||||||
* - Use new ArduinoOTA library.
|
- Use new ArduinoOTA library.
|
||||||
* - loadConfig function can handle different line endings
|
- loadConfig function can handle different line endings
|
||||||
* - remove mDNS studd. ArduinoOTA handle it.
|
- remove mDNS studd. ArduinoOTA handle it.
|
||||||
*
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// includes
|
// includes
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
@ -21,16 +21,16 @@
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief mDNS and OTA Constants
|
@brief mDNS and OTA Constants
|
||||||
* @{
|
@{
|
||||||
*/
|
*/
|
||||||
#define HOSTNAME "ESP8266-OTA-" ///< Hostename. The setup function adds the Chip ID at the end.
|
#define HOSTNAME "ESP8266-OTA-" ///< Hostename. The setup function adds the Chip ID at the end.
|
||||||
/// @}
|
/// @}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Default WiFi connection information.
|
@brief Default WiFi connection information.
|
||||||
* @{
|
@{
|
||||||
*/
|
*/
|
||||||
const char* ap_default_ssid = "esp8266"; ///< Default SSID.
|
const char* ap_default_ssid = "esp8266"; ///< Default SSID.
|
||||||
const char* ap_default_psk = "esp8266esp8266"; ///< Default PSK.
|
const char* ap_default_psk = "esp8266esp8266"; ///< Default PSK.
|
||||||
/// @}
|
/// @}
|
||||||
@ -39,21 +39,19 @@ const char* ap_default_psk = "esp8266esp8266"; ///< Default PSK.
|
|||||||
//#define SERIAL_VERBOSE
|
//#define SERIAL_VERBOSE
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Read WiFi connection information from file system.
|
@brief Read WiFi connection information from file system.
|
||||||
* @param ssid String pointer for storing SSID.
|
@param ssid String pointer for storing SSID.
|
||||||
* @param pass String pointer for storing PSK.
|
@param pass String pointer for storing PSK.
|
||||||
* @return True or False.
|
@return True or False.
|
||||||
*
|
|
||||||
* The config file have to containt the WiFi SSID in the first line
|
The config file have to containt the WiFi SSID in the first line
|
||||||
* and the WiFi PSK in the second line.
|
and the WiFi PSK in the second line.
|
||||||
* Line seperator can be \r\n (CR LF) \r or \n.
|
Line seperator can be \r\n (CR LF) \r or \n.
|
||||||
*/
|
*/
|
||||||
bool loadConfig(String *ssid, String *pass)
|
bool loadConfig(String *ssid, String *pass) {
|
||||||
{
|
|
||||||
// open file for reading.
|
// open file for reading.
|
||||||
File configFile = SPIFFS.open("/cl_conf.txt", "r");
|
File configFile = SPIFFS.open("/cl_conf.txt", "r");
|
||||||
if (!configFile)
|
if (!configFile) {
|
||||||
{
|
|
||||||
Serial.println("Failed to open cl_conf.txt.");
|
Serial.println("Failed to open cl_conf.txt.");
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
@ -62,26 +60,23 @@ bool loadConfig(String *ssid, String *pass)
|
|||||||
// Read content from config file.
|
// Read content from config file.
|
||||||
String content = configFile.readString();
|
String content = configFile.readString();
|
||||||
configFile.close();
|
configFile.close();
|
||||||
|
|
||||||
content.trim();
|
content.trim();
|
||||||
|
|
||||||
// Check if ther is a second line available.
|
// Check if ther is a second line available.
|
||||||
int8_t pos = content.indexOf("\r\n");
|
int8_t pos = content.indexOf("\r\n");
|
||||||
uint8_t le = 2;
|
uint8_t le = 2;
|
||||||
// check for linux and mac line ending.
|
// check for linux and mac line ending.
|
||||||
if (pos == -1)
|
if (pos == -1) {
|
||||||
{
|
|
||||||
le = 1;
|
le = 1;
|
||||||
pos = content.indexOf("\n");
|
pos = content.indexOf("\n");
|
||||||
if (pos == -1)
|
if (pos == -1) {
|
||||||
{
|
|
||||||
pos = content.indexOf("\r");
|
pos = content.indexOf("\r");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If there is no second line: Some information is missing.
|
// If there is no second line: Some information is missing.
|
||||||
if (pos == -1)
|
if (pos == -1) {
|
||||||
{
|
|
||||||
Serial.println("Infvalid content.");
|
Serial.println("Infvalid content.");
|
||||||
Serial.println(content);
|
Serial.println(content);
|
||||||
|
|
||||||
@ -95,30 +90,28 @@ bool loadConfig(String *ssid, String *pass)
|
|||||||
ssid->trim();
|
ssid->trim();
|
||||||
pass->trim();
|
pass->trim();
|
||||||
|
|
||||||
#ifdef SERIAL_VERBOSE
|
#ifdef SERIAL_VERBOSE
|
||||||
Serial.println("----- file content -----");
|
Serial.println("----- file content -----");
|
||||||
Serial.println(content);
|
Serial.println(content);
|
||||||
Serial.println("----- file content -----");
|
Serial.println("----- file content -----");
|
||||||
Serial.println("ssid: " + *ssid);
|
Serial.println("ssid: " + *ssid);
|
||||||
Serial.println("psk: " + *pass);
|
Serial.println("psk: " + *pass);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} // loadConfig
|
} // loadConfig
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Save WiFi SSID and PSK to configuration file.
|
@brief Save WiFi SSID and PSK to configuration file.
|
||||||
* @param ssid SSID as string pointer.
|
@param ssid SSID as string pointer.
|
||||||
* @param pass PSK as string pointer,
|
@param pass PSK as string pointer,
|
||||||
* @return True or False.
|
@return True or False.
|
||||||
*/
|
*/
|
||||||
bool saveConfig(String *ssid, String *pass)
|
bool saveConfig(String *ssid, String *pass) {
|
||||||
{
|
|
||||||
// Open config file for writing.
|
// Open config file for writing.
|
||||||
File configFile = SPIFFS.open("/cl_conf.txt", "w");
|
File configFile = SPIFFS.open("/cl_conf.txt", "w");
|
||||||
if (!configFile)
|
if (!configFile) {
|
||||||
{
|
|
||||||
Serial.println("Failed to open cl_conf.txt for writing");
|
Serial.println("Failed to open cl_conf.txt for writing");
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
@ -129,21 +122,20 @@ bool saveConfig(String *ssid, String *pass)
|
|||||||
configFile.println(*pass);
|
configFile.println(*pass);
|
||||||
|
|
||||||
configFile.close();
|
configFile.close();
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} // saveConfig
|
} // saveConfig
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Arduino setup function.
|
@brief Arduino setup function.
|
||||||
*/
|
*/
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
String station_ssid = "";
|
String station_ssid = "";
|
||||||
String station_psk = "";
|
String station_psk = "";
|
||||||
|
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
|
|
||||||
delay(100);
|
delay(100);
|
||||||
|
|
||||||
Serial.println("\r\n");
|
Serial.println("\r\n");
|
||||||
@ -161,15 +153,13 @@ void setup()
|
|||||||
|
|
||||||
|
|
||||||
// Initialize file system.
|
// Initialize file system.
|
||||||
if (!SPIFFS.begin())
|
if (!SPIFFS.begin()) {
|
||||||
{
|
|
||||||
Serial.println("Failed to mount file system");
|
Serial.println("Failed to mount file system");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load wifi connection information.
|
// Load wifi connection information.
|
||||||
if (! loadConfig(&station_ssid, &station_psk))
|
if (! loadConfig(&station_ssid, &station_psk)) {
|
||||||
{
|
|
||||||
station_ssid = "";
|
station_ssid = "";
|
||||||
station_psk = "";
|
station_psk = "";
|
||||||
|
|
||||||
@ -178,15 +168,13 @@ void setup()
|
|||||||
|
|
||||||
// Check WiFi connection
|
// Check WiFi connection
|
||||||
// ... check mode
|
// ... check mode
|
||||||
if (WiFi.getMode() != WIFI_STA)
|
if (WiFi.getMode() != WIFI_STA) {
|
||||||
{
|
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
delay(10);
|
delay(10);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ... Compare file config with sdk config.
|
// ... Compare file config with sdk config.
|
||||||
if (WiFi.SSID() != station_ssid || WiFi.psk() != station_psk)
|
if (WiFi.SSID() != station_ssid || WiFi.psk() != station_psk) {
|
||||||
{
|
|
||||||
Serial.println("WiFi config changed.");
|
Serial.println("WiFi config changed.");
|
||||||
|
|
||||||
// ... Try to connect to WiFi station.
|
// ... Try to connect to WiFi station.
|
||||||
@ -198,9 +186,7 @@ void setup()
|
|||||||
|
|
||||||
// ... Uncomment this for debugging output.
|
// ... Uncomment this for debugging output.
|
||||||
//WiFi.printDiag(Serial);
|
//WiFi.printDiag(Serial);
|
||||||
}
|
} else {
|
||||||
else
|
|
||||||
{
|
|
||||||
// ... Begin with sdk config.
|
// ... Begin with sdk config.
|
||||||
WiFi.begin();
|
WiFi.begin();
|
||||||
}
|
}
|
||||||
@ -209,8 +195,7 @@ void setup()
|
|||||||
|
|
||||||
// ... Give ESP 10 seconds to connect to station.
|
// ... Give ESP 10 seconds to connect to station.
|
||||||
unsigned long startTime = millis();
|
unsigned long startTime = millis();
|
||||||
while (WiFi.status() != WL_CONNECTED && millis() - startTime < 10000)
|
while (WiFi.status() != WL_CONNECTED && millis() - startTime < 10000) {
|
||||||
{
|
|
||||||
Serial.write('.');
|
Serial.write('.');
|
||||||
//Serial.print(WiFi.status());
|
//Serial.print(WiFi.status());
|
||||||
delay(500);
|
delay(500);
|
||||||
@ -218,16 +203,13 @@ void setup()
|
|||||||
Serial.println();
|
Serial.println();
|
||||||
|
|
||||||
// Check connection
|
// Check connection
|
||||||
if(WiFi.status() == WL_CONNECTED)
|
if (WiFi.status() == WL_CONNECTED) {
|
||||||
{
|
|
||||||
// ... print IP Address
|
// ... print IP Address
|
||||||
Serial.print("IP address: ");
|
Serial.print("IP address: ");
|
||||||
Serial.println(WiFi.localIP());
|
Serial.println(WiFi.localIP());
|
||||||
}
|
} else {
|
||||||
else
|
|
||||||
{
|
|
||||||
Serial.println("Can not connect to WiFi station. Go into AP mode.");
|
Serial.println("Can not connect to WiFi station. Go into AP mode.");
|
||||||
|
|
||||||
// Go into software AP mode.
|
// Go into software AP mode.
|
||||||
WiFi.mode(WIFI_AP);
|
WiFi.mode(WIFI_AP);
|
||||||
|
|
||||||
@ -246,10 +228,9 @@ void setup()
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @brief Arduino loop function.
|
@brief Arduino loop function.
|
||||||
*/
|
*/
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
// Handle OTA server.
|
// Handle OTA server.
|
||||||
ArduinoOTA.handle();
|
ArduinoOTA.handle();
|
||||||
yield();
|
yield();
|
||||||
|
@ -2,12 +2,12 @@
|
|||||||
ESP8266 mDNS-SD responder and query sample
|
ESP8266 mDNS-SD responder and query sample
|
||||||
|
|
||||||
This is an example of announcing and finding services.
|
This is an example of announcing and finding services.
|
||||||
|
|
||||||
Instructions:
|
Instructions:
|
||||||
- Update WiFi SSID and password as necessary.
|
- Update WiFi SSID and password as necessary.
|
||||||
- Flash the sketch to two ESP8266 boards
|
- Flash the sketch to two ESP8266 boards
|
||||||
- The last one powered on should now find the other.
|
- The last one powered on should now find the other.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
#include <ESP8266mDNS.h>
|
#include <ESP8266mDNS.h>
|
||||||
@ -38,7 +38,7 @@ void setup() {
|
|||||||
Serial.print("IP address: ");
|
Serial.print("IP address: ");
|
||||||
Serial.println(WiFi.localIP());
|
Serial.println(WiFi.localIP());
|
||||||
|
|
||||||
if (!MDNS.begin(hostString)) {
|
if (!MDNS.begin(hostString)) {
|
||||||
Serial.println("Error setting up MDNS responder!");
|
Serial.println("Error setting up MDNS responder!");
|
||||||
}
|
}
|
||||||
Serial.println("mDNS responder started");
|
Serial.println("mDNS responder started");
|
||||||
@ -49,8 +49,7 @@ void setup() {
|
|||||||
Serial.println("mDNS query done");
|
Serial.println("mDNS query done");
|
||||||
if (n == 0) {
|
if (n == 0) {
|
||||||
Serial.println("no services found");
|
Serial.println("no services found");
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
Serial.print(n);
|
Serial.print(n);
|
||||||
Serial.println(" service(s) found");
|
Serial.println(" service(s) found");
|
||||||
for (int i = 0; i < n; ++i) {
|
for (int i = 0; i < n; ++i) {
|
||||||
@ -66,7 +65,7 @@ void setup() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Serial.println();
|
Serial.println();
|
||||||
|
|
||||||
Serial.println("loop() next");
|
Serial.println("loop() next");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -13,7 +13,7 @@
|
|||||||
- For Mac OSX and iOS support is built in through Bonjour already.
|
- For Mac OSX and iOS support is built in through Bonjour already.
|
||||||
- Point your browser to http://esp8266.local, you should see a response.
|
- Point your browser to http://esp8266.local, you should see a response.
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
#include <ESP8266WiFi.h>
|
#include <ESP8266WiFi.h>
|
||||||
@ -26,15 +26,14 @@ const char* password = "..............";
|
|||||||
// TCP server at port 80 will respond to HTTP requests
|
// TCP server at port 80 will respond to HTTP requests
|
||||||
WiFiServer server(80);
|
WiFiServer server(80);
|
||||||
|
|
||||||
void setup(void)
|
void setup(void) {
|
||||||
{
|
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
|
|
||||||
// Connect to WiFi network
|
// Connect to WiFi network
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(ssid, password);
|
WiFi.begin(ssid, password);
|
||||||
Serial.println("");
|
Serial.println("");
|
||||||
|
|
||||||
// Wait for connection
|
// Wait for connection
|
||||||
while (WiFi.status() != WL_CONNECTED) {
|
while (WiFi.status() != WL_CONNECTED) {
|
||||||
delay(500);
|
delay(500);
|
||||||
@ -53,22 +52,21 @@ void setup(void)
|
|||||||
// we send our IP address on the WiFi network
|
// we send our IP address on the WiFi network
|
||||||
if (!MDNS.begin("esp8266")) {
|
if (!MDNS.begin("esp8266")) {
|
||||||
Serial.println("Error setting up MDNS responder!");
|
Serial.println("Error setting up MDNS responder!");
|
||||||
while(1) {
|
while (1) {
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Serial.println("mDNS responder started");
|
Serial.println("mDNS responder started");
|
||||||
|
|
||||||
// Start TCP (HTTP) server
|
// Start TCP (HTTP) server
|
||||||
server.begin();
|
server.begin();
|
||||||
Serial.println("TCP server started");
|
Serial.println("TCP server started");
|
||||||
|
|
||||||
// Add service to MDNS-SD
|
// Add service to MDNS-SD
|
||||||
MDNS.addService("http", "tcp", 80);
|
MDNS.addService("http", "tcp", 80);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop(void)
|
void loop(void) {
|
||||||
{
|
|
||||||
// Check if a client has connected
|
// Check if a client has connected
|
||||||
WiFiClient client = server.available();
|
WiFiClient client = server.available();
|
||||||
if (!client) {
|
if (!client) {
|
||||||
@ -78,13 +76,13 @@ void loop(void)
|
|||||||
Serial.println("New client");
|
Serial.println("New client");
|
||||||
|
|
||||||
// Wait for data from client to become available
|
// Wait for data from client to become available
|
||||||
while(client.connected() && !client.available()){
|
while (client.connected() && !client.available()) {
|
||||||
delay(1);
|
delay(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the first line of HTTP request
|
// Read the first line of HTTP request
|
||||||
String req = client.readStringUntil('\r');
|
String req = client.readStringUntil('\r');
|
||||||
|
|
||||||
// First line of HTTP request looks like "GET /path HTTP/1.1"
|
// First line of HTTP request looks like "GET /path HTTP/1.1"
|
||||||
// Retrieve the "/path" part by finding the spaces
|
// Retrieve the "/path" part by finding the spaces
|
||||||
int addr_start = req.indexOf(' ');
|
int addr_start = req.indexOf(' ');
|
||||||
@ -98,24 +96,21 @@ void loop(void)
|
|||||||
Serial.print("Request: ");
|
Serial.print("Request: ");
|
||||||
Serial.println(req);
|
Serial.println(req);
|
||||||
client.flush();
|
client.flush();
|
||||||
|
|
||||||
String s;
|
String s;
|
||||||
if (req == "/")
|
if (req == "/") {
|
||||||
{
|
|
||||||
IPAddress ip = WiFi.localIP();
|
IPAddress ip = WiFi.localIP();
|
||||||
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
|
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
|
||||||
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from ESP8266 at ";
|
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from ESP8266 at ";
|
||||||
s += ipStr;
|
s += ipStr;
|
||||||
s += "</html>\r\n\r\n";
|
s += "</html>\r\n\r\n";
|
||||||
Serial.println("Sending 200");
|
Serial.println("Sending 200");
|
||||||
}
|
} else {
|
||||||
else
|
|
||||||
{
|
|
||||||
s = "HTTP/1.1 404 Not Found\r\n\r\n";
|
s = "HTTP/1.1 404 Not Found\r\n\r\n";
|
||||||
Serial.println("Sending 404");
|
Serial.println("Sending 404");
|
||||||
}
|
}
|
||||||
client.print(s);
|
client.print(s);
|
||||||
|
|
||||||
Serial.println("Done with client");
|
Serial.println("Done with client");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,24 +1,24 @@
|
|||||||
/*
|
/*
|
||||||
Advanced Chat Server
|
Advanced Chat Server
|
||||||
|
|
||||||
A more advanced server that distributes any incoming messages
|
A more advanced server that distributes any incoming messages
|
||||||
to all connected clients but the client the message comes from.
|
to all connected clients but the client the message comes from.
|
||||||
To use telnet to your device's IP address and type.
|
To use telnet to your device's IP address and type.
|
||||||
You can see the client's input in the serial monitor as well.
|
You can see the client's input in the serial monitor as well.
|
||||||
Using an Arduino Wiznet Ethernet shield.
|
Using an Arduino Wiznet Ethernet shield.
|
||||||
|
|
||||||
Circuit:
|
Circuit:
|
||||||
* Ethernet shield attached to pins 10, 11, 12, 13
|
Ethernet shield attached to pins 10, 11, 12, 13
|
||||||
* Analog inputs attached to pins A0 through A5 (optional)
|
Analog inputs attached to pins A0 through A5 (optional)
|
||||||
|
|
||||||
created 18 Dec 2009
|
created 18 Dec 2009
|
||||||
by David A. Mellis
|
by David A. Mellis
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
redesigned to make use of operator== 25 Nov 2013
|
redesigned to make use of operator== 25 Nov 2013
|
||||||
by Norbert Truchsess
|
by Norbert Truchsess
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <Ethernet.h>
|
#include <Ethernet.h>
|
||||||
@ -26,10 +26,11 @@
|
|||||||
// Enter a MAC address and IP address for your controller below.
|
// Enter a MAC address and IP address for your controller below.
|
||||||
// The IP address will be dependent on your local network.
|
// The IP address will be dependent on your local network.
|
||||||
// gateway and subnet are optional:
|
// gateway and subnet are optional:
|
||||||
byte mac[] = {
|
byte mac[] = {
|
||||||
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
|
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
|
||||||
IPAddress ip(192,168,1, 177);
|
};
|
||||||
IPAddress gateway(192,168,1, 1);
|
IPAddress ip(192, 168, 1, 177);
|
||||||
|
IPAddress gateway(192, 168, 1, 1);
|
||||||
IPAddress subnet(255, 255, 0, 0);
|
IPAddress subnet(255, 255, 0, 0);
|
||||||
|
|
||||||
|
|
||||||
@ -43,9 +44,9 @@ void setup() {
|
|||||||
Ethernet.begin(mac, ip, gateway, subnet);
|
Ethernet.begin(mac, ip, gateway, subnet);
|
||||||
// start listening for clients
|
// start listening for clients
|
||||||
server.begin();
|
server.begin();
|
||||||
// Open serial communications and wait for port to open:
|
// Open serial communications and wait for port to open:
|
||||||
Serial.begin(9600);
|
Serial.begin(9600);
|
||||||
while (!Serial) {
|
while (!Serial) {
|
||||||
; // wait for serial port to connect. Needed for Leonardo only
|
; // wait for serial port to connect. Needed for Leonardo only
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -62,9 +63,9 @@ void loop() {
|
|||||||
if (client) {
|
if (client) {
|
||||||
|
|
||||||
boolean newClient = true;
|
boolean newClient = true;
|
||||||
for (byte i=0;i<4;i++) {
|
for (byte i = 0; i < 4; i++) {
|
||||||
//check whether this client refers to the same socket as one of the existing instances:
|
//check whether this client refers to the same socket as one of the existing instances:
|
||||||
if (clients[i]==client) {
|
if (clients[i] == client) {
|
||||||
newClient = false;
|
newClient = false;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@ -72,8 +73,8 @@ void loop() {
|
|||||||
|
|
||||||
if (newClient) {
|
if (newClient) {
|
||||||
//check which of the existing clients can be overridden:
|
//check which of the existing clients can be overridden:
|
||||||
for (byte i=0;i<4;i++) {
|
for (byte i = 0; i < 4; i++) {
|
||||||
if (!clients[i] && clients[i]!=client) {
|
if (!clients[i] && clients[i] != client) {
|
||||||
clients[i] = client;
|
clients[i] = client;
|
||||||
// clead out the input buffer:
|
// clead out the input buffer:
|
||||||
client.flush();
|
client.flush();
|
||||||
@ -90,8 +91,8 @@ void loop() {
|
|||||||
// read the bytes incoming from the client:
|
// read the bytes incoming from the client:
|
||||||
char thisChar = client.read();
|
char thisChar = client.read();
|
||||||
// echo the bytes back to all other connected clients:
|
// echo the bytes back to all other connected clients:
|
||||||
for (byte i=0;i<4;i++) {
|
for (byte i = 0; i < 4; i++) {
|
||||||
if (clients[i] && (clients[i]!=client)) {
|
if (clients[i] && (clients[i] != client)) {
|
||||||
clients[i].write(thisChar);
|
clients[i].write(thisChar);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -99,7 +100,7 @@ void loop() {
|
|||||||
Serial.write(thisChar);
|
Serial.write(thisChar);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (byte i=0;i<4;i++) {
|
for (byte i = 0; i < 4; i++) {
|
||||||
if (!(clients[i].connected())) {
|
if (!(clients[i].connected())) {
|
||||||
// client.stop() invalidates the internal socket-descriptor, so next use of == will allways return false;
|
// client.stop() invalidates the internal socket-descriptor, so next use of == will allways return false;
|
||||||
clients[i].stop();
|
clients[i].stop();
|
||||||
|
@ -1,25 +1,25 @@
|
|||||||
/*
|
/*
|
||||||
SCP1000 Barometric Pressure Sensor Display
|
SCP1000 Barometric Pressure Sensor Display
|
||||||
|
|
||||||
Serves the output of a Barometric Pressure Sensor as a web page.
|
Serves the output of a Barometric Pressure Sensor as a web page.
|
||||||
Uses the SPI library. For details on the sensor, see:
|
Uses the SPI library. For details on the sensor, see:
|
||||||
http://www.sparkfun.com/commerce/product_info.php?products_id=8161
|
http://www.sparkfun.com/commerce/product_info.php?products_id=8161
|
||||||
http://www.vti.fi/en/support/obsolete_products/pressure_sensors/
|
http://www.vti.fi/en/support/obsolete_products/pressure_sensors/
|
||||||
|
|
||||||
This sketch adapted from Nathan Seidle's SCP1000 example for PIC:
|
This sketch adapted from Nathan Seidle's SCP1000 example for PIC:
|
||||||
http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip
|
http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip
|
||||||
|
|
||||||
Circuit:
|
Circuit:
|
||||||
SCP1000 sensor attached to pins 6,7, and 11 - 13:
|
SCP1000 sensor attached to pins 6,7, and 11 - 13:
|
||||||
DRDY: pin 6
|
DRDY: pin 6
|
||||||
CSB: pin 7
|
CSB: pin 7
|
||||||
MOSI: pin 11
|
MOSI: pin 11
|
||||||
MISO: pin 12
|
MISO: pin 12
|
||||||
SCK: pin 13
|
SCK: pin 13
|
||||||
|
|
||||||
created 31 July 2010
|
created 31 July 2010
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <Ethernet.h>
|
#include <Ethernet.h>
|
||||||
// the sensor communicates using SPI, so include the library:
|
// the sensor communicates using SPI, so include the library:
|
||||||
@ -156,8 +156,7 @@ void listenForEthernetClients() {
|
|||||||
if (c == '\n') {
|
if (c == '\n') {
|
||||||
// you're starting a new line
|
// you're starting a new line
|
||||||
currentLineIsBlank = true;
|
currentLineIsBlank = true;
|
||||||
}
|
} else if (c != '\r') {
|
||||||
else if (c != '\r') {
|
|
||||||
// you've gotten a character on the current line
|
// you've gotten a character on the current line
|
||||||
currentLineIsBlank = false;
|
currentLineIsBlank = false;
|
||||||
}
|
}
|
||||||
@ -219,5 +218,5 @@ unsigned int readRegister(byte registerName, int numBytes) {
|
|||||||
// take the chip select high to de-select:
|
// take the chip select high to de-select:
|
||||||
digitalWrite(chipSelectPin, HIGH);
|
digitalWrite(chipSelectPin, HIGH);
|
||||||
// return the result:
|
// return the result:
|
||||||
return(result);
|
return (result);
|
||||||
}
|
}
|
||||||
|
@ -1,21 +1,21 @@
|
|||||||
/*
|
/*
|
||||||
Chat Server
|
Chat Server
|
||||||
|
|
||||||
A simple server that distributes any incoming messages to all
|
A simple server that distributes any incoming messages to all
|
||||||
connected clients. To use telnet to your device's IP address and type.
|
connected clients. To use telnet to your device's IP address and type.
|
||||||
You can see the client's input in the serial monitor as well.
|
You can see the client's input in the serial monitor as well.
|
||||||
Using an Arduino Wiznet Ethernet shield.
|
Using an Arduino Wiznet Ethernet shield.
|
||||||
|
|
||||||
Circuit:
|
Circuit:
|
||||||
* Ethernet shield attached to pins 10, 11, 12, 13
|
Ethernet shield attached to pins 10, 11, 12, 13
|
||||||
* Analog inputs attached to pins A0 through A5 (optional)
|
Analog inputs attached to pins A0 through A5 (optional)
|
||||||
|
|
||||||
created 18 Dec 2009
|
created 18 Dec 2009
|
||||||
by David A. Mellis
|
by David A. Mellis
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <Ethernet.h>
|
#include <Ethernet.h>
|
||||||
|
@ -1,18 +1,18 @@
|
|||||||
/*
|
/*
|
||||||
DHCP-based IP printer
|
DHCP-based IP printer
|
||||||
|
|
||||||
This sketch uses the DHCP extensions to the Ethernet library
|
This sketch uses the DHCP extensions to the Ethernet library
|
||||||
to get an IP address via DHCP and print the address obtained.
|
to get an IP address via DHCP and print the address obtained.
|
||||||
using an Arduino Wiznet Ethernet shield.
|
using an Arduino Wiznet Ethernet shield.
|
||||||
|
|
||||||
Circuit:
|
Circuit:
|
||||||
* Ethernet shield attached to pins 10, 11, 12, 13
|
Ethernet shield attached to pins 10, 11, 12, 13
|
||||||
|
|
||||||
created 12 April 2011
|
created 12 April 2011
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <Ethernet.h>
|
#include <Ethernet.h>
|
||||||
|
@ -1,22 +1,22 @@
|
|||||||
/*
|
/*
|
||||||
DHCP Chat Server
|
DHCP Chat Server
|
||||||
|
|
||||||
A simple server that distributes any incoming messages to all
|
A simple server that distributes any incoming messages to all
|
||||||
connected clients. To use telnet to your device's IP address and type.
|
connected clients. To use telnet to your device's IP address and type.
|
||||||
You can see the client's input in the serial monitor as well.
|
You can see the client's input in the serial monitor as well.
|
||||||
Using an Arduino Wiznet Ethernet shield.
|
Using an Arduino Wiznet Ethernet shield.
|
||||||
|
|
||||||
THis version attempts to get an IP address using DHCP
|
THis version attempts to get an IP address using DHCP
|
||||||
|
|
||||||
Circuit:
|
Circuit:
|
||||||
* Ethernet shield attached to pins 10, 11, 12, 13
|
Ethernet shield attached to pins 10, 11, 12, 13
|
||||||
|
|
||||||
created 21 May 2011
|
created 21 May 2011
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
Based on ChatServer example by David A. Mellis
|
Based on ChatServer example by David A. Mellis
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <Ethernet.h>
|
#include <Ethernet.h>
|
||||||
|
@ -1,22 +1,22 @@
|
|||||||
/*
|
/*
|
||||||
Telnet client
|
Telnet client
|
||||||
|
|
||||||
This sketch connects to a a telnet server (http://www.google.com)
|
This sketch connects to a a telnet server (http://www.google.com)
|
||||||
using an Arduino Wiznet Ethernet shield. You'll need a telnet server
|
using an Arduino Wiznet Ethernet shield. You'll need a telnet server
|
||||||
to test this with.
|
to test this with.
|
||||||
Processing's ChatServer example (part of the network library) works well,
|
Processing's ChatServer example (part of the network library) works well,
|
||||||
running on port 10002. It can be found as part of the examples
|
running on port 10002. It can be found as part of the examples
|
||||||
in the Processing application, available at
|
in the Processing application, available at
|
||||||
http://processing.org/
|
http://processing.org/
|
||||||
|
|
||||||
Circuit:
|
Circuit:
|
||||||
* Ethernet shield attached to pins 10, 11, 12, 13
|
Ethernet shield attached to pins 10, 11, 12, 13
|
||||||
|
|
||||||
created 14 Sep 2010
|
created 14 Sep 2010
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <Ethernet.h>
|
#include <Ethernet.h>
|
||||||
@ -54,15 +54,13 @@ void setup() {
|
|||||||
// if you get a connection, report back via serial:
|
// if you get a connection, report back via serial:
|
||||||
if (client.connect(server, 10002)) {
|
if (client.connect(server, 10002)) {
|
||||||
Serial.println("connected");
|
Serial.println("connected");
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
// if you didn't get a connection to the server:
|
// if you didn't get a connection to the server:
|
||||||
Serial.println("connection failed");
|
Serial.println("connection failed");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
// if there are incoming bytes available
|
// if there are incoming bytes available
|
||||||
// from the server, read them and print them:
|
// from the server, read them and print them:
|
||||||
if (client.available()) {
|
if (client.available()) {
|
||||||
|
@ -1,16 +1,16 @@
|
|||||||
/*
|
/*
|
||||||
UDPSendReceive.pde:
|
UDPSendReceive.pde:
|
||||||
This sketch receives UDP message strings, prints them to the serial port
|
This sketch receives UDP message strings, prints them to the serial port
|
||||||
and sends an "acknowledge" string back to the sender
|
and sends an "acknowledge" string back to the sender
|
||||||
|
|
||||||
A Processing sketch is included at the end of file that can be used to send
|
A Processing sketch is included at the end of file that can be used to send
|
||||||
and received messages for testing with a computer.
|
and received messages for testing with a computer.
|
||||||
|
|
||||||
created 21 Aug 2010
|
created 21 Aug 2010
|
||||||
by Michael Margolis
|
by Michael Margolis
|
||||||
|
|
||||||
This code is in the public domain.
|
This code is in the public domain.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
#include <SPI.h> // needed for Arduino versions later than 0018
|
#include <SPI.h> // needed for Arduino versions later than 0018
|
||||||
@ -45,17 +45,14 @@ void setup() {
|
|||||||
void loop() {
|
void loop() {
|
||||||
// if there's data available, read a packet
|
// if there's data available, read a packet
|
||||||
int packetSize = Udp.parsePacket();
|
int packetSize = Udp.parsePacket();
|
||||||
if (packetSize)
|
if (packetSize) {
|
||||||
{
|
|
||||||
Serial.print("Received packet of size ");
|
Serial.print("Received packet of size ");
|
||||||
Serial.println(packetSize);
|
Serial.println(packetSize);
|
||||||
Serial.print("From ");
|
Serial.print("From ");
|
||||||
IPAddress remote = Udp.remoteIP();
|
IPAddress remote = Udp.remoteIP();
|
||||||
for (int i = 0; i < 4; i++)
|
for (int i = 0; i < 4; i++) {
|
||||||
{
|
|
||||||
Serial.print(remote[i], DEC);
|
Serial.print(remote[i], DEC);
|
||||||
if (i < 3)
|
if (i < 3) {
|
||||||
{
|
|
||||||
Serial.print(".");
|
Serial.print(".");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -78,42 +75,42 @@ void loop() {
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
Processing sketch to run with this example
|
Processing sketch to run with this example
|
||||||
=====================================================
|
=====================================================
|
||||||
|
|
||||||
// Processing UDP example to send and receive string data from Arduino
|
// Processing UDP example to send and receive string data from Arduino
|
||||||
// press any key to send the "Hello Arduino" message
|
// press any key to send the "Hello Arduino" message
|
||||||
|
|
||||||
|
|
||||||
import hypermedia.net.*;
|
import hypermedia.net.*;
|
||||||
|
|
||||||
UDP udp; // define the UDP object
|
UDP udp; // define the UDP object
|
||||||
|
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
udp = new UDP( this, 6000 ); // create a new datagram connection on port 6000
|
udp = new UDP( this, 6000 ); // create a new datagram connection on port 6000
|
||||||
//udp.log( true ); // <-- printout the connection activity
|
//udp.log( true ); // <-- printout the connection activity
|
||||||
udp.listen( true ); // and wait for incoming message
|
udp.listen( true ); // and wait for incoming message
|
||||||
}
|
}
|
||||||
|
|
||||||
void draw()
|
void draw()
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
void keyPressed() {
|
void keyPressed() {
|
||||||
String ip = "192.168.1.177"; // the remote IP address
|
String ip = "192.168.1.177"; // the remote IP address
|
||||||
int port = 8888; // the destination port
|
int port = 8888; // the destination port
|
||||||
|
|
||||||
udp.send("Hello World", ip, port ); // the message to send
|
udp.send("Hello World", ip, port ); // the message to send
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void receive( byte[] data ) { // <-- default handler
|
void receive( byte[] data ) { // <-- default handler
|
||||||
//void receive( byte[] data, String ip, int port ) { // <-- extended handler
|
//void receive( byte[] data, String ip, int port ) { // <-- extended handler
|
||||||
|
|
||||||
for(int i=0; i < data.length; i++)
|
for(int i=0; i < data.length; i++)
|
||||||
print(char(data[i]));
|
print(char(data[i]));
|
||||||
println();
|
println();
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,20 +1,20 @@
|
|||||||
/*
|
/*
|
||||||
|
|
||||||
Udp NTP Client
|
Udp NTP Client
|
||||||
|
|
||||||
Get the time from a Network Time Protocol (NTP) time server
|
Get the time from a Network Time Protocol (NTP) time server
|
||||||
Demonstrates use of UDP sendPacket and ReceivePacket
|
Demonstrates use of UDP sendPacket and ReceivePacket
|
||||||
For more on NTP time servers and the messages needed to communicate with them,
|
For more on NTP time servers and the messages needed to communicate with them,
|
||||||
see http://en.wikipedia.org/wiki/Network_Time_Protocol
|
see http://en.wikipedia.org/wiki/Network_Time_Protocol
|
||||||
|
|
||||||
created 4 Sep 2010
|
created 4 Sep 2010
|
||||||
by Michael Margolis
|
by Michael Margolis
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
|
|
||||||
This code is in the public domain.
|
This code is in the public domain.
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <Ethernet.h>
|
#include <Ethernet.h>
|
||||||
@ -37,8 +37,7 @@ byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing pack
|
|||||||
// A UDP instance to let us send and receive packets over UDP
|
// A UDP instance to let us send and receive packets over UDP
|
||||||
EthernetUDP Udp;
|
EthernetUDP Udp;
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
// Open serial communications and wait for port to open:
|
// Open serial communications and wait for port to open:
|
||||||
Serial.begin(9600);
|
Serial.begin(9600);
|
||||||
while (!Serial) {
|
while (!Serial) {
|
||||||
@ -56,13 +55,12 @@ void setup()
|
|||||||
Udp.begin(localPort);
|
Udp.begin(localPort);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
sendNTPpacket(timeServer); // send an NTP packet to a time server
|
sendNTPpacket(timeServer); // send an NTP packet to a time server
|
||||||
|
|
||||||
// wait to see if a reply is available
|
// wait to see if a reply is available
|
||||||
delay(1000);
|
delay(1000);
|
||||||
if ( Udp.parsePacket() ) {
|
if (Udp.parsePacket()) {
|
||||||
// We've received a packet, read the data from it
|
// We've received a packet, read the data from it
|
||||||
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
|
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
|
||||||
|
|
||||||
@ -74,7 +72,7 @@ void loop()
|
|||||||
// combine the four bytes (two words) into a long integer
|
// combine the four bytes (two words) into a long integer
|
||||||
// this is NTP time (seconds since Jan 1 1900):
|
// this is NTP time (seconds since Jan 1 1900):
|
||||||
unsigned long secsSince1900 = highWord << 16 | lowWord;
|
unsigned long secsSince1900 = highWord << 16 | lowWord;
|
||||||
Serial.print("Seconds since Jan 1 1900 = " );
|
Serial.print("Seconds since Jan 1 1900 = ");
|
||||||
Serial.println(secsSince1900);
|
Serial.println(secsSince1900);
|
||||||
|
|
||||||
// now convert NTP time into everyday time:
|
// now convert NTP time into everyday time:
|
||||||
@ -91,13 +89,13 @@ void loop()
|
|||||||
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
|
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
|
||||||
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
|
Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day)
|
||||||
Serial.print(':');
|
Serial.print(':');
|
||||||
if ( ((epoch % 3600) / 60) < 10 ) {
|
if (((epoch % 3600) / 60) < 10) {
|
||||||
// In the first 10 minutes of each hour, we'll want a leading '0'
|
// In the first 10 minutes of each hour, we'll want a leading '0'
|
||||||
Serial.print('0');
|
Serial.print('0');
|
||||||
}
|
}
|
||||||
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
|
Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute)
|
||||||
Serial.print(':');
|
Serial.print(':');
|
||||||
if ( (epoch % 60) < 10 ) {
|
if ((epoch % 60) < 10) {
|
||||||
// In the first 10 seconds of each minute, we'll want a leading '0'
|
// In the first 10 seconds of each minute, we'll want a leading '0'
|
||||||
Serial.print('0');
|
Serial.print('0');
|
||||||
}
|
}
|
||||||
@ -108,8 +106,7 @@ void loop()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// send an NTP request to the time server at the given address
|
// send an NTP request to the time server at the given address
|
||||||
void sendNTPpacket(char* address)
|
void sendNTPpacket(char* address) {
|
||||||
{
|
|
||||||
// set all bytes in the buffer to 0
|
// set all bytes in the buffer to 0
|
||||||
memset(packetBuffer, 0, NTP_PACKET_SIZE);
|
memset(packetBuffer, 0, NTP_PACKET_SIZE);
|
||||||
// Initialize values needed to form NTP request
|
// Initialize values needed to form NTP request
|
||||||
|
@ -1,18 +1,18 @@
|
|||||||
/*
|
/*
|
||||||
Web client
|
Web client
|
||||||
|
|
||||||
This sketch connects to a website (http://www.google.com)
|
This sketch connects to a website (http://www.google.com)
|
||||||
using an Arduino Wiznet Ethernet shield.
|
using an Arduino Wiznet Ethernet shield.
|
||||||
|
|
||||||
Circuit:
|
Circuit:
|
||||||
* Ethernet shield attached to pins 10, 11, 12, 13
|
Ethernet shield attached to pins 10, 11, 12, 13
|
||||||
|
|
||||||
created 18 Dec 2009
|
created 18 Dec 2009
|
||||||
by David A. Mellis
|
by David A. Mellis
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe, based on work by Adrian McEwen
|
by Tom Igoe, based on work by Adrian McEwen
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <Ethernet.h>
|
#include <Ethernet.h>
|
||||||
@ -59,15 +59,13 @@ void setup() {
|
|||||||
client.println("Host: www.google.com");
|
client.println("Host: www.google.com");
|
||||||
client.println("Connection: close");
|
client.println("Connection: close");
|
||||||
client.println();
|
client.println();
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
// kf you didn't get a connection to the server:
|
// kf you didn't get a connection to the server:
|
||||||
Serial.println("connection failed");
|
Serial.println("connection failed");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
// if there are incoming bytes available
|
// if there are incoming bytes available
|
||||||
// from the server, read them and print them:
|
// from the server, read them and print them:
|
||||||
if (client.available()) {
|
if (client.available()) {
|
||||||
|
@ -1,26 +1,26 @@
|
|||||||
/*
|
/*
|
||||||
Repeating Web client
|
Repeating Web client
|
||||||
|
|
||||||
This sketch connects to a a web server and makes a request
|
This sketch connects to a a web server and makes a request
|
||||||
using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or
|
using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or
|
||||||
the Adafruit Ethernet shield, either one will work, as long as it's got
|
the Adafruit Ethernet shield, either one will work, as long as it's got
|
||||||
a Wiznet Ethernet module on board.
|
a Wiznet Ethernet module on board.
|
||||||
|
|
||||||
This example uses DNS, by assigning the Ethernet client with a MAC address,
|
This example uses DNS, by assigning the Ethernet client with a MAC address,
|
||||||
IP address, and DNS address.
|
IP address, and DNS address.
|
||||||
|
|
||||||
Circuit:
|
Circuit:
|
||||||
* Ethernet shield attached to pins 10, 11, 12, 13
|
Ethernet shield attached to pins 10, 11, 12, 13
|
||||||
|
|
||||||
created 19 Apr 2012
|
created 19 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
modified 21 Jan 2014
|
modified 21 Jan 2014
|
||||||
by Federico Vanzati
|
by Federico Vanzati
|
||||||
|
|
||||||
http://www.arduino.cc/en/Tutorial/WebClientRepeating
|
http://www.arduino.cc/en/Tutorial/WebClientRepeating
|
||||||
This code is in the public domain.
|
This code is in the public domain.
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <Ethernet.h>
|
#include <Ethernet.h>
|
||||||
@ -98,8 +98,7 @@ void httpRequest() {
|
|||||||
|
|
||||||
// note the time that the connection was made:
|
// note the time that the connection was made:
|
||||||
lastConnectionTime = millis();
|
lastConnectionTime = millis();
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
// if you couldn't make a connection:
|
// if you couldn't make a connection:
|
||||||
Serial.println("connection failed");
|
Serial.println("connection failed");
|
||||||
}
|
}
|
||||||
|
@ -1,19 +1,19 @@
|
|||||||
/*
|
/*
|
||||||
Web Server
|
Web Server
|
||||||
|
|
||||||
A simple web server that shows the value of the analog input pins.
|
A simple web server that shows the value of the analog input pins.
|
||||||
using an Arduino Wiznet Ethernet shield.
|
using an Arduino Wiznet Ethernet shield.
|
||||||
|
|
||||||
Circuit:
|
Circuit:
|
||||||
* Ethernet shield attached to pins 10, 11, 12, 13
|
Ethernet shield attached to pins 10, 11, 12, 13
|
||||||
* Analog inputs attached to pins A0 through A5 (optional)
|
Analog inputs attached to pins A0 through A5 (optional)
|
||||||
|
|
||||||
created 18 Dec 2009
|
created 18 Dec 2009
|
||||||
by David A. Mellis
|
by David A. Mellis
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <Ethernet.h>
|
#include <Ethernet.h>
|
||||||
@ -84,8 +84,7 @@ void loop() {
|
|||||||
if (c == '\n') {
|
if (c == '\n') {
|
||||||
// you're starting a new line
|
// you're starting a new line
|
||||||
currentLineIsBlank = true;
|
currentLineIsBlank = true;
|
||||||
}
|
} else if (c != '\r') {
|
||||||
else if (c != '\r') {
|
|
||||||
// you've gotten a character on the current line
|
// you've gotten a character on the current line
|
||||||
currentLineIsBlank = false;
|
currentLineIsBlank = false;
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,22 @@
|
|||||||
/*
|
/*
|
||||||
|
|
||||||
Udp NTP Client
|
Udp NTP Client
|
||||||
|
|
||||||
Get the time from a Network Time Protocol (NTP) time server
|
Get the time from a Network Time Protocol (NTP) time server
|
||||||
Demonstrates use of UDP sendPacket and ReceivePacket
|
Demonstrates use of UDP sendPacket and ReceivePacket
|
||||||
For more on NTP time servers and the messages needed to communicate with them,
|
For more on NTP time servers and the messages needed to communicate with them,
|
||||||
see http://en.wikipedia.org/wiki/Network_Time_Protocol
|
see http://en.wikipedia.org/wiki/Network_Time_Protocol
|
||||||
|
|
||||||
created 4 Sep 2010
|
created 4 Sep 2010
|
||||||
by Michael Margolis
|
by Michael Margolis
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
|
|
||||||
This code is in the public domain.
|
This code is in the public domain.
|
||||||
|
|
||||||
Modified by David Henry to show where all the 'magic numbers' come from.
|
Modified by David Henry to show where all the 'magic numbers' come from.
|
||||||
You need to read the RFC-1305 spec to understand https://tools.ietf.org/html/rfc1305
|
You need to read the RFC-1305 spec to understand https://tools.ietf.org/html/rfc1305
|
||||||
mgadriver@gmail.com
|
mgadriver@gmail.com
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@ -42,8 +42,7 @@ struct sRFC1305 packetBuffer; //buffer to hold incoming and outgoing packets
|
|||||||
// A UDP instance to let us send and receive packets over UDP
|
// A UDP instance to let us send and receive packets over UDP
|
||||||
EthernetUDP Udp;
|
EthernetUDP Udp;
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
// Open serial communications and wait for port to open:
|
// Open serial communications and wait for port to open:
|
||||||
Serial.begin(9600);
|
Serial.begin(9600);
|
||||||
while (!Serial) {
|
while (!Serial) {
|
||||||
@ -62,34 +61,33 @@ void setup()
|
|||||||
Udp.begin(localPort);
|
Udp.begin(localPort);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
sendNTPpacket(timeServer); // send an NTP packet to a time server
|
sendNTPpacket(timeServer); // send an NTP packet to a time server
|
||||||
|
|
||||||
// wait to see if a reply is available
|
// wait to see if a reply is available
|
||||||
delay(1000);
|
delay(1000);
|
||||||
if ( Udp.parsePacket() ) {
|
if (Udp.parsePacket()) {
|
||||||
// We've received a packet, read the data from it
|
// We've received a packet, read the data from it
|
||||||
Udp.read((byte *)&packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
|
Udp.read((byte *)&packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
|
||||||
#if 0 // just for debugging
|
#if 0 // just for debugging
|
||||||
Serial.println(ENDIAN_SWAP_16(packetBuffer.rootdelay_main),HEX);
|
Serial.println(ENDIAN_SWAP_16(packetBuffer.rootdelay_main), HEX);
|
||||||
Serial.println(ENDIAN_SWAP_16(packetBuffer.rootdelay_fraction),HEX);
|
Serial.println(ENDIAN_SWAP_16(packetBuffer.rootdelay_fraction), HEX);
|
||||||
Serial.println(ENDIAN_SWAP_16(packetBuffer.rootdispersion_main),HEX);
|
Serial.println(ENDIAN_SWAP_16(packetBuffer.rootdispersion_main), HEX);
|
||||||
Serial.println(ENDIAN_SWAP_16(packetBuffer.rootdispersion_fraction),HEX);
|
Serial.println(ENDIAN_SWAP_16(packetBuffer.rootdispersion_fraction), HEX);
|
||||||
Serial.println(ENDIAN_SWAP_32(packetBuffer.referencetimestamp_main),HEX);
|
Serial.println(ENDIAN_SWAP_32(packetBuffer.referencetimestamp_main), HEX);
|
||||||
Serial.println(ENDIAN_SWAP_32(packetBuffer.referencetimestamp_fraction),HEX);
|
Serial.println(ENDIAN_SWAP_32(packetBuffer.referencetimestamp_fraction), HEX);
|
||||||
Serial.println(ENDIAN_SWAP_32(packetBuffer.origintimestamp_main),HEX);
|
Serial.println(ENDIAN_SWAP_32(packetBuffer.origintimestamp_main), HEX);
|
||||||
Serial.println(ENDIAN_SWAP_32(packetBuffer.origintimestamp_fraction),HEX);
|
Serial.println(ENDIAN_SWAP_32(packetBuffer.origintimestamp_fraction), HEX);
|
||||||
Serial.println(ENDIAN_SWAP_32(packetBuffer.receivetimestamp_main),HEX);
|
Serial.println(ENDIAN_SWAP_32(packetBuffer.receivetimestamp_main), HEX);
|
||||||
Serial.println(ENDIAN_SWAP_32(packetBuffer.receivetimestamp_fraction),HEX);
|
Serial.println(ENDIAN_SWAP_32(packetBuffer.receivetimestamp_fraction), HEX);
|
||||||
Serial.println(ENDIAN_SWAP_32(packetBuffer.transmittimestamp_main),HEX);
|
Serial.println(ENDIAN_SWAP_32(packetBuffer.transmittimestamp_main), HEX);
|
||||||
Serial.println(ENDIAN_SWAP_32(packetBuffer.transmittimestamp_fraction),HEX);
|
Serial.println(ENDIAN_SWAP_32(packetBuffer.transmittimestamp_fraction), HEX);
|
||||||
#endif
|
#endif
|
||||||
Serial.print("Delay ");
|
Serial.print("Delay ");
|
||||||
Serial.print(ENDIAN_SWAP_16(packetBuffer.rootdelay_main));Serial.print(".");Serial.println(ENDIAN_SWAP_16(packetBuffer.rootdelay_fraction));
|
Serial.print(ENDIAN_SWAP_16(packetBuffer.rootdelay_main)); Serial.print("."); Serial.println(ENDIAN_SWAP_16(packetBuffer.rootdelay_fraction));
|
||||||
Serial.print("Seconds since Jan 1 1900 = " );
|
Serial.print("Seconds since Jan 1 1900 = ");
|
||||||
unsigned long secsSince1900 = ENDIAN_SWAP_32(packetBuffer.transmittimestamp_main);
|
unsigned long secsSince1900 = ENDIAN_SWAP_32(packetBuffer.transmittimestamp_main);
|
||||||
Serial.print(secsSince1900);Serial.print(".");Serial.println(ENDIAN_SWAP_32(packetBuffer.transmittimestamp_fraction));
|
Serial.print(secsSince1900); Serial.print("."); Serial.println(ENDIAN_SWAP_32(packetBuffer.transmittimestamp_fraction));
|
||||||
|
|
||||||
// now convert NTP time into everyday time:
|
// now convert NTP time into everyday time:
|
||||||
Serial.print("Unix time = ");
|
Serial.print("Unix time = ");
|
||||||
@ -99,34 +97,33 @@ void loop()
|
|||||||
unsigned long epoch = secsSince1900 - seventyYears;
|
unsigned long epoch = secsSince1900 - seventyYears;
|
||||||
// print Unix time:
|
// print Unix time:
|
||||||
Serial.println(epoch);
|
Serial.println(epoch);
|
||||||
|
|
||||||
#define SECS_PER_MINUTE 60
|
#define SECS_PER_MINUTE 60
|
||||||
#define SECS_PER_HOUR 3600
|
#define SECS_PER_HOUR 3600
|
||||||
#define SECS_PER_DAY 86400L
|
#define SECS_PER_DAY 86400L
|
||||||
|
|
||||||
// print the hour, minute and second:
|
// print the hour, minute and second:
|
||||||
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
|
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
|
||||||
Serial.print((epoch % SECS_PER_DAY) / SECS_PER_HOUR);
|
Serial.print((epoch % SECS_PER_DAY) / SECS_PER_HOUR);
|
||||||
Serial.print(':');
|
Serial.print(':');
|
||||||
if ( ((epoch % SECS_PER_HOUR) / SECS_PER_MINUTE) < 10 ) {
|
if (((epoch % SECS_PER_HOUR) / SECS_PER_MINUTE) < 10) {
|
||||||
// In the first 10 minutes of each hour, we'll want a leading '0'
|
// In the first 10 minutes of each hour, we'll want a leading '0'
|
||||||
Serial.print('0');
|
Serial.print('0');
|
||||||
}
|
}
|
||||||
Serial.print((epoch % SECS_PER_HOUR) / SECS_PER_MINUTE);
|
Serial.print((epoch % SECS_PER_HOUR) / SECS_PER_MINUTE);
|
||||||
Serial.print(':');
|
Serial.print(':');
|
||||||
if ( (epoch % SECS_PER_MINUTE) < 10 ) {
|
if ((epoch % SECS_PER_MINUTE) < 10) {
|
||||||
// In the first 10 seconds of each minute, we'll want a leading '0'
|
// In the first 10 seconds of each minute, we'll want a leading '0'
|
||||||
Serial.print('0');
|
Serial.print('0');
|
||||||
}
|
}
|
||||||
Serial.println(epoch % SECS_PER_MINUTE); // print the second
|
Serial.println(epoch % SECS_PER_MINUTE); // print the second
|
||||||
}
|
}
|
||||||
// wait ten seconds before asking for the time again
|
// wait ten seconds before asking for the time again
|
||||||
delay(10000);
|
delay(10000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// send an NTP request to the time server at the given address
|
// send an NTP request to the time server at the given address
|
||||||
unsigned long sendNTPpacket(char* address)
|
unsigned long sendNTPpacket(char* address) {
|
||||||
{
|
|
||||||
// set all bytes in the buffer to 0
|
// set all bytes in the buffer to 0
|
||||||
memset((char *)&packetBuffer, 0, NTP_PACKET_SIZE);
|
memset((char *)&packetBuffer, 0, NTP_PACKET_SIZE);
|
||||||
// Initialize values needed to form NTP request
|
// Initialize values needed to form NTP request
|
||||||
@ -141,7 +138,7 @@ unsigned long sendNTPpacket(char* address)
|
|||||||
packetBuffer.identifier[1] = 'N';
|
packetBuffer.identifier[1] = 'N';
|
||||||
packetBuffer.identifier[2] = '1';
|
packetBuffer.identifier[2] = '1';
|
||||||
packetBuffer.identifier[3] = '4';
|
packetBuffer.identifier[3] = '4';
|
||||||
// Serial.println(*(uint8_t *)&packetBuffer,HEX);
|
// Serial.println(*(uint8_t *)&packetBuffer,HEX);
|
||||||
// all NTP fields have been given values, now
|
// all NTP fields have been given values, now
|
||||||
// you can send a packet requesting a timestamp:
|
// you can send a packet requesting a timestamp:
|
||||||
Udp.beginPacket(address, 123); //NTP requests are to port 123
|
Udp.beginPacket(address, 123); //NTP requests are to port 123
|
||||||
@ -157,4 +154,4 @@ unsigned long sendNTPpacket(char* address)
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,32 +1,32 @@
|
|||||||
/**
|
/**
|
||||||
* simple demo to show sha1 calculation
|
simple demo to show sha1 calculation
|
||||||
*/
|
*/
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
#include <Hash.h>
|
#include <Hash.h>
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
Serial.begin(921600);
|
Serial.begin(921600);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
|
|
||||||
// usage as String
|
// usage as String
|
||||||
// SHA1:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
|
// SHA1:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
|
||||||
|
|
||||||
Serial.print("SHA1:");
|
Serial.print("SHA1:");
|
||||||
Serial.println(sha1("abc"));
|
Serial.println(sha1("abc"));
|
||||||
|
|
||||||
// usage as ptr
|
// usage as ptr
|
||||||
// SHA1:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
|
// SHA1:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
|
||||||
uint8_t hash[20];
|
uint8_t hash[20];
|
||||||
sha1("abc", &hash[0]);
|
sha1("abc", &hash[0]);
|
||||||
|
|
||||||
Serial.print("SHA1:");
|
Serial.print("SHA1:");
|
||||||
for(uint16_t i = 0; i < 20; i++) {
|
for (uint16_t i = 0; i < 20; i++) {
|
||||||
Serial.printf("%02x", hash[i]);
|
Serial.printf("%02x", hash[i]);
|
||||||
}
|
}
|
||||||
Serial.println();
|
Serial.println();
|
||||||
|
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,12 +1,12 @@
|
|||||||
/*
|
/*
|
||||||
SD card test
|
SD card test
|
||||||
|
|
||||||
This example shows how use the utility libraries on which the'
|
This example shows how use the utility libraries on which the'
|
||||||
SD library is based in order to get info about your SD card.
|
SD library is based in order to get info about your SD card.
|
||||||
Very useful for testing a card when you're not sure whether its working or not.
|
Very useful for testing a card when you're not sure whether its working or not.
|
||||||
|
|
||||||
The circuit:
|
The circuit:
|
||||||
* SD card attached to SPI bus as follows:
|
SD card attached to SPI bus as follows:
|
||||||
** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
|
** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
|
||||||
** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
|
** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
|
||||||
** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
|
** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
|
||||||
@ -14,11 +14,11 @@
|
|||||||
Pin 4 used here for consistency with other Arduino examples
|
Pin 4 used here for consistency with other Arduino examples
|
||||||
|
|
||||||
|
|
||||||
created 28 Mar 2011
|
created 28 Mar 2011
|
||||||
by Limor Fried
|
by Limor Fried
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
*/
|
*/
|
||||||
// include the SD library:
|
// include the SD library:
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <SD.h>
|
#include <SD.h>
|
||||||
@ -34,8 +34,7 @@ SdFile root;
|
|||||||
// Sparkfun SD shield: pin 8
|
// Sparkfun SD shield: pin 8
|
||||||
const int chipSelect = 4;
|
const int chipSelect = 4;
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
// Open serial communications and wait for port to open:
|
// Open serial communications and wait for port to open:
|
||||||
Serial.begin(9600);
|
Serial.begin(9600);
|
||||||
while (!Serial) {
|
while (!Serial) {
|
||||||
|
@ -1,32 +1,31 @@
|
|||||||
/*
|
/*
|
||||||
SD card datalogger
|
SD card datalogger
|
||||||
|
|
||||||
This example shows how to log data from three analog sensors
|
This example shows how to log data from three analog sensors
|
||||||
to an SD card using the SD library.
|
to an SD card using the SD library.
|
||||||
|
|
||||||
The circuit:
|
The circuit:
|
||||||
* analog sensors on analog ins 0, 1, and 2
|
analog sensors on analog ins 0, 1, and 2
|
||||||
* SD card attached to SPI bus as follows:
|
SD card attached to SPI bus as follows:
|
||||||
** MOSI - pin 11
|
** MOSI - pin 11
|
||||||
** MISO - pin 12
|
** MISO - pin 12
|
||||||
** CLK - pin 13
|
** CLK - pin 13
|
||||||
** CS - pin 4
|
** CS - pin 4
|
||||||
|
|
||||||
created 24 Nov 2010
|
created 24 Nov 2010
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
|
|
||||||
This example code is in the public domain.
|
This example code is in the public domain.
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <SD.h>
|
#include <SD.h>
|
||||||
|
|
||||||
const int chipSelect = 4;
|
const int chipSelect = 4;
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
// Open serial communications and wait for port to open:
|
// Open serial communications and wait for port to open:
|
||||||
Serial.begin(9600);
|
Serial.begin(9600);
|
||||||
while (!Serial) {
|
while (!Serial) {
|
||||||
@ -45,8 +44,7 @@ void setup()
|
|||||||
Serial.println("card initialized.");
|
Serial.println("card initialized.");
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
// make a string for assembling the data to log:
|
// make a string for assembling the data to log:
|
||||||
String dataString = "";
|
String dataString = "";
|
||||||
|
|
||||||
|
@ -1,32 +1,31 @@
|
|||||||
/*
|
/*
|
||||||
SD card file dump
|
SD card file dump
|
||||||
|
|
||||||
This example shows how to read a file from the SD card using the
|
This example shows how to read a file from the SD card using the
|
||||||
SD library and send it over the serial port.
|
SD library and send it over the serial port.
|
||||||
|
|
||||||
The circuit:
|
The circuit:
|
||||||
* SD card attached to SPI bus as follows:
|
SD card attached to SPI bus as follows:
|
||||||
** MOSI - pin 11
|
** MOSI - pin 11
|
||||||
** MISO - pin 12
|
** MISO - pin 12
|
||||||
** CLK - pin 13
|
** CLK - pin 13
|
||||||
** CS - pin 4
|
** CS - pin 4
|
||||||
|
|
||||||
created 22 December 2010
|
created 22 December 2010
|
||||||
by Limor Fried
|
by Limor Fried
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
|
|
||||||
This example code is in the public domain.
|
This example code is in the public domain.
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <SD.h>
|
#include <SD.h>
|
||||||
|
|
||||||
const int chipSelect = 4;
|
const int chipSelect = 4;
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
// Open serial communications and wait for port to open:
|
// Open serial communications and wait for port to open:
|
||||||
Serial.begin(9600);
|
Serial.begin(9600);
|
||||||
while (!Serial) {
|
while (!Serial) {
|
||||||
@ -61,7 +60,6 @@ void setup()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,29 +1,28 @@
|
|||||||
/*
|
/*
|
||||||
SD card basic file example
|
SD card basic file example
|
||||||
|
|
||||||
This example shows how to create and destroy an SD card file
|
This example shows how to create and destroy an SD card file
|
||||||
The circuit:
|
The circuit:
|
||||||
* SD card attached to SPI bus as follows:
|
SD card attached to SPI bus as follows:
|
||||||
** MOSI - pin 11
|
** MOSI - pin 11
|
||||||
** MISO - pin 12
|
** MISO - pin 12
|
||||||
** CLK - pin 13
|
** CLK - pin 13
|
||||||
** CS - pin 4
|
** CS - pin 4
|
||||||
|
|
||||||
created Nov 2010
|
created Nov 2010
|
||||||
by David A. Mellis
|
by David A. Mellis
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
|
|
||||||
This example code is in the public domain.
|
This example code is in the public domain.
|
||||||
|
|
||||||
*/
|
*/
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <SD.h>
|
#include <SD.h>
|
||||||
|
|
||||||
File myFile;
|
File myFile;
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
// Open serial communications and wait for port to open:
|
// Open serial communications and wait for port to open:
|
||||||
Serial.begin(9600);
|
Serial.begin(9600);
|
||||||
while (!Serial) {
|
while (!Serial) {
|
||||||
@ -41,8 +40,7 @@ void setup()
|
|||||||
|
|
||||||
if (SD.exists("example.txt")) {
|
if (SD.exists("example.txt")) {
|
||||||
Serial.println("example.txt exists.");
|
Serial.println("example.txt exists.");
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
Serial.println("example.txt doesn't exist.");
|
Serial.println("example.txt doesn't exist.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -54,8 +52,7 @@ void setup()
|
|||||||
// Check to see if the file exists:
|
// Check to see if the file exists:
|
||||||
if (SD.exists("example.txt")) {
|
if (SD.exists("example.txt")) {
|
||||||
Serial.println("example.txt exists.");
|
Serial.println("example.txt exists.");
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
Serial.println("example.txt doesn't exist.");
|
Serial.println("example.txt doesn't exist.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -65,14 +62,12 @@ void setup()
|
|||||||
|
|
||||||
if (SD.exists("example.txt")) {
|
if (SD.exists("example.txt")) {
|
||||||
Serial.println("example.txt exists.");
|
Serial.println("example.txt exists.");
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
Serial.println("example.txt doesn't exist.");
|
Serial.println("example.txt doesn't exist.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
// nothing happens after setup finishes.
|
// nothing happens after setup finishes.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,30 +1,29 @@
|
|||||||
/*
|
/*
|
||||||
SD card read/write
|
SD card read/write
|
||||||
|
|
||||||
This example shows how to read and write data to and from an SD card file
|
This example shows how to read and write data to and from an SD card file
|
||||||
The circuit:
|
The circuit:
|
||||||
* SD card attached to SPI bus as follows:
|
SD card attached to SPI bus as follows:
|
||||||
** MOSI - pin 11
|
** MOSI - pin 11
|
||||||
** MISO - pin 12
|
** MISO - pin 12
|
||||||
** CLK - pin 13
|
** CLK - pin 13
|
||||||
** CS - pin 4
|
** CS - pin 4
|
||||||
|
|
||||||
created Nov 2010
|
created Nov 2010
|
||||||
by David A. Mellis
|
by David A. Mellis
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
|
|
||||||
This example code is in the public domain.
|
This example code is in the public domain.
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <SD.h>
|
#include <SD.h>
|
||||||
|
|
||||||
File myFile;
|
File myFile;
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
// Open serial communications and wait for port to open:
|
// Open serial communications and wait for port to open:
|
||||||
Serial.begin(9600);
|
Serial.begin(9600);
|
||||||
while (!Serial) {
|
while (!Serial) {
|
||||||
@ -73,8 +72,7 @@ void setup()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
// nothing happens after setup
|
// nothing happens after setup
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,33 +1,32 @@
|
|||||||
/*
|
/*
|
||||||
Listfiles
|
Listfiles
|
||||||
|
|
||||||
This example shows how print out the files in a
|
This example shows how print out the files in a
|
||||||
directory on a SD card
|
directory on a SD card
|
||||||
|
|
||||||
The circuit:
|
The circuit:
|
||||||
* SD card attached to SPI bus as follows:
|
SD card attached to SPI bus as follows:
|
||||||
** MOSI - pin 11
|
** MOSI - pin 11
|
||||||
** MISO - pin 12
|
** MISO - pin 12
|
||||||
** CLK - pin 13
|
** CLK - pin 13
|
||||||
** CS - pin 4
|
** CS - pin 4
|
||||||
|
|
||||||
created Nov 2010
|
created Nov 2010
|
||||||
by David A. Mellis
|
by David A. Mellis
|
||||||
modified 9 Apr 2012
|
modified 9 Apr 2012
|
||||||
by Tom Igoe
|
by Tom Igoe
|
||||||
modified 2 Feb 2014
|
modified 2 Feb 2014
|
||||||
by Scott Fitzgerald
|
by Scott Fitzgerald
|
||||||
|
|
||||||
This example code is in the public domain.
|
|
||||||
|
|
||||||
*/
|
This example code is in the public domain.
|
||||||
|
|
||||||
|
*/
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <SD.h>
|
#include <SD.h>
|
||||||
|
|
||||||
File root;
|
File root;
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
// Open serial communications and wait for port to open:
|
// Open serial communications and wait for port to open:
|
||||||
Serial.begin(9600);
|
Serial.begin(9600);
|
||||||
while (!Serial) {
|
while (!Serial) {
|
||||||
@ -49,33 +48,32 @@ void setup()
|
|||||||
Serial.println("done!");
|
Serial.println("done!");
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
// nothing happens after setup finishes.
|
// nothing happens after setup finishes.
|
||||||
}
|
}
|
||||||
|
|
||||||
void printDirectory(File dir, int numTabs) {
|
void printDirectory(File dir, int numTabs) {
|
||||||
while(true) {
|
while (true) {
|
||||||
|
|
||||||
File entry = dir.openNextFile();
|
File entry = dir.openNextFile();
|
||||||
if (! entry) {
|
if (! entry) {
|
||||||
// no more files
|
// no more files
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
for (uint8_t i=0; i<numTabs; i++) {
|
for (uint8_t i = 0; i < numTabs; i++) {
|
||||||
Serial.print('\t');
|
Serial.print('\t');
|
||||||
}
|
}
|
||||||
Serial.print(entry.name());
|
Serial.print(entry.name());
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
Serial.println("/");
|
Serial.println("/");
|
||||||
printDirectory(entry, numTabs+1);
|
printDirectory(entry, numTabs + 1);
|
||||||
} else {
|
} else {
|
||||||
// files have sizes, directories do not
|
// files have sizes, directories do not
|
||||||
Serial.print("\t\t");
|
Serial.print("\t\t");
|
||||||
Serial.println(entry.size(), DEC);
|
Serial.println(entry.size(), DEC);
|
||||||
}
|
}
|
||||||
entry.close();
|
entry.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -16,103 +16,92 @@
|
|||||||
*/
|
*/
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
|
|
||||||
class ESPMaster
|
class ESPMaster {
|
||||||
{
|
private:
|
||||||
private:
|
|
||||||
uint8_t _ss_pin;
|
uint8_t _ss_pin;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
ESPMaster(uint8_t pin):_ss_pin(pin) {}
|
ESPMaster(uint8_t pin): _ss_pin(pin) {}
|
||||||
void begin()
|
void begin() {
|
||||||
{
|
pinMode(_ss_pin, OUTPUT);
|
||||||
pinMode(_ss_pin, OUTPUT);
|
digitalWrite(_ss_pin, HIGH);
|
||||||
digitalWrite(_ss_pin, HIGH);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
uint32_t readStatus()
|
uint32_t readStatus() {
|
||||||
{
|
digitalWrite(_ss_pin, LOW);
|
||||||
digitalWrite(_ss_pin, LOW);
|
SPI.transfer(0x04);
|
||||||
SPI.transfer(0x04);
|
uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24));
|
||||||
uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24));
|
digitalWrite(_ss_pin, HIGH);
|
||||||
digitalWrite(_ss_pin, HIGH);
|
return status;
|
||||||
return status;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void writeStatus(uint32_t status)
|
void writeStatus(uint32_t status) {
|
||||||
{
|
digitalWrite(_ss_pin, LOW);
|
||||||
digitalWrite(_ss_pin, LOW);
|
SPI.transfer(0x01);
|
||||||
SPI.transfer(0x01);
|
SPI.transfer(status & 0xFF);
|
||||||
SPI.transfer(status & 0xFF);
|
SPI.transfer((status >> 8) & 0xFF);
|
||||||
SPI.transfer((status >> 8) & 0xFF);
|
SPI.transfer((status >> 16) & 0xFF);
|
||||||
SPI.transfer((status >> 16) & 0xFF);
|
SPI.transfer((status >> 24) & 0xFF);
|
||||||
SPI.transfer((status >> 24) & 0xFF);
|
digitalWrite(_ss_pin, HIGH);
|
||||||
digitalWrite(_ss_pin, HIGH);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void readData(uint8_t * data)
|
void readData(uint8_t * data) {
|
||||||
{
|
digitalWrite(_ss_pin, LOW);
|
||||||
digitalWrite(_ss_pin, LOW);
|
SPI.transfer(0x03);
|
||||||
SPI.transfer(0x03);
|
SPI.transfer(0x00);
|
||||||
SPI.transfer(0x00);
|
for (uint8_t i = 0; i < 32; i++) {
|
||||||
for(uint8_t i=0; i<32; i++) {
|
data[i] = SPI.transfer(0);
|
||||||
data[i] = SPI.transfer(0);
|
}
|
||||||
}
|
digitalWrite(_ss_pin, HIGH);
|
||||||
digitalWrite(_ss_pin, HIGH);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void writeData(uint8_t * data, size_t len)
|
void writeData(uint8_t * data, size_t len) {
|
||||||
{
|
uint8_t i = 0;
|
||||||
uint8_t i=0;
|
digitalWrite(_ss_pin, LOW);
|
||||||
digitalWrite(_ss_pin, LOW);
|
SPI.transfer(0x02);
|
||||||
SPI.transfer(0x02);
|
SPI.transfer(0x00);
|
||||||
SPI.transfer(0x00);
|
while (len-- && i < 32) {
|
||||||
while(len-- && i < 32) {
|
SPI.transfer(data[i++]);
|
||||||
SPI.transfer(data[i++]);
|
}
|
||||||
}
|
while (i++ < 32) {
|
||||||
while(i++ < 32) {
|
SPI.transfer(0);
|
||||||
SPI.transfer(0);
|
}
|
||||||
}
|
digitalWrite(_ss_pin, HIGH);
|
||||||
digitalWrite(_ss_pin, HIGH);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String readData()
|
String readData() {
|
||||||
{
|
char data[33];
|
||||||
char data[33];
|
data[32] = 0;
|
||||||
data[32] = 0;
|
readData((uint8_t *)data);
|
||||||
readData((uint8_t *)data);
|
return String(data);
|
||||||
return String(data);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void writeData(const char * data)
|
void writeData(const char * data) {
|
||||||
{
|
writeData((uint8_t *)data, strlen(data));
|
||||||
writeData((uint8_t *)data, strlen(data));
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
ESPMaster esp(SS);
|
ESPMaster esp(SS);
|
||||||
|
|
||||||
void send(const char * message)
|
void send(const char * message) {
|
||||||
{
|
Serial.print("Master: ");
|
||||||
Serial.print("Master: ");
|
Serial.println(message);
|
||||||
Serial.println(message);
|
esp.writeData(message);
|
||||||
esp.writeData(message);
|
delay(10);
|
||||||
delay(10);
|
Serial.print("Slave: ");
|
||||||
Serial.print("Slave: ");
|
Serial.println(esp.readData());
|
||||||
Serial.println(esp.readData());
|
Serial.println();
|
||||||
Serial.println();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
Serial.begin(115200);
|
||||||
Serial.begin(115200);
|
SPI.begin();
|
||||||
SPI.begin();
|
esp.begin();
|
||||||
esp.begin();
|
delay(1000);
|
||||||
delay(1000);
|
send("Hello Slave!");
|
||||||
send("Hello Slave!");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
delay(1000);
|
||||||
delay(1000);
|
send("Are you alive?");
|
||||||
send("Are you alive?");
|
|
||||||
}
|
}
|
||||||
|
@ -17,108 +17,96 @@
|
|||||||
*/
|
*/
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
|
|
||||||
class ESPSafeMaster
|
class ESPSafeMaster {
|
||||||
{
|
private:
|
||||||
private:
|
|
||||||
uint8_t _ss_pin;
|
uint8_t _ss_pin;
|
||||||
void _pulseSS()
|
void _pulseSS() {
|
||||||
{
|
digitalWrite(_ss_pin, HIGH);
|
||||||
digitalWrite(_ss_pin, HIGH);
|
delayMicroseconds(5);
|
||||||
delayMicroseconds(5);
|
digitalWrite(_ss_pin, LOW);
|
||||||
digitalWrite(_ss_pin, LOW);
|
|
||||||
}
|
}
|
||||||
public:
|
public:
|
||||||
ESPSafeMaster(uint8_t pin):_ss_pin(pin) {}
|
ESPSafeMaster(uint8_t pin): _ss_pin(pin) {}
|
||||||
void begin()
|
void begin() {
|
||||||
{
|
pinMode(_ss_pin, OUTPUT);
|
||||||
pinMode(_ss_pin, OUTPUT);
|
_pulseSS();
|
||||||
_pulseSS();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
uint32_t readStatus()
|
uint32_t readStatus() {
|
||||||
{
|
_pulseSS();
|
||||||
_pulseSS();
|
SPI.transfer(0x04);
|
||||||
SPI.transfer(0x04);
|
uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24));
|
||||||
uint32_t status = (SPI.transfer(0) | ((uint32_t)(SPI.transfer(0)) << 8) | ((uint32_t)(SPI.transfer(0)) << 16) | ((uint32_t)(SPI.transfer(0)) << 24));
|
_pulseSS();
|
||||||
_pulseSS();
|
return status;
|
||||||
return status;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void writeStatus(uint32_t status)
|
void writeStatus(uint32_t status) {
|
||||||
{
|
_pulseSS();
|
||||||
_pulseSS();
|
SPI.transfer(0x01);
|
||||||
SPI.transfer(0x01);
|
SPI.transfer(status & 0xFF);
|
||||||
SPI.transfer(status & 0xFF);
|
SPI.transfer((status >> 8) & 0xFF);
|
||||||
SPI.transfer((status >> 8) & 0xFF);
|
SPI.transfer((status >> 16) & 0xFF);
|
||||||
SPI.transfer((status >> 16) & 0xFF);
|
SPI.transfer((status >> 24) & 0xFF);
|
||||||
SPI.transfer((status >> 24) & 0xFF);
|
_pulseSS();
|
||||||
_pulseSS();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void readData(uint8_t * data)
|
void readData(uint8_t * data) {
|
||||||
{
|
_pulseSS();
|
||||||
_pulseSS();
|
SPI.transfer(0x03);
|
||||||
SPI.transfer(0x03);
|
SPI.transfer(0x00);
|
||||||
SPI.transfer(0x00);
|
for (uint8_t i = 0; i < 32; i++) {
|
||||||
for(uint8_t i=0; i<32; i++) {
|
data[i] = SPI.transfer(0);
|
||||||
data[i] = SPI.transfer(0);
|
}
|
||||||
}
|
_pulseSS();
|
||||||
_pulseSS();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void writeData(uint8_t * data, size_t len)
|
void writeData(uint8_t * data, size_t len) {
|
||||||
{
|
uint8_t i = 0;
|
||||||
uint8_t i=0;
|
_pulseSS();
|
||||||
_pulseSS();
|
SPI.transfer(0x02);
|
||||||
SPI.transfer(0x02);
|
SPI.transfer(0x00);
|
||||||
SPI.transfer(0x00);
|
while (len-- && i < 32) {
|
||||||
while(len-- && i < 32) {
|
SPI.transfer(data[i++]);
|
||||||
SPI.transfer(data[i++]);
|
}
|
||||||
}
|
while (i++ < 32) {
|
||||||
while(i++ < 32) {
|
SPI.transfer(0);
|
||||||
SPI.transfer(0);
|
}
|
||||||
}
|
_pulseSS();
|
||||||
_pulseSS();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String readData()
|
String readData() {
|
||||||
{
|
char data[33];
|
||||||
char data[33];
|
data[32] = 0;
|
||||||
data[32] = 0;
|
readData((uint8_t *)data);
|
||||||
readData((uint8_t *)data);
|
return String(data);
|
||||||
return String(data);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void writeData(const char * data)
|
void writeData(const char * data) {
|
||||||
{
|
writeData((uint8_t *)data, strlen(data));
|
||||||
writeData((uint8_t *)data, strlen(data));
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
ESPSafeMaster esp(SS);
|
ESPSafeMaster esp(SS);
|
||||||
|
|
||||||
void send(const char * message)
|
void send(const char * message) {
|
||||||
{
|
Serial.print("Master: ");
|
||||||
Serial.print("Master: ");
|
Serial.println(message);
|
||||||
Serial.println(message);
|
esp.writeData(message);
|
||||||
esp.writeData(message);
|
delay(10);
|
||||||
delay(10);
|
Serial.print("Slave: ");
|
||||||
Serial.print("Slave: ");
|
Serial.println(esp.readData());
|
||||||
Serial.println(esp.readData());
|
Serial.println();
|
||||||
Serial.println();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
Serial.begin(115200);
|
||||||
Serial.begin(115200);
|
SPI.begin();
|
||||||
SPI.begin();
|
esp.begin();
|
||||||
esp.begin();
|
delay(1000);
|
||||||
delay(1000);
|
send("Hello Slave!");
|
||||||
send("Hello Slave!");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
delay(1000);
|
||||||
delay(1000);
|
send("Are you alive?");
|
||||||
send("Are you alive?");
|
|
||||||
}
|
}
|
||||||
|
@ -17,57 +17,56 @@
|
|||||||
|
|
||||||
#include "SPISlave.h"
|
#include "SPISlave.h"
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
Serial.begin(115200);
|
||||||
Serial.begin(115200);
|
Serial.setDebugOutput(true);
|
||||||
Serial.setDebugOutput(true);
|
|
||||||
|
|
||||||
// data has been received from the master. Beware that len is always 32
|
// data has been received from the master. Beware that len is always 32
|
||||||
// and the buffer is autofilled with zeroes if data is less than 32 bytes long
|
// and the buffer is autofilled with zeroes if data is less than 32 bytes long
|
||||||
// It's up to the user to implement protocol for handling data length
|
// It's up to the user to implement protocol for handling data length
|
||||||
SPISlave.onData([](uint8_t * data, size_t len) {
|
SPISlave.onData([](uint8_t * data, size_t len) {
|
||||||
String message = String((char *)data);
|
String message = String((char *)data);
|
||||||
(void) len;
|
(void) len;
|
||||||
if(message.equals("Hello Slave!")) {
|
if (message.equals("Hello Slave!")) {
|
||||||
SPISlave.setData("Hello Master!");
|
SPISlave.setData("Hello Master!");
|
||||||
} else if(message.equals("Are you alive?")) {
|
} else if (message.equals("Are you alive?")) {
|
||||||
char answer[33];
|
char answer[33];
|
||||||
sprintf(answer,"Alive for %lu seconds!", millis() / 1000);
|
sprintf(answer, "Alive for %lu seconds!", millis() / 1000);
|
||||||
SPISlave.setData(answer);
|
SPISlave.setData(answer);
|
||||||
} else {
|
} else {
|
||||||
SPISlave.setData("Say what?");
|
SPISlave.setData("Say what?");
|
||||||
}
|
}
|
||||||
Serial.printf("Question: %s\n", (char *)data);
|
Serial.printf("Question: %s\n", (char *)data);
|
||||||
});
|
});
|
||||||
|
|
||||||
// The master has read out outgoing data buffer
|
// The master has read out outgoing data buffer
|
||||||
// that buffer can be set with SPISlave.setData
|
// that buffer can be set with SPISlave.setData
|
||||||
SPISlave.onDataSent([]() {
|
SPISlave.onDataSent([]() {
|
||||||
Serial.println("Answer Sent");
|
Serial.println("Answer Sent");
|
||||||
});
|
});
|
||||||
|
|
||||||
// status has been received from the master.
|
// status has been received from the master.
|
||||||
// The status register is a special register that bot the slave and the master can write to and read from.
|
// The status register is a special register that bot the slave and the master can write to and read from.
|
||||||
// Can be used to exchange small data or status information
|
// Can be used to exchange small data or status information
|
||||||
SPISlave.onStatus([](uint32_t data) {
|
SPISlave.onStatus([](uint32_t data) {
|
||||||
Serial.printf("Status: %u\n", data);
|
Serial.printf("Status: %u\n", data);
|
||||||
SPISlave.setStatus(millis()); //set next status
|
SPISlave.setStatus(millis()); //set next status
|
||||||
});
|
});
|
||||||
|
|
||||||
// The master has read the status register
|
// The master has read the status register
|
||||||
SPISlave.onStatusSent([]() {
|
SPISlave.onStatusSent([]() {
|
||||||
Serial.println("Status Sent");
|
Serial.println("Status Sent");
|
||||||
});
|
});
|
||||||
|
|
||||||
// Setup SPI Slave registers and pins
|
// Setup SPI Slave registers and pins
|
||||||
SPISlave.begin();
|
SPISlave.begin();
|
||||||
|
|
||||||
// Set the status register (if the master reads it, it will read this value)
|
// Set the status register (if the master reads it, it will read this value)
|
||||||
SPISlave.setStatus(millis());
|
SPISlave.setStatus(millis());
|
||||||
|
|
||||||
// Sets the data registers. Limited to 32 bytes at a time.
|
// Sets the data registers. Limited to 32 bytes at a time.
|
||||||
// SPISlave.setData(uint8_t * data, size_t len); is also available with the same limitation
|
// SPISlave.setData(uint8_t * data, size_t len); is also available with the same limitation
|
||||||
SPISlave.setData("Ask me a question!");
|
SPISlave.setData("Ask me a question!");
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {}
|
void loop() {}
|
||||||
|
@ -1,39 +1,36 @@
|
|||||||
/* Sweep
|
/* Sweep
|
||||||
by BARRAGAN <http://barraganstudio.com>
|
by BARRAGAN <http://barraganstudio.com>
|
||||||
This example code is in the public domain.
|
This example code is in the public domain.
|
||||||
|
|
||||||
modified 28 May 2015
|
modified 28 May 2015
|
||||||
by Michael C. Miller
|
by Michael C. Miller
|
||||||
modified 8 Nov 2013
|
modified 8 Nov 2013
|
||||||
by Scott Fitzgerald
|
by Scott Fitzgerald
|
||||||
|
|
||||||
http://arduino.cc/en/Tutorial/Sweep
|
http://arduino.cc/en/Tutorial/Sweep
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <Servo.h>
|
#include <Servo.h>
|
||||||
|
|
||||||
Servo myservo; // create servo object to control a servo
|
|
||||||
// twelve servo objects can be created on most boards
|
|
||||||
|
|
||||||
|
|
||||||
void setup()
|
Servo myservo; // create servo object to control a servo
|
||||||
{
|
// twelve servo objects can be created on most boards
|
||||||
myservo.attach(2); // attaches the servo on GIO2 to the servo object
|
|
||||||
}
|
|
||||||
|
void setup() {
|
||||||
void loop()
|
myservo.attach(2); // attaches the servo on GIO2 to the servo object
|
||||||
{
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
int pos;
|
int pos;
|
||||||
|
|
||||||
for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees
|
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
|
||||||
{ // in steps of 1 degree
|
// in steps of 1 degree
|
||||||
myservo.write(pos); // tell servo to go to position in variable 'pos'
|
myservo.write(pos); // tell servo to go to position in variable 'pos'
|
||||||
delay(15); // waits 15ms for the servo to reach the position
|
delay(15); // waits 15ms for the servo to reach the position
|
||||||
}
|
}
|
||||||
for(pos = 180; pos>=0; pos-=1) // goes from 180 degrees to 0 degrees
|
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
|
||||||
{
|
myservo.write(pos); // tell servo to go to position in variable 'pos'
|
||||||
myservo.write(pos); // tell servo to go to position in variable 'pos'
|
delay(15); // waits 15ms for the servo to reach the position
|
||||||
delay(15); // waits 15ms for the servo to reach the position
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
@ -7,23 +7,21 @@
|
|||||||
#include <TFTv2.h>
|
#include <TFTv2.h>
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
TFT_BL_ON; //turn on the background light
|
||||||
TFT_BL_ON; //turn on the background light
|
|
||||||
|
|
||||||
Tft.TFTinit(); //init TFT library
|
|
||||||
|
|
||||||
Tft.drawCircle(100, 100, 30,YELLOW); //center: (100, 100), r = 30 ,color : YELLOW
|
Tft.TFTinit(); //init TFT library
|
||||||
|
|
||||||
Tft.drawCircle(100, 200, 40,CYAN); // center: (100, 200), r = 10 ,color : CYAN
|
Tft.drawCircle(100, 100, 30, YELLOW); //center: (100, 100), r = 30 ,color : YELLOW
|
||||||
|
|
||||||
Tft.fillCircle(200, 100, 30,RED); //center: (200, 100), r = 30 ,color : RED
|
Tft.drawCircle(100, 200, 40, CYAN); // center: (100, 200), r = 10 ,color : CYAN
|
||||||
|
|
||||||
Tft.fillCircle(200, 200, 30,BLUE); //center: (200, 200), r = 30 ,color : BLUE
|
Tft.fillCircle(200, 100, 30, RED); //center: (200, 100), r = 30 ,color : RED
|
||||||
|
|
||||||
|
Tft.fillCircle(200, 200, 30, BLUE); //center: (200, 200), r = 30 ,color : BLUE
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -7,23 +7,21 @@
|
|||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
#include <TFTv2.h>
|
#include <TFTv2.h>
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
TFT_BL_ON; // turn on the background light
|
||||||
TFT_BL_ON; // turn on the background light
|
Tft.TFTinit(); //init TFT library
|
||||||
Tft.TFTinit(); //init TFT library
|
|
||||||
|
|
||||||
Tft.drawLine(0,0,239,319,RED); //start: (0, 0) end: (239, 319), color : RED
|
Tft.drawLine(0, 0, 239, 319, RED); //start: (0, 0) end: (239, 319), color : RED
|
||||||
|
|
||||||
Tft.drawVerticalLine(60,100,100,GREEN); // Draw a vertical line
|
Tft.drawVerticalLine(60, 100, 100, GREEN); // Draw a vertical line
|
||||||
// start: (60, 100) length: 100 color: green
|
// start: (60, 100) length: 100 color: green
|
||||||
|
|
||||||
Tft.drawHorizontalLine(30,60,150,BLUE); //Draw a horizontal line
|
Tft.drawHorizontalLine(30, 60, 150, BLUE); //Draw a horizontal line
|
||||||
//start: (30, 60), high: 150, color: blue
|
//start: (30, 60), high: 150, color: blue
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*********************************************************************************************************
|
/*********************************************************************************************************
|
||||||
|
@ -8,31 +8,29 @@
|
|||||||
#include <TFTv2.h>
|
#include <TFTv2.h>
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
TFT_BL_ON; // turn on the background light
|
||||||
TFT_BL_ON; // turn on the background light
|
|
||||||
|
Tft.TFTinit(); // init TFT library
|
||||||
Tft.TFTinit(); // init TFT library
|
|
||||||
|
Tft.drawNumber(1024, 0, 0, 1, RED); // draw a integer: 1024, Location: (0, 0), size: 1, color: RED
|
||||||
Tft.drawNumber(1024, 0, 0, 1, RED); // draw a integer: 1024, Location: (0, 0), size: 1, color: RED
|
|
||||||
|
Tft.drawNumber(1024, 0, 20, 2, BLUE); // draw a integer: 1024, Location: (0, 20), size: 2, color: BLUE
|
||||||
Tft.drawNumber(1024, 0, 20, 2, BLUE); // draw a integer: 1024, Location: (0, 20), size: 2, color: BLUE
|
|
||||||
|
Tft.drawNumber(1024, 0, 50, 3, GREEN); // draw a integer: 1024, Location: (0, 50), size: 3, color: GREEN
|
||||||
Tft.drawNumber(1024, 0, 50, 3, GREEN); // draw a integer: 1024, Location: (0, 50), size: 3, color: GREEN
|
|
||||||
|
Tft.drawNumber(1024, 0, 90, 4, BLUE); // draw a integer: 1024, Location: (0, 90), size:4, color: BLUE
|
||||||
Tft.drawNumber(1024, 0, 90, 4, BLUE); // draw a integer: 1024, Location: (0, 90), size:4, color: BLUE
|
|
||||||
|
Tft.drawFloat(1.2345, 0, 150, 4, YELLOW); // draw a float number: 1.2345, Location: (0, 150), size: 4, color: YELLOW
|
||||||
Tft.drawFloat(1.2345, 0, 150, 4, YELLOW); // draw a float number: 1.2345, Location: (0, 150), size: 4, color: YELLOW
|
|
||||||
|
Tft.drawFloat(1.2345, 2, 0, 200, 4, BLUE); // draw a float number: 1.2345: Location: (0, 200), size: 4, decimal: 2, color: BLUE
|
||||||
Tft.drawFloat(1.2345, 2, 0, 200, 4, BLUE); // draw a float number: 1.2345: Location: (0, 200), size: 4, decimal: 2, color: BLUE
|
|
||||||
|
Tft.drawFloat(1.2345, 4, 0, 250, 4, RED); // draw a float number: 1.2345 Location: (0, 250), size: 4, decimal: 4, color: RED
|
||||||
Tft.drawFloat(1.2345, 4, 0, 250, 4, RED); // draw a float number: 1.2345 Location: (0, 250), size: 4, decimal: 4, color: RED
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*********************************************************************************************************
|
/*********************************************************************************************************
|
||||||
|
@ -7,19 +7,17 @@
|
|||||||
#include <TFTv2.h>
|
#include <TFTv2.h>
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
TFT_BL_ON; // turn on the background light
|
||||||
TFT_BL_ON; // turn on the background light
|
Tft.TFTinit(); // init TFT library
|
||||||
Tft.TFTinit(); // init TFT library
|
|
||||||
|
|
||||||
Tft.fillScreen(80, 160, 50, 150,RED);
|
Tft.fillScreen(80, 160, 50, 150, RED);
|
||||||
Tft.fillRectangle(30, 120, 100,65,YELLOW);
|
Tft.fillRectangle(30, 120, 100, 65, YELLOW);
|
||||||
Tft.drawRectangle(100, 170, 120,60,BLUE);
|
Tft.drawRectangle(100, 170, 120, 60, BLUE);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
|
|
||||||
}
|
}
|
||||||
/*********************************************************************************************************
|
/*********************************************************************************************************
|
||||||
END FILE
|
END FILE
|
||||||
|
@ -14,41 +14,35 @@ unsigned int colors[8] = {BLACK, RED, GREEN, BLUE, CYAN, YELLOW, WHITE, GRAY1};
|
|||||||
|
|
||||||
TouchScreen ts = TouchScreen(XP, YP, XM, YM); //init TouchScreen port pins
|
TouchScreen ts = TouchScreen(XP, YP, XM, YM); //init TouchScreen port pins
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
Tft.TFTinit(); //init TFT library
|
||||||
Tft.TFTinit(); //init TFT library
|
Serial.begin(115200);
|
||||||
Serial.begin(115200);
|
//Draw the pallet
|
||||||
//Draw the pallet
|
for (int i = 0; i < 8; i++) {
|
||||||
for(int i = 0; i<8; i++)
|
Tft.fillRectangle(i * 30, 0, 30, ColorPaletteHigh, colors[i]);
|
||||||
{
|
}
|
||||||
Tft.fillRectangle(i*30, 0, 30, ColorPaletteHigh, colors[i]);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
// a point object holds x y and z coordinates.
|
||||||
// a point object holds x y and z coordinates.
|
Point p = ts.getPoint();
|
||||||
Point p = ts.getPoint();
|
|
||||||
|
|
||||||
//map the ADC value read to into pixel co-ordinates
|
//map the ADC value read to into pixel co-ordinates
|
||||||
|
|
||||||
p.x = map(p.x, TS_MINX, TS_MAXX, 0, 240);
|
p.x = map(p.x, TS_MINX, TS_MAXX, 0, 240);
|
||||||
p.y = map(p.y, TS_MINY, TS_MAXY, 0, 320);
|
p.y = map(p.y, TS_MINY, TS_MAXY, 0, 320);
|
||||||
|
|
||||||
// we have some minimum pressure we consider 'valid'
|
// we have some minimum pressure we consider 'valid'
|
||||||
// pressure of 0 means no pressing!
|
// pressure of 0 means no pressing!
|
||||||
|
|
||||||
if (p.z > __PRESURE) {
|
if (p.z > __PRESURE) {
|
||||||
// Detect paint brush color change
|
// Detect paint brush color change
|
||||||
if(p.y < ColorPaletteHigh+2)
|
if (p.y < ColorPaletteHigh + 2) {
|
||||||
{
|
color = colors[p.x / 30];
|
||||||
color = colors[p.x/30];
|
} else {
|
||||||
}
|
Tft.fillCircle(p.x, p.y, 2, color);
|
||||||
else
|
|
||||||
{
|
|
||||||
Tft.fillCircle(p.x,p.y,2,color);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
/*********************************************************************************************************
|
/*********************************************************************************************************
|
||||||
END FILE
|
END FILE
|
||||||
|
@ -4,19 +4,16 @@
|
|||||||
#include <TFTv2.h>
|
#include <TFTv2.h>
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
TFT_BL_ON; // turn on the background light
|
||||||
TFT_BL_ON; // turn on the background light
|
Tft.TFTinit(); // init TFT library
|
||||||
Tft.TFTinit(); // init TFT library
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
for (int r = 0; r < 115; r = r + 2) { //set r : 0--115
|
||||||
for(int r=0;r<115;r=r+2) //set r : 0--115
|
Tft.drawCircle(119, 160, r, random(0xFFFF)); //draw circle, center:(119, 160), color: random
|
||||||
{
|
}
|
||||||
Tft.drawCircle(119,160,r,random(0xFFFF)); //draw circle, center:(119, 160), color: random
|
delay(10);
|
||||||
}
|
|
||||||
delay(10);
|
|
||||||
}
|
}
|
||||||
/*********************************************************************************************************
|
/*********************************************************************************************************
|
||||||
END FILE
|
END FILE
|
||||||
|
@ -7,29 +7,27 @@
|
|||||||
#include <TFTv2.h>
|
#include <TFTv2.h>
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
TFT_BL_ON; // turn on the background light
|
||||||
TFT_BL_ON; // turn on the background light
|
Tft.TFTinit(); // init TFT library
|
||||||
Tft.TFTinit(); // init TFT library
|
|
||||||
|
Tft.drawChar('S', 0, 0, 1, RED); // draw char: 'S', (0, 0), size: 1, color: RED
|
||||||
Tft.drawChar('S',0,0,1,RED); // draw char: 'S', (0, 0), size: 1, color: RED
|
|
||||||
|
Tft.drawChar('E', 10, 10, 2, BLUE); // draw char: 'E', (10, 10), size: 2, color: BLUE
|
||||||
Tft.drawChar('E',10,10,2,BLUE); // draw char: 'E', (10, 10), size: 2, color: BLUE
|
|
||||||
|
Tft.drawChar('E', 20, 40, 3, GREEN); // draw char: 'E', (20, 40), size: 3, color: GREEN
|
||||||
Tft.drawChar('E',20,40,3,GREEN); // draw char: 'E', (20, 40), size: 3, color: GREEN
|
|
||||||
|
Tft.drawChar('E', 30, 80, 4, YELLOW); // draw char: 'E', (30, 80), size: 4, color: YELLOW
|
||||||
Tft.drawChar('E',30,80,4,YELLOW); // draw char: 'E', (30, 80), size: 4, color: YELLOW
|
|
||||||
|
Tft.drawChar('D', 40, 120, 4, YELLOW); // draw char: 'D', (40, 120), size: 4, color: YELLOW
|
||||||
Tft.drawChar('D',40,120,4,YELLOW); // draw char: 'D', (40, 120), size: 4, color: YELLOW
|
|
||||||
|
Tft.drawString("Hello", 0, 180, 3, CYAN); // draw string: "hello", (0, 180), size: 3, color: CYAN
|
||||||
Tft.drawString("Hello",0,180,3,CYAN); // draw string: "hello", (0, 180), size: 3, color: CYAN
|
|
||||||
|
Tft.drawString("World!!", 60, 220, 4, WHITE); // draw string: "world!!", (80, 230), size: 4, color: WHITE
|
||||||
Tft.drawString("World!!",60,220,4,WHITE); // draw string: "world!!", (80, 230), size: 4, color: WHITE
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
/*
|
/*
|
||||||
TFT Touch Shield 2.0 examples - tftbmp
|
TFT Touch Shield 2.0 examples - tftbmp
|
||||||
|
|
||||||
loovee
|
loovee
|
||||||
2013-1-21
|
2013-1-21
|
||||||
|
|
||||||
this demo can show specified bmp file in root Directory of SD card
|
this demo can show specified bmp file in root Directory of SD card
|
||||||
please ensure that your image file is 320x240 size.
|
please ensure that your image file is 320x240 size.
|
||||||
|
|
||||||
change __Gnfile_num and __Gsbmp_files to display your image
|
change __Gnfile_num and __Gsbmp_files to display your image
|
||||||
*/
|
*/
|
||||||
@ -30,64 +30,57 @@ unsigned char __Gnbmp_image_offset = 0; // offset
|
|||||||
|
|
||||||
int __Gnfile_num = 3; // num of file
|
int __Gnfile_num = 3; // num of file
|
||||||
|
|
||||||
char __Gsbmp_files[3][FILENAME_LEN] = // add file name here
|
char __Gsbmp_files[3][FILENAME_LEN] = { // add file name here
|
||||||
{
|
"flower.BMP",
|
||||||
"flower.BMP",
|
"hibiscus.bmp",
|
||||||
"hibiscus.bmp",
|
"test.bmp",
|
||||||
"test.bmp",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
File bmpFile;
|
File bmpFile;
|
||||||
|
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
|
|
||||||
Serial.begin(9600);
|
Serial.begin(9600);
|
||||||
|
|
||||||
pinMode(PIN_SD_CS,OUTPUT);
|
|
||||||
digitalWrite(PIN_SD_CS,HIGH);
|
|
||||||
|
|
||||||
Tft.TFTinit();
|
pinMode(PIN_SD_CS, OUTPUT);
|
||||||
|
digitalWrite(PIN_SD_CS, HIGH);
|
||||||
|
|
||||||
Sd2Card card;
|
Tft.TFTinit();
|
||||||
card.init(SPI_FULL_SPEED, PIN_SD_CS);
|
|
||||||
|
|
||||||
if(!SD.begin(PIN_SD_CS))
|
|
||||||
{
|
|
||||||
Serial.println("failed!");
|
|
||||||
while(1); // init fail, die here
|
|
||||||
}
|
|
||||||
|
|
||||||
Serial.println("SD OK!");
|
|
||||||
|
|
||||||
TFT_BL_ON;
|
Sd2Card card;
|
||||||
|
card.init(SPI_FULL_SPEED, PIN_SD_CS);
|
||||||
|
|
||||||
|
if (!SD.begin(PIN_SD_CS)) {
|
||||||
|
Serial.println("failed!");
|
||||||
|
while (1); // init fail, die here
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.println("SD OK!");
|
||||||
|
|
||||||
|
TFT_BL_ON;
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
for (unsigned char i = 0; i < __Gnfile_num; i++) {
|
||||||
for(unsigned char i=0; i<__Gnfile_num; i++)
|
bmpFile = SD.open(__Gsbmp_files[i]);
|
||||||
{
|
if (! bmpFile) {
|
||||||
bmpFile = SD.open(__Gsbmp_files[i]);
|
Serial.println("didnt find image");
|
||||||
if (! bmpFile)
|
while (1);
|
||||||
{
|
|
||||||
Serial.println("didnt find image");
|
|
||||||
while (1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if(! bmpReadHeader(bmpFile))
|
|
||||||
{
|
|
||||||
Serial.println("bad bmp");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
bmpdraw(bmpFile, 0, 0);
|
|
||||||
bmpFile.close();
|
|
||||||
|
|
||||||
delay(1000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (! bmpReadHeader(bmpFile)) {
|
||||||
|
Serial.println("bad bmp");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
bmpdraw(bmpFile, 0, 0);
|
||||||
|
bmpFile.close();
|
||||||
|
|
||||||
|
delay(1000);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*********************************************/
|
/*********************************************/
|
||||||
@ -100,109 +93,103 @@ void loop()
|
|||||||
#define BUFFPIXEL 60 // must be a divisor of 240
|
#define BUFFPIXEL 60 // must be a divisor of 240
|
||||||
#define BUFFPIXEL_X3 180 // BUFFPIXELx3
|
#define BUFFPIXEL_X3 180 // BUFFPIXELx3
|
||||||
|
|
||||||
void bmpdraw(File f, int x, int y)
|
void bmpdraw(File f, int x, int y) {
|
||||||
{
|
bmpFile.seek(__Gnbmp_image_offset);
|
||||||
bmpFile.seek(__Gnbmp_image_offset);
|
|
||||||
|
|
||||||
uint32_t time = millis();
|
uint32_t time = millis();
|
||||||
|
|
||||||
uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer
|
uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer
|
||||||
|
|
||||||
for (int i=0; i< __Gnbmp_height; i++)
|
for (int i = 0; i < __Gnbmp_height; i++) {
|
||||||
{
|
|
||||||
|
|
||||||
for(int j=0; j<(240/BUFFPIXEL); j++)
|
for (int j = 0; j < (240 / BUFFPIXEL); j++) {
|
||||||
{
|
bmpFile.read(sdbuffer, BUFFPIXEL_X3);
|
||||||
bmpFile.read(sdbuffer, BUFFPIXEL_X3);
|
uint8_t buffidx = 0;
|
||||||
uint8_t buffidx = 0;
|
int offset_x = j * BUFFPIXEL;
|
||||||
int offset_x = j*BUFFPIXEL;
|
|
||||||
|
|
||||||
unsigned int __color[BUFFPIXEL];
|
|
||||||
|
|
||||||
for(int k=0; k<BUFFPIXEL; k++)
|
|
||||||
{
|
|
||||||
__color[k] = sdbuffer[buffidx+2]>>3; // read
|
|
||||||
__color[k] = __color[k]<<6 | (sdbuffer[buffidx+1]>>2); // green
|
|
||||||
__color[k] = __color[k]<<5 | (sdbuffer[buffidx+0]>>3); // blue
|
|
||||||
|
|
||||||
buffidx += 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
Tft.setCol(offset_x, offset_x+BUFFPIXEL);
|
unsigned int __color[BUFFPIXEL];
|
||||||
Tft.setPage(i, i);
|
|
||||||
Tft.sendCMD(0x2c);
|
|
||||||
|
|
||||||
TFT_DC_HIGH;
|
|
||||||
TFT_CS_LOW;
|
|
||||||
|
|
||||||
for(int m=0; m < BUFFPIXEL; m++)
|
for (int k = 0; k < BUFFPIXEL; k++) {
|
||||||
{
|
__color[k] = sdbuffer[buffidx + 2] >> 3; // read
|
||||||
SPI.transfer(__color[m]>>8);
|
__color[k] = __color[k] << 6 | (sdbuffer[buffidx + 1] >> 2); // green
|
||||||
SPI.transfer(__color[m]);
|
__color[k] = __color[k] << 5 | (sdbuffer[buffidx + 0] >> 3); // blue
|
||||||
}
|
|
||||||
|
|
||||||
TFT_CS_HIGH;
|
buffidx += 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Tft.setCol(offset_x, offset_x + BUFFPIXEL);
|
||||||
|
Tft.setPage(i, i);
|
||||||
|
Tft.sendCMD(0x2c);
|
||||||
|
|
||||||
|
TFT_DC_HIGH;
|
||||||
|
TFT_CS_LOW;
|
||||||
|
|
||||||
|
for (int m = 0; m < BUFFPIXEL; m++) {
|
||||||
|
SPI.transfer(__color[m] >> 8);
|
||||||
|
SPI.transfer(__color[m]);
|
||||||
|
}
|
||||||
|
|
||||||
|
TFT_CS_HIGH;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.print(millis() - time, DEC);
|
}
|
||||||
Serial.println(" ms");
|
|
||||||
|
Serial.print(millis() - time, DEC);
|
||||||
|
Serial.println(" ms");
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean bmpReadHeader(File f)
|
boolean bmpReadHeader(File f) {
|
||||||
{
|
// read header
|
||||||
// read header
|
uint32_t tmp;
|
||||||
uint32_t tmp;
|
uint8_t bmpDepth;
|
||||||
uint8_t bmpDepth;
|
|
||||||
|
|
||||||
if (read16(f) != 0x4D42) {
|
|
||||||
// magic bytes missing
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// read file size
|
if (read16(f) != 0x4D42) {
|
||||||
tmp = read32(f);
|
// magic bytes missing
|
||||||
Serial.print("size 0x");
|
|
||||||
Serial.println(tmp, HEX);
|
|
||||||
|
|
||||||
// read and ignore creator bytes
|
|
||||||
read32(f);
|
|
||||||
|
|
||||||
__Gnbmp_image_offset = read32(f);
|
|
||||||
Serial.print("offset ");
|
|
||||||
Serial.println(__Gnbmp_image_offset, DEC);
|
|
||||||
|
|
||||||
// read DIB header
|
|
||||||
tmp = read32(f);
|
|
||||||
Serial.print("header size ");
|
|
||||||
Serial.println(tmp, DEC);
|
|
||||||
|
|
||||||
|
|
||||||
int bmp_width = read32(f);
|
|
||||||
int bmp_height = read32(f);
|
|
||||||
|
|
||||||
if(bmp_width != __Gnbmp_width || bmp_height != __Gnbmp_height) // if image is not 320x240, return false
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (read16(f) != 1)
|
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
bmpDepth = read16(f);
|
// read file size
|
||||||
Serial.print("bitdepth ");
|
tmp = read32(f);
|
||||||
Serial.println(bmpDepth, DEC);
|
Serial.print("size 0x");
|
||||||
|
Serial.println(tmp, HEX);
|
||||||
|
|
||||||
if (read32(f) != 0) {
|
// read and ignore creator bytes
|
||||||
// compression not supported!
|
read32(f);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
Serial.print("compression ");
|
__Gnbmp_image_offset = read32(f);
|
||||||
Serial.println(tmp, DEC);
|
Serial.print("offset ");
|
||||||
|
Serial.println(__Gnbmp_image_offset, DEC);
|
||||||
|
|
||||||
return true;
|
// read DIB header
|
||||||
|
tmp = read32(f);
|
||||||
|
Serial.print("header size ");
|
||||||
|
Serial.println(tmp, DEC);
|
||||||
|
|
||||||
|
|
||||||
|
int bmp_width = read32(f);
|
||||||
|
int bmp_height = read32(f);
|
||||||
|
|
||||||
|
if (bmp_width != __Gnbmp_width || bmp_height != __Gnbmp_height) { // if image is not 320x240, return false
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (read16(f) != 1) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bmpDepth = read16(f);
|
||||||
|
Serial.print("bitdepth ");
|
||||||
|
Serial.println(bmpDepth, DEC);
|
||||||
|
|
||||||
|
if (read32(f) != 0) {
|
||||||
|
// compression not supported!
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.print("compression ");
|
||||||
|
Serial.println(tmp, DEC);
|
||||||
|
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*********************************************/
|
/*********************************************/
|
||||||
@ -210,26 +197,24 @@ boolean bmpReadHeader(File f)
|
|||||||
// (the data is stored in little endian format!)
|
// (the data is stored in little endian format!)
|
||||||
|
|
||||||
// LITTLE ENDIAN!
|
// LITTLE ENDIAN!
|
||||||
uint16_t read16(File f)
|
uint16_t read16(File f) {
|
||||||
{
|
uint16_t d;
|
||||||
uint16_t d;
|
uint8_t b;
|
||||||
uint8_t b;
|
b = f.read();
|
||||||
b = f.read();
|
d = f.read();
|
||||||
d = f.read();
|
d <<= 8;
|
||||||
d <<= 8;
|
d |= b;
|
||||||
d |= b;
|
return d;
|
||||||
return d;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// LITTLE ENDIAN!
|
// LITTLE ENDIAN!
|
||||||
uint32_t read32(File f)
|
uint32_t read32(File f) {
|
||||||
{
|
uint32_t d;
|
||||||
uint32_t d;
|
uint16_t b;
|
||||||
uint16_t b;
|
|
||||||
|
|
||||||
b = read16(f);
|
b = read16(f);
|
||||||
d = read16(f);
|
d = read16(f);
|
||||||
d <<= 16;
|
d <<= 16;
|
||||||
d |= b;
|
d |= b;
|
||||||
return d;
|
return d;
|
||||||
}
|
}
|
||||||
|
@ -1,15 +1,15 @@
|
|||||||
/*
|
/*
|
||||||
TFT Touch Shield 2.0 examples - tftbmp2
|
TFT Touch Shield 2.0 examples - tftbmp2
|
||||||
|
|
||||||
loovee
|
loovee
|
||||||
2013-1-21
|
2013-1-21
|
||||||
|
|
||||||
this demo can show all bmp file in root Directory of SD card
|
this demo can show all bmp file in root Directory of SD card
|
||||||
please ensure that your image file is 320x240 size.
|
please ensure that your image file is 320x240 size.
|
||||||
|
|
||||||
MAX_BMP can config the max file to display
|
MAX_BMP can config the max file to display
|
||||||
FILENAME_LEN can config the max length of file name
|
FILENAME_LEN can config the max length of file name
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <SD.h>
|
#include <SD.h>
|
||||||
@ -34,147 +34,139 @@ char __Gsbmp_files[MAX_BMP][FILENAME_LEN]; // file name
|
|||||||
File bmpFile;
|
File bmpFile;
|
||||||
|
|
||||||
// if bmp file return 1, else return 0
|
// if bmp file return 1, else return 0
|
||||||
bool checkBMP(char *_name, char r_name[])
|
bool checkBMP(char *_name, char r_name[]) {
|
||||||
{
|
int len = 0;
|
||||||
int len = 0;
|
|
||||||
|
|
||||||
if(NULL == _name)return false;
|
|
||||||
|
|
||||||
while(*_name)
|
|
||||||
{
|
|
||||||
r_name[len++] = *(_name++);
|
|
||||||
if(len>FILENAME_LEN)return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
r_name[len] = '\0';
|
|
||||||
|
|
||||||
if(len < 5)return false;
|
|
||||||
|
|
||||||
// if xxx.bmp or xxx.BMP
|
|
||||||
if( r_name[len-4] == '.' \
|
|
||||||
&& (r_name[len-3] == 'b' || (r_name[len-3] == 'B')) \
|
|
||||||
&& (r_name[len-2] == 'm' || (r_name[len-2] == 'M')) \
|
|
||||||
&& (r_name[len-1] == 'p' || (r_name[len-1] == 'P')) )
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (NULL == _name) {
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (*_name) {
|
||||||
|
r_name[len++] = *(_name++);
|
||||||
|
if (len > FILENAME_LEN) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
r_name[len] = '\0';
|
||||||
|
|
||||||
|
if (len < 5) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// if xxx.bmp or xxx.BMP
|
||||||
|
if (r_name[len - 4] == '.' \
|
||||||
|
&& (r_name[len - 3] == 'b' || (r_name[len - 3] == 'B')) \
|
||||||
|
&& (r_name[len - 2] == 'm' || (r_name[len - 2] == 'M')) \
|
||||||
|
&& (r_name[len - 1] == 'p' || (r_name[len - 1] == 'P'))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// search root to find bmp file
|
// search root to find bmp file
|
||||||
void searchDirectory()
|
void searchDirectory() {
|
||||||
{
|
File root = SD.open("/"); // root
|
||||||
File root = SD.open("/"); // root
|
while (true) {
|
||||||
while(true)
|
File entry = root.openNextFile();
|
||||||
{
|
|
||||||
File entry = root.openNextFile();
|
|
||||||
|
|
||||||
if (! entry)
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(!entry.isDirectory())
|
if (! entry) {
|
||||||
{
|
break;
|
||||||
char *ptmp = entry.name();
|
|
||||||
|
|
||||||
char __Name[20];
|
|
||||||
|
|
||||||
if(checkBMP(ptmp, __Name))
|
|
||||||
{
|
|
||||||
Serial.println(__Name);
|
|
||||||
|
|
||||||
strcpy(__Gsbmp_files[__Gnfile_num++], __Name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
entry.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.print("get ");
|
if (!entry.isDirectory()) {
|
||||||
Serial.print(__Gnfile_num);
|
char *ptmp = entry.name();
|
||||||
Serial.println(" file: ");
|
|
||||||
|
char __Name[20];
|
||||||
for(int i=0; i<__Gnfile_num; i++)
|
|
||||||
{
|
if (checkBMP(ptmp, __Name)) {
|
||||||
Serial.println(__Gsbmp_files[i]);
|
Serial.println(__Name);
|
||||||
|
|
||||||
|
strcpy(__Gsbmp_files[__Gnfile_num++], __Name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
entry.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.print("get ");
|
||||||
|
Serial.print(__Gnfile_num);
|
||||||
|
Serial.println(" file: ");
|
||||||
|
|
||||||
|
for (int i = 0; i < __Gnfile_num; i++) {
|
||||||
|
Serial.println(__Gsbmp_files[i]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
|
||||||
|
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
|
|
||||||
pinMode(PIN_SD_CS,OUTPUT);
|
|
||||||
digitalWrite(PIN_SD_CS,HIGH);
|
|
||||||
|
|
||||||
Tft.TFTinit();
|
pinMode(PIN_SD_CS, OUTPUT);
|
||||||
|
digitalWrite(PIN_SD_CS, HIGH);
|
||||||
|
|
||||||
Sd2Card card;
|
Tft.TFTinit();
|
||||||
card.init(SPI_FULL_SPEED, PIN_SD_CS);
|
|
||||||
|
|
||||||
if(!SD.begin(PIN_SD_CS))
|
|
||||||
{
|
|
||||||
Serial.println("failed!");
|
|
||||||
while(1); // init fail, die here
|
|
||||||
}
|
|
||||||
|
|
||||||
Serial.println("SD OK!");
|
|
||||||
|
|
||||||
searchDirectory();
|
|
||||||
|
|
||||||
TFT_BL_ON;
|
Sd2Card card;
|
||||||
|
card.init(SPI_FULL_SPEED, PIN_SD_CS);
|
||||||
|
|
||||||
|
if (!SD.begin(PIN_SD_CS)) {
|
||||||
|
Serial.println("failed!");
|
||||||
|
while (1); // init fail, die here
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.println("SD OK!");
|
||||||
|
|
||||||
|
searchDirectory();
|
||||||
|
|
||||||
|
TFT_BL_ON;
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
/*
|
||||||
/*
|
static int dirCtrl = 0;
|
||||||
static int dirCtrl = 0;
|
for(unsigned char i=0; i<__Gnfile_num; i++)
|
||||||
for(unsigned char i=0; i<__Gnfile_num; i++)
|
{
|
||||||
{
|
bmpFile = SD.open(__Gsbmp_files[i]);
|
||||||
bmpFile = SD.open(__Gsbmp_files[i]);
|
if (! bmpFile)
|
||||||
if (! bmpFile)
|
{
|
||||||
{
|
Serial.println("didnt find image");
|
||||||
Serial.println("didnt find image");
|
while (1);
|
||||||
while (1);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if(! bmpReadHeader(bmpFile))
|
if(! bmpReadHeader(bmpFile))
|
||||||
{
|
{
|
||||||
Serial.println("bad bmp");
|
Serial.println("bad bmp");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
dirCtrl = 1-dirCtrl;
|
dirCtrl = 1-dirCtrl;
|
||||||
bmpdraw(bmpFile, 0, 0, dirCtrl);
|
bmpdraw(bmpFile, 0, 0, dirCtrl);
|
||||||
bmpFile.close();
|
bmpFile.close();
|
||||||
|
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
bmpFile = SD.open("pfvm_1.bmp");
|
bmpFile = SD.open("pfvm_1.bmp");
|
||||||
|
|
||||||
if (! bmpFile)
|
|
||||||
{
|
|
||||||
Serial.println("didnt find image");
|
|
||||||
while (1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if(! bmpReadHeader(bmpFile))
|
if (! bmpFile) {
|
||||||
{
|
Serial.println("didnt find image");
|
||||||
Serial.println("bad bmp");
|
while (1);
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
bmpdraw(bmpFile, 0, 0, 1);
|
if (! bmpReadHeader(bmpFile)) {
|
||||||
bmpFile.close();
|
Serial.println("bad bmp");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
while(1);
|
bmpdraw(bmpFile, 0, 0, 1);
|
||||||
|
bmpFile.close();
|
||||||
|
|
||||||
|
while (1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*********************************************/
|
/*********************************************/
|
||||||
@ -193,129 +185,118 @@ void loop()
|
|||||||
|
|
||||||
// dir - 1: up to down
|
// dir - 1: up to down
|
||||||
// dir - 2: down to up
|
// dir - 2: down to up
|
||||||
void bmpdraw(File f, int x, int y, int dir)
|
void bmpdraw(File f, int x, int y, int dir) {
|
||||||
{
|
|
||||||
|
|
||||||
if(bmpFile.seek(__Gnbmp_image_offset))
|
if (bmpFile.seek(__Gnbmp_image_offset)) {
|
||||||
{
|
Serial.print("pos = ");
|
||||||
Serial.print("pos = ");
|
Serial.println(bmpFile.position());
|
||||||
Serial.println(bmpFile.position());
|
}
|
||||||
|
|
||||||
|
uint32_t time = millis();
|
||||||
|
|
||||||
|
uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer
|
||||||
|
|
||||||
|
for (int i = 0; i < __Gnbmp_height; i++) {
|
||||||
|
if (dir) {
|
||||||
|
bmpFile.seek(__Gnbmp_image_offset + (__Gnbmp_height - 1 - i) * 240 * 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
uint32_t time = millis();
|
|
||||||
|
|
||||||
uint8_t sdbuffer[BUFFPIXEL_X3]; // 3 * pixels to buffer
|
for (int j = 0; j < (240 / BUFFPIXEL); j++) {
|
||||||
|
|
||||||
for (int i=0; i< __Gnbmp_height; i++)
|
bmpFile.read(sdbuffer, BUFFPIXEL_X3);
|
||||||
{
|
uint8_t buffidx = 0;
|
||||||
if(dir)
|
int offset_x = j * BUFFPIXEL;
|
||||||
{
|
|
||||||
bmpFile.seek(__Gnbmp_image_offset+(__Gnbmp_height-1-i)*240*3);
|
|
||||||
}
|
|
||||||
|
|
||||||
for(int j=0; j<(240/BUFFPIXEL); j++)
|
unsigned int __color[BUFFPIXEL];
|
||||||
{
|
|
||||||
|
|
||||||
bmpFile.read(sdbuffer, BUFFPIXEL_X3);
|
|
||||||
uint8_t buffidx = 0;
|
|
||||||
int offset_x = j*BUFFPIXEL;
|
|
||||||
|
|
||||||
unsigned int __color[BUFFPIXEL];
|
|
||||||
|
|
||||||
for(int k=0; k<BUFFPIXEL; k++)
|
|
||||||
{
|
|
||||||
__color[k] = sdbuffer[buffidx+2]>>3; // read
|
|
||||||
__color[k] = __color[k]<<6 | (sdbuffer[buffidx+1]>>2); // green
|
|
||||||
__color[k] = __color[k]<<5 | (sdbuffer[buffidx+0]>>3); // blue
|
|
||||||
|
|
||||||
buffidx += 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
Tft.setCol(offset_x, offset_x+BUFFPIXEL);
|
for (int k = 0; k < BUFFPIXEL; k++) {
|
||||||
|
__color[k] = sdbuffer[buffidx + 2] >> 3; // read
|
||||||
|
__color[k] = __color[k] << 6 | (sdbuffer[buffidx + 1] >> 2); // green
|
||||||
|
__color[k] = __color[k] << 5 | (sdbuffer[buffidx + 0] >> 3); // blue
|
||||||
|
|
||||||
if(dir)
|
buffidx += 3;
|
||||||
{
|
}
|
||||||
Tft.setPage(i, i);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Tft.setPage(__Gnbmp_height-i-1, __Gnbmp_height-i-1);
|
|
||||||
}
|
|
||||||
|
|
||||||
Tft.sendCMD(0x2c);
|
Tft.setCol(offset_x, offset_x + BUFFPIXEL);
|
||||||
|
|
||||||
TFT_DC_HIGH;
|
|
||||||
TFT_CS_LOW;
|
|
||||||
|
|
||||||
for(int m=0; m < BUFFPIXEL; m++)
|
if (dir) {
|
||||||
{
|
Tft.setPage(i, i);
|
||||||
SPI.transfer(__color[m]>>8);
|
} else {
|
||||||
SPI.transfer(__color[m]);
|
Tft.setPage(__Gnbmp_height - i - 1, __Gnbmp_height - i - 1);
|
||||||
|
}
|
||||||
delay(10);
|
|
||||||
}
|
|
||||||
|
|
||||||
TFT_CS_HIGH;
|
Tft.sendCMD(0x2c);
|
||||||
}
|
|
||||||
|
TFT_DC_HIGH;
|
||||||
|
TFT_CS_LOW;
|
||||||
|
|
||||||
|
for (int m = 0; m < BUFFPIXEL; m++) {
|
||||||
|
SPI.transfer(__color[m] >> 8);
|
||||||
|
SPI.transfer(__color[m]);
|
||||||
|
|
||||||
|
delay(10);
|
||||||
|
}
|
||||||
|
|
||||||
|
TFT_CS_HIGH;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.print(millis() - time, DEC);
|
}
|
||||||
Serial.println(" ms");
|
|
||||||
|
Serial.print(millis() - time, DEC);
|
||||||
|
Serial.println(" ms");
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean bmpReadHeader(File f)
|
boolean bmpReadHeader(File f) {
|
||||||
{
|
// read header
|
||||||
// read header
|
uint32_t tmp;
|
||||||
uint32_t tmp;
|
uint8_t bmpDepth;
|
||||||
uint8_t bmpDepth;
|
|
||||||
|
|
||||||
if (read16(f) != 0x4D42) {
|
|
||||||
// magic bytes missing
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// read file size
|
if (read16(f) != 0x4D42) {
|
||||||
tmp = read32(f);
|
// magic bytes missing
|
||||||
Serial.print("size 0x");
|
|
||||||
Serial.println(tmp, HEX);
|
|
||||||
|
|
||||||
// read and ignore creator bytes
|
|
||||||
read32(f);
|
|
||||||
|
|
||||||
__Gnbmp_image_offset = read32(f);
|
|
||||||
Serial.print("offset ");
|
|
||||||
Serial.println(__Gnbmp_image_offset, DEC);
|
|
||||||
|
|
||||||
// read DIB header
|
|
||||||
tmp = read32(f);
|
|
||||||
Serial.print("header size ");
|
|
||||||
Serial.println(tmp, DEC);
|
|
||||||
|
|
||||||
int bmp_width = read32(f);
|
|
||||||
int bmp_height = read32(f);
|
|
||||||
|
|
||||||
if(bmp_width != __Gnbmp_width || bmp_height != __Gnbmp_height) // if image is not 320x240, return false
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (read16(f) != 1)
|
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
bmpDepth = read16(f);
|
// read file size
|
||||||
Serial.print("bitdepth ");
|
tmp = read32(f);
|
||||||
Serial.println(bmpDepth, DEC);
|
Serial.print("size 0x");
|
||||||
|
Serial.println(tmp, HEX);
|
||||||
|
|
||||||
if (read32(f) != 0) {
|
// read and ignore creator bytes
|
||||||
// compression not supported!
|
read32(f);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
Serial.print("compression ");
|
__Gnbmp_image_offset = read32(f);
|
||||||
Serial.println(tmp, DEC);
|
Serial.print("offset ");
|
||||||
|
Serial.println(__Gnbmp_image_offset, DEC);
|
||||||
|
|
||||||
return true;
|
// read DIB header
|
||||||
|
tmp = read32(f);
|
||||||
|
Serial.print("header size ");
|
||||||
|
Serial.println(tmp, DEC);
|
||||||
|
|
||||||
|
int bmp_width = read32(f);
|
||||||
|
int bmp_height = read32(f);
|
||||||
|
|
||||||
|
if (bmp_width != __Gnbmp_width || bmp_height != __Gnbmp_height) { // if image is not 320x240, return false
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (read16(f) != 1) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bmpDepth = read16(f);
|
||||||
|
Serial.print("bitdepth ");
|
||||||
|
Serial.println(bmpDepth, DEC);
|
||||||
|
|
||||||
|
if (read32(f) != 0) {
|
||||||
|
// compression not supported!
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.print("compression ");
|
||||||
|
Serial.println(tmp, DEC);
|
||||||
|
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*********************************************/
|
/*********************************************/
|
||||||
@ -323,26 +304,24 @@ boolean bmpReadHeader(File f)
|
|||||||
// (the data is stored in little endian format!)
|
// (the data is stored in little endian format!)
|
||||||
|
|
||||||
// LITTLE ENDIAN!
|
// LITTLE ENDIAN!
|
||||||
uint16_t read16(File f)
|
uint16_t read16(File f) {
|
||||||
{
|
uint16_t d;
|
||||||
uint16_t d;
|
uint8_t b;
|
||||||
uint8_t b;
|
b = f.read();
|
||||||
b = f.read();
|
d = f.read();
|
||||||
d = f.read();
|
d <<= 8;
|
||||||
d <<= 8;
|
d |= b;
|
||||||
d |= b;
|
return d;
|
||||||
return d;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// LITTLE ENDIAN!
|
// LITTLE ENDIAN!
|
||||||
uint32_t read32(File f)
|
uint32_t read32(File f) {
|
||||||
{
|
uint32_t d;
|
||||||
uint32_t d;
|
uint16_t b;
|
||||||
uint16_t b;
|
|
||||||
|
|
||||||
b = read16(f);
|
b = read16(f);
|
||||||
d = read16(f);
|
d = read16(f);
|
||||||
d <<= 16;
|
d <<= 16;
|
||||||
d |= b;
|
d |= b;
|
||||||
return d;
|
return d;
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
Basic Ticker usage
|
Basic Ticker usage
|
||||||
|
|
||||||
Ticker is an object that will call a given function with a certain period.
|
Ticker is an object that will call a given function with a certain period.
|
||||||
Each Ticker calls one function. You can have as many Tickers as you like,
|
Each Ticker calls one function. You can have as many Tickers as you like,
|
||||||
memory being the only limitation.
|
memory being the only limitation.
|
||||||
|
|
||||||
A function may be attached to a ticker and detached from the ticker.
|
A function may be attached to a ticker and detached from the ticker.
|
||||||
There are two variants of the attach function: attach and attach_ms.
|
There are two variants of the attach function: attach and attach_ms.
|
||||||
The first one takes period in seconds, the second one in milliseconds.
|
The first one takes period in seconds, the second one in milliseconds.
|
||||||
|
|
||||||
The built-in LED will be blinking.
|
The built-in LED will be blinking.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@ -18,20 +18,17 @@ Ticker flipper;
|
|||||||
|
|
||||||
int count = 0;
|
int count = 0;
|
||||||
|
|
||||||
void flip()
|
void flip() {
|
||||||
{
|
|
||||||
int state = digitalRead(LED_BUILTIN); // get the current state of GPIO1 pin
|
int state = digitalRead(LED_BUILTIN); // get the current state of GPIO1 pin
|
||||||
digitalWrite(LED_BUILTIN, !state); // set pin to the opposite state
|
digitalWrite(LED_BUILTIN, !state); // set pin to the opposite state
|
||||||
|
|
||||||
++count;
|
++count;
|
||||||
// when the counter reaches a certain value, start blinking like crazy
|
// when the counter reaches a certain value, start blinking like crazy
|
||||||
if (count == 20)
|
if (count == 20) {
|
||||||
{
|
|
||||||
flipper.attach(0.1, flip);
|
flipper.attach(0.1, flip);
|
||||||
}
|
}
|
||||||
// when the counter reaches yet another value, stop blinking
|
// when the counter reaches yet another value, stop blinking
|
||||||
else if (count == 120)
|
else if (count == 120) {
|
||||||
{
|
|
||||||
flipper.detach();
|
flipper.detach();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -39,7 +36,7 @@ void flip()
|
|||||||
void setup() {
|
void setup() {
|
||||||
pinMode(LED_BUILTIN, OUTPUT);
|
pinMode(LED_BUILTIN, OUTPUT);
|
||||||
digitalWrite(LED_BUILTIN, LOW);
|
digitalWrite(LED_BUILTIN, LOW);
|
||||||
|
|
||||||
// flip the pin every 0.3s
|
// flip the pin every 0.3s
|
||||||
flipper.attach(0.3, flip);
|
flipper.attach(0.3, flip);
|
||||||
}
|
}
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
/*
|
/*
|
||||||
Passing paramters to Ticker callbacks
|
Passing paramters to Ticker callbacks
|
||||||
|
|
||||||
Apart from void(void) functions, the Ticker library supports
|
Apart from void(void) functions, the Ticker library supports
|
||||||
functions taking one argument. This argument's size has to be less or
|
functions taking one argument. This argument's size has to be less or
|
||||||
equal to 4 bytes (so char, short, int, float, void*, char* types will do).
|
equal to 4 bytes (so char, short, int, float, void*, char* types will do).
|
||||||
|
|
||||||
This sample runs two tickers that both call one callback function,
|
This sample runs two tickers that both call one callback function,
|
||||||
but with different arguments.
|
but with different arguments.
|
||||||
|
|
||||||
@ -23,10 +23,10 @@ void setPin(int state) {
|
|||||||
void setup() {
|
void setup() {
|
||||||
pinMode(LED_BUILTIN, OUTPUT);
|
pinMode(LED_BUILTIN, OUTPUT);
|
||||||
digitalWrite(1, LOW);
|
digitalWrite(1, LOW);
|
||||||
|
|
||||||
// every 25 ms, call setPin(0)
|
// every 25 ms, call setPin(0)
|
||||||
tickerSetLow.attach_ms(25, setPin, 0);
|
tickerSetLow.attach_ms(25, setPin, 0);
|
||||||
|
|
||||||
// every 26 ms, call setPin(1)
|
// every 26 ms, call setPin(1)
|
||||||
tickerSetHigh.attach_ms(26, setPin, 1);
|
tickerSetHigh.attach_ms(26, setPin, 1);
|
||||||
}
|
}
|
||||||
|
@ -1,12 +1,12 @@
|
|||||||
/*
|
/*
|
||||||
ESP8266 Blink by Simon Peter
|
ESP8266 Blink by Simon Peter
|
||||||
Blink the blue LED on the ESP-01 module
|
Blink the blue LED on the ESP-01 module
|
||||||
This example code is in the public domain
|
This example code is in the public domain
|
||||||
|
|
||||||
The blue LED on the ESP-01 module is connected to GPIO1
|
The blue LED on the ESP-01 module is connected to GPIO1
|
||||||
(which is also the TXD pin; so we cannot use Serial.print() at the same time)
|
(which is also the TXD pin; so we cannot use Serial.print() at the same time)
|
||||||
|
|
||||||
Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
|
Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
|
||||||
*/
|
*/
|
||||||
|
|
||||||
void setup() {
|
void setup() {
|
||||||
@ -16,8 +16,8 @@ void setup() {
|
|||||||
// the loop function runs over and over again forever
|
// the loop function runs over and over again forever
|
||||||
void loop() {
|
void loop() {
|
||||||
digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level
|
digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level
|
||||||
// but actually the LED is on; this is because
|
// but actually the LED is on; this is because
|
||||||
// it is active low on the ESP-01)
|
// it is active low on the ESP-01)
|
||||||
delay(1000); // Wait for a second
|
delay(1000); // Wait for a second
|
||||||
digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH
|
digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH
|
||||||
delay(2000); // Wait for two seconds (to demonstrate the active low LED)
|
delay(2000); // Wait for two seconds (to demonstrate the active low LED)
|
||||||
|
@ -1,16 +1,16 @@
|
|||||||
/*
|
/*
|
||||||
ESP8266 BlinkWithoutDelay by Simon Peter
|
ESP8266 BlinkWithoutDelay by Simon Peter
|
||||||
Blink the blue LED on the ESP-01 module
|
Blink the blue LED on the ESP-01 module
|
||||||
Based on the Arduino Blink without Delay example
|
Based on the Arduino Blink without Delay example
|
||||||
This example code is in the public domain
|
This example code is in the public domain
|
||||||
|
|
||||||
The blue LED on the ESP-01 module is connected to GPIO1
|
The blue LED on the ESP-01 module is connected to GPIO1
|
||||||
(which is also the TXD pin; so we cannot use Serial.print() at the same time)
|
(which is also the TXD pin; so we cannot use Serial.print() at the same time)
|
||||||
|
|
||||||
Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
|
Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
|
||||||
*/
|
*/
|
||||||
|
|
||||||
int ledState = LOW;
|
int ledState = LOW;
|
||||||
|
|
||||||
unsigned long previousMillis = 0;
|
unsigned long previousMillis = 0;
|
||||||
const long interval = 1000;
|
const long interval = 1000;
|
||||||
@ -19,15 +19,15 @@ void setup() {
|
|||||||
pinMode(LED_BUILTIN, OUTPUT);
|
pinMode(LED_BUILTIN, OUTPUT);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
|
||||||
unsigned long currentMillis = millis();
|
unsigned long currentMillis = millis();
|
||||||
if(currentMillis - previousMillis >= interval) {
|
if (currentMillis - previousMillis >= interval) {
|
||||||
previousMillis = currentMillis;
|
previousMillis = currentMillis;
|
||||||
if (ledState == LOW)
|
if (ledState == LOW) {
|
||||||
ledState = HIGH; // Note that this switches the LED *off*
|
ledState = HIGH; // Note that this switches the LED *off*
|
||||||
else
|
} else {
|
||||||
ledState = LOW; // Note that this switches the LED *on*
|
ledState = LOW; // Note that this switches the LED *on*
|
||||||
|
}
|
||||||
digitalWrite(LED_BUILTIN, ledState);
|
digitalWrite(LED_BUILTIN, ledState);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,14 +1,14 @@
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
* NativeSdk by Simon Peter
|
NativeSdk by Simon Peter
|
||||||
* Access functionality from the Espressif ESP8266 SDK
|
Access functionality from the Espressif ESP8266 SDK
|
||||||
* This example code is in the public domain
|
This example code is in the public domain
|
||||||
*
|
|
||||||
* This is for advanced users.
|
This is for advanced users.
|
||||||
* Note that this makes your code dependent on the ESP8266, which is generally
|
Note that this makes your code dependent on the ESP8266, which is generally
|
||||||
* a bad idea. So you should try to use esp8266/Arduino functionality
|
a bad idea. So you should try to use esp8266/Arduino functionality
|
||||||
* where possible instead, in order to abstract away the hardware dependency.
|
where possible instead, in order to abstract away the hardware dependency.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Expose Espressif SDK functionality - wrapped in ifdef so that it still
|
// Expose Espressif SDK functionality - wrapped in ifdef so that it still
|
||||||
// compiles on other platforms
|
// compiles on other platforms
|
||||||
@ -25,9 +25,9 @@ void setup() {
|
|||||||
void loop() {
|
void loop() {
|
||||||
// Call Espressif SDK functionality - wrapped in ifdef so that it still
|
// Call Espressif SDK functionality - wrapped in ifdef so that it still
|
||||||
// compiles on other platforms
|
// compiles on other platforms
|
||||||
#ifdef ESP8266
|
#ifdef ESP8266
|
||||||
Serial.print("wifi_station_get_hostname: ");
|
Serial.print("wifi_station_get_hostname: ");
|
||||||
Serial.println(wifi_station_get_hostname());
|
Serial.println(wifi_station_get_hostname());
|
||||||
#endif
|
#endif
|
||||||
delay(1000);
|
delay(1000);
|
||||||
}
|
}
|
||||||
|
@ -1,32 +1,32 @@
|
|||||||
/*
|
/*
|
||||||
ESP8266 CheckFlashConfig by Markus Sattler
|
ESP8266 CheckFlashConfig by Markus Sattler
|
||||||
|
|
||||||
This sketch tests if the EEPROM settings of the IDE match to the Hardware
|
This sketch tests if the EEPROM settings of the IDE match to the Hardware
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
void setup(void) {
|
void setup(void) {
|
||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void loop() {
|
||||||
|
|
||||||
uint32_t realSize = ESP.getFlashChipRealSize();
|
uint32_t realSize = ESP.getFlashChipRealSize();
|
||||||
uint32_t ideSize = ESP.getFlashChipSize();
|
uint32_t ideSize = ESP.getFlashChipSize();
|
||||||
FlashMode_t ideMode = ESP.getFlashChipMode();
|
FlashMode_t ideMode = ESP.getFlashChipMode();
|
||||||
|
|
||||||
Serial.printf("Flash real id: %08X\n", ESP.getFlashChipId());
|
Serial.printf("Flash real id: %08X\n", ESP.getFlashChipId());
|
||||||
Serial.printf("Flash real size: %u\n\n", realSize);
|
Serial.printf("Flash real size: %u\n\n", realSize);
|
||||||
|
|
||||||
Serial.printf("Flash ide size: %u\n", ideSize);
|
Serial.printf("Flash ide size: %u\n", ideSize);
|
||||||
Serial.printf("Flash ide speed: %u\n", ESP.getFlashChipSpeed());
|
Serial.printf("Flash ide speed: %u\n", ESP.getFlashChipSpeed());
|
||||||
Serial.printf("Flash ide mode: %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN"));
|
Serial.printf("Flash ide mode: %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN"));
|
||||||
|
|
||||||
if(ideSize != realSize) {
|
if (ideSize != realSize) {
|
||||||
Serial.println("Flash Chip configuration wrong!\n");
|
Serial.println("Flash Chip configuration wrong!\n");
|
||||||
} else {
|
} else {
|
||||||
Serial.println("Flash Chip configuration ok.\n");
|
Serial.println("Flash Chip configuration ok.\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
delay(5000);
|
delay(5000);
|
||||||
}
|
}
|
||||||
|
@ -36,8 +36,7 @@
|
|||||||
timeval cbtime; // time set in callback
|
timeval cbtime; // time set in callback
|
||||||
bool cbtime_set = false;
|
bool cbtime_set = false;
|
||||||
|
|
||||||
void time_is_set (void)
|
void time_is_set(void) {
|
||||||
{
|
|
||||||
gettimeofday(&cbtime, NULL);
|
gettimeofday(&cbtime, NULL);
|
||||||
cbtime_set = true;
|
cbtime_set = true;
|
||||||
Serial.println("------------------ settimeofday() was called ------------------");
|
Serial.println("------------------ settimeofday() was called ------------------");
|
||||||
@ -47,7 +46,7 @@ void setup() {
|
|||||||
Serial.begin(115200);
|
Serial.begin(115200);
|
||||||
settimeofday_cb(time_is_set);
|
settimeofday_cb(time_is_set);
|
||||||
|
|
||||||
#if NTP0_OR_LOCAL1
|
#if NTP0_OR_LOCAL1
|
||||||
// local
|
// local
|
||||||
|
|
||||||
ESP.eraseConfig();
|
ESP.eraseConfig();
|
||||||
@ -56,14 +55,14 @@ void setup() {
|
|||||||
timezone tz = { TZ_MN + DST_MN, 0 };
|
timezone tz = { TZ_MN + DST_MN, 0 };
|
||||||
settimeofday(&tv, &tz);
|
settimeofday(&tv, &tz);
|
||||||
|
|
||||||
#else // ntp
|
#else // ntp
|
||||||
|
|
||||||
configTime(TZ_SEC, DST_SEC, "pool.ntp.org");
|
configTime(TZ_SEC, DST_SEC, "pool.ntp.org");
|
||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.begin(SSID, SSIDPWD);
|
WiFi.begin(SSID, SSIDPWD);
|
||||||
// don't wait, observe time changing when ntp timestamp is received
|
// don't wait, observe time changing when ntp timestamp is received
|
||||||
|
|
||||||
#endif // ntp
|
#endif // ntp
|
||||||
}
|
}
|
||||||
|
|
||||||
// for testing purpose:
|
// for testing purpose:
|
||||||
@ -73,7 +72,7 @@ extern "C" int clock_gettime(clockid_t unused, struct timespec *tp);
|
|||||||
Serial.print(":" #w "="); \
|
Serial.print(":" #w "="); \
|
||||||
Serial.print(tm->tm_##w);
|
Serial.print(tm->tm_##w);
|
||||||
|
|
||||||
void printTm (const char* what, const tm* tm) {
|
void printTm(const char* what, const tm* tm) {
|
||||||
Serial.print(what);
|
Serial.print(what);
|
||||||
PTM(isdst); PTM(yday); PTM(wday);
|
PTM(isdst); PTM(yday); PTM(wday);
|
||||||
PTM(year); PTM(mon); PTM(mday);
|
PTM(year); PTM(mon); PTM(mday);
|
||||||
|
@ -38,15 +38,14 @@ void setup() {
|
|||||||
Serial.println("Read: ");
|
Serial.println("Read: ");
|
||||||
printMemory();
|
printMemory();
|
||||||
Serial.println();
|
Serial.println();
|
||||||
uint32_t crcOfData = calculateCRC32( (uint8_t*) &rtcData.data[0], sizeof(rtcData.data) );
|
uint32_t crcOfData = calculateCRC32((uint8_t*) &rtcData.data[0], sizeof(rtcData.data));
|
||||||
Serial.print("CRC32 of data: ");
|
Serial.print("CRC32 of data: ");
|
||||||
Serial.println(crcOfData, HEX);
|
Serial.println(crcOfData, HEX);
|
||||||
Serial.print("CRC32 read from RTC: ");
|
Serial.print("CRC32 read from RTC: ");
|
||||||
Serial.println(rtcData.crc32, HEX);
|
Serial.println(rtcData.crc32, HEX);
|
||||||
if (crcOfData != rtcData.crc32) {
|
if (crcOfData != rtcData.crc32) {
|
||||||
Serial.println("CRC32 in RTC memory doesn't match CRC32 of data. Data is probably invalid!");
|
Serial.println("CRC32 in RTC memory doesn't match CRC32 of data. Data is probably invalid!");
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
Serial.println("CRC32 check ok, data is probably valid.");
|
Serial.println("CRC32 check ok, data is probably valid.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -56,7 +55,7 @@ void setup() {
|
|||||||
rtcData.data[i] = random(0, 128);
|
rtcData.data[i] = random(0, 128);
|
||||||
}
|
}
|
||||||
// Update CRC32 of data
|
// Update CRC32 of data
|
||||||
rtcData.crc32 = calculateCRC32( (uint8_t*) &rtcData.data[0], sizeof(rtcData.data) );
|
rtcData.crc32 = calculateCRC32((uint8_t*) &rtcData.data[0], sizeof(rtcData.data));
|
||||||
// Write struct to RTC memory
|
// Write struct to RTC memory
|
||||||
if (ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtcData, sizeof(rtcData))) {
|
if (ESP.rtcUserMemoryWrite(0, (uint32_t*) &rtcData, sizeof(rtcData))) {
|
||||||
Serial.println("Write: ");
|
Serial.println("Write: ");
|
||||||
@ -71,8 +70,7 @@ void setup() {
|
|||||||
void loop() {
|
void loop() {
|
||||||
}
|
}
|
||||||
|
|
||||||
uint32_t calculateCRC32(const uint8_t *data, size_t length)
|
uint32_t calculateCRC32(const uint8_t *data, size_t length) {
|
||||||
{
|
|
||||||
uint32_t crc = 0xffffffff;
|
uint32_t crc = 0xffffffff;
|
||||||
while (length--) {
|
while (length--) {
|
||||||
uint8_t c = *data++;
|
uint8_t c = *data++;
|
||||||
@ -99,8 +97,7 @@ void printMemory() {
|
|||||||
Serial.print(buf);
|
Serial.print(buf);
|
||||||
if ((i + 1) % 32 == 0) {
|
if ((i + 1) % 32 == 0) {
|
||||||
Serial.println();
|
Serial.println();
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
Serial.print(" ");
|
Serial.print(" ");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
/**
|
/**
|
||||||
* TestEspApi by Max Vilimpoc
|
TestEspApi by Max Vilimpoc
|
||||||
* This code is released to the public domain.
|
This code is released to the public domain.
|
||||||
*
|
|
||||||
* Test out the Expressif ESP8266 Non-OS API, exhaustively trying out
|
Test out the Expressif ESP8266 Non-OS API, exhaustively trying out
|
||||||
* as many of the built-in functions as possible.
|
as many of the built-in functions as possible.
|
||||||
*
|
|
||||||
* Some of the code is based on examples in:
|
Some of the code is based on examples in:
|
||||||
* "20A-ESP8266__RTOS_SDK__Programming Guide__EN_v1.3.0.pdf"
|
"20A-ESP8266__RTOS_SDK__Programming Guide__EN_v1.3.0.pdf"
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#ifdef ESP8266
|
#ifdef ESP8266
|
||||||
extern "C" {
|
extern "C" {
|
||||||
@ -23,291 +23,274 @@ Stream& ehConsolePort(Serial);
|
|||||||
// Wired to the blue LED on an ESP-01 board, active LOW.
|
// Wired to the blue LED on an ESP-01 board, active LOW.
|
||||||
//
|
//
|
||||||
// Cannot be used simultaneously with Serial.print/println()
|
// Cannot be used simultaneously with Serial.print/println()
|
||||||
// calls, as TX is wired to the same pin.
|
// calls, as TX is wired to the same pin.
|
||||||
//
|
//
|
||||||
// UNLESS: You swap the TX pin using the alternate pinout.
|
// UNLESS: You swap the TX pin using the alternate pinout.
|
||||||
const uint8_t LED_PIN = 1;
|
const uint8_t LED_PIN = 1;
|
||||||
|
|
||||||
const char * const RST_REASONS[] =
|
const char * const RST_REASONS[] = {
|
||||||
{
|
"REASON_DEFAULT_RST",
|
||||||
"REASON_DEFAULT_RST",
|
"REASON_WDT_RST",
|
||||||
"REASON_WDT_RST",
|
"REASON_EXCEPTION_RST",
|
||||||
"REASON_EXCEPTION_RST",
|
"REASON_SOFT_WDT_RST",
|
||||||
"REASON_SOFT_WDT_RST",
|
"REASON_SOFT_RESTART",
|
||||||
"REASON_SOFT_RESTART",
|
"REASON_DEEP_SLEEP_AWAKE",
|
||||||
"REASON_DEEP_SLEEP_AWAKE",
|
"REASON_EXT_SYS_RST"
|
||||||
"REASON_EXT_SYS_RST"
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const char * const FLASH_SIZE_MAP_NAMES[] =
|
const char * const FLASH_SIZE_MAP_NAMES[] = {
|
||||||
{
|
"FLASH_SIZE_4M_MAP_256_256",
|
||||||
"FLASH_SIZE_4M_MAP_256_256",
|
"FLASH_SIZE_2M",
|
||||||
"FLASH_SIZE_2M",
|
"FLASH_SIZE_8M_MAP_512_512",
|
||||||
"FLASH_SIZE_8M_MAP_512_512",
|
"FLASH_SIZE_16M_MAP_512_512",
|
||||||
"FLASH_SIZE_16M_MAP_512_512",
|
"FLASH_SIZE_32M_MAP_512_512",
|
||||||
"FLASH_SIZE_32M_MAP_512_512",
|
"FLASH_SIZE_16M_MAP_1024_1024",
|
||||||
"FLASH_SIZE_16M_MAP_1024_1024",
|
"FLASH_SIZE_32M_MAP_1024_1024"
|
||||||
"FLASH_SIZE_32M_MAP_1024_1024"
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const char * const OP_MODE_NAMES[]
|
const char * const OP_MODE_NAMES[] {
|
||||||
{
|
"NULL_MODE",
|
||||||
"NULL_MODE",
|
"STATION_MODE",
|
||||||
"STATION_MODE",
|
"SOFTAP_MODE",
|
||||||
"SOFTAP_MODE",
|
"STATIONAP_MODE"
|
||||||
"STATIONAP_MODE"
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const char * const AUTH_MODE_NAMES[]
|
const char * const AUTH_MODE_NAMES[] {
|
||||||
{
|
"AUTH_OPEN",
|
||||||
"AUTH_OPEN",
|
"AUTH_WEP",
|
||||||
"AUTH_WEP",
|
"AUTH_WPA_PSK",
|
||||||
"AUTH_WPA_PSK",
|
"AUTH_WPA2_PSK",
|
||||||
"AUTH_WPA2_PSK",
|
"AUTH_WPA_WPA2_PSK",
|
||||||
"AUTH_WPA_WPA2_PSK",
|
"AUTH_MAX"
|
||||||
"AUTH_MAX"
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const char * const PHY_MODE_NAMES[]
|
const char * const PHY_MODE_NAMES[] {
|
||||||
{
|
"",
|
||||||
"",
|
"PHY_MODE_11B",
|
||||||
"PHY_MODE_11B",
|
"PHY_MODE_11G",
|
||||||
"PHY_MODE_11G",
|
"PHY_MODE_11N"
|
||||||
"PHY_MODE_11N"
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const char * const EVENT_NAMES[]
|
const char * const EVENT_NAMES[] {
|
||||||
{
|
"EVENT_STAMODE_CONNECTED",
|
||||||
"EVENT_STAMODE_CONNECTED",
|
"EVENT_STAMODE_DISCONNECTED",
|
||||||
"EVENT_STAMODE_DISCONNECTED",
|
"EVENT_STAMODE_AUTHMODE_CHANGE",
|
||||||
"EVENT_STAMODE_AUTHMODE_CHANGE",
|
"EVENT_STAMODE_GOT_IP",
|
||||||
"EVENT_STAMODE_GOT_IP",
|
"EVENT_SOFTAPMODE_STACONNECTED",
|
||||||
"EVENT_SOFTAPMODE_STACONNECTED",
|
"EVENT_SOFTAPMODE_STADISCONNECTED",
|
||||||
"EVENT_SOFTAPMODE_STADISCONNECTED",
|
"EVENT_MAX"
|
||||||
"EVENT_MAX"
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const char * const EVENT_REASONS[]
|
const char * const EVENT_REASONS[] {
|
||||||
{
|
"",
|
||||||
"",
|
"REASON_UNSPECIFIED",
|
||||||
"REASON_UNSPECIFIED",
|
"REASON_AUTH_EXPIRE",
|
||||||
"REASON_AUTH_EXPIRE",
|
"REASON_AUTH_LEAVE",
|
||||||
"REASON_AUTH_LEAVE",
|
"REASON_ASSOC_EXPIRE",
|
||||||
"REASON_ASSOC_EXPIRE",
|
"REASON_ASSOC_TOOMANY",
|
||||||
"REASON_ASSOC_TOOMANY",
|
"REASON_NOT_AUTHED",
|
||||||
"REASON_NOT_AUTHED",
|
"REASON_NOT_ASSOCED",
|
||||||
"REASON_NOT_ASSOCED",
|
"REASON_ASSOC_LEAVE",
|
||||||
"REASON_ASSOC_LEAVE",
|
"REASON_ASSOC_NOT_AUTHED",
|
||||||
"REASON_ASSOC_NOT_AUTHED",
|
"REASON_DISASSOC_PWRCAP_BAD",
|
||||||
"REASON_DISASSOC_PWRCAP_BAD",
|
"REASON_DISASSOC_SUPCHAN_BAD",
|
||||||
"REASON_DISASSOC_SUPCHAN_BAD",
|
"REASON_IE_INVALID",
|
||||||
"REASON_IE_INVALID",
|
"REASON_MIC_FAILURE",
|
||||||
"REASON_MIC_FAILURE",
|
"REASON_4WAY_HANDSHAKE_TIMEOUT",
|
||||||
"REASON_4WAY_HANDSHAKE_TIMEOUT",
|
"REASON_GROUP_KEY_UPDATE_TIMEOUT",
|
||||||
"REASON_GROUP_KEY_UPDATE_TIMEOUT",
|
"REASON_IE_IN_4WAY_DIFFERS",
|
||||||
"REASON_IE_IN_4WAY_DIFFERS",
|
"REASON_GROUP_CIPHER_INVALID",
|
||||||
"REASON_GROUP_CIPHER_INVALID",
|
"REASON_PAIRWISE_CIPHER_INVALID",
|
||||||
"REASON_PAIRWISE_CIPHER_INVALID",
|
"REASON_AKMP_INVALID",
|
||||||
"REASON_AKMP_INVALID",
|
"REASON_UNSUPP_RSN_IE_VERSION",
|
||||||
"REASON_UNSUPP_RSN_IE_VERSION",
|
"REASON_INVALID_RSN_IE_CAP",
|
||||||
"REASON_INVALID_RSN_IE_CAP",
|
"REASON_802_1X_AUTH_FAILED",
|
||||||
"REASON_802_1X_AUTH_FAILED",
|
"REASON_CIPHER_SUITE_REJECTED",
|
||||||
"REASON_CIPHER_SUITE_REJECTED",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const char * const EVENT_REASONS_200[]
|
const char * const EVENT_REASONS_200[] {
|
||||||
{
|
"REASON_BEACON_TIMEOUT",
|
||||||
"REASON_BEACON_TIMEOUT",
|
"REASON_NO_AP_FOUND"
|
||||||
"REASON_NO_AP_FOUND"
|
|
||||||
};
|
};
|
||||||
|
|
||||||
void wifi_event_handler_cb(System_Event_t * event)
|
void wifi_event_handler_cb(System_Event_t * event) {
|
||||||
{
|
ehConsolePort.print(EVENT_NAMES[event->event]);
|
||||||
ehConsolePort.print(EVENT_NAMES[event->event]);
|
ehConsolePort.print(" (");
|
||||||
ehConsolePort.print(" (");
|
|
||||||
|
|
||||||
switch (event->event)
|
|
||||||
{
|
|
||||||
case EVENT_STAMODE_CONNECTED:
|
|
||||||
break;
|
|
||||||
case EVENT_STAMODE_DISCONNECTED:
|
|
||||||
break;
|
|
||||||
case EVENT_STAMODE_AUTHMODE_CHANGE:
|
|
||||||
break;
|
|
||||||
case EVENT_STAMODE_GOT_IP:
|
|
||||||
break;
|
|
||||||
case EVENT_SOFTAPMODE_STACONNECTED:
|
|
||||||
case EVENT_SOFTAPMODE_STADISCONNECTED:
|
|
||||||
{
|
|
||||||
char mac[32] = {0};
|
|
||||||
snprintf(mac, 32, MACSTR ", aid: %d" , MAC2STR(event->event_info.sta_connected.mac), event->event_info.sta_connected.aid);
|
|
||||||
|
|
||||||
ehConsolePort.print(mac);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
ehConsolePort.println(")");
|
switch (event->event) {
|
||||||
|
case EVENT_STAMODE_CONNECTED:
|
||||||
|
break;
|
||||||
|
case EVENT_STAMODE_DISCONNECTED:
|
||||||
|
break;
|
||||||
|
case EVENT_STAMODE_AUTHMODE_CHANGE:
|
||||||
|
break;
|
||||||
|
case EVENT_STAMODE_GOT_IP:
|
||||||
|
break;
|
||||||
|
case EVENT_SOFTAPMODE_STACONNECTED:
|
||||||
|
case EVENT_SOFTAPMODE_STADISCONNECTED: {
|
||||||
|
char mac[32] = {0};
|
||||||
|
snprintf(mac, 32, MACSTR ", aid: %d", MAC2STR(event->event_info.sta_connected.mac), event->event_info.sta_connected.aid);
|
||||||
|
|
||||||
|
ehConsolePort.print(mac);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
ehConsolePort.println(")");
|
||||||
}
|
}
|
||||||
|
|
||||||
void print_softap_config(Stream & consolePort, softap_config const& config)
|
void print_softap_config(Stream & consolePort, softap_config const& config) {
|
||||||
{
|
consolePort.println();
|
||||||
consolePort.println();
|
consolePort.println(F("SoftAP Configuration"));
|
||||||
consolePort.println(F("SoftAP Configuration"));
|
consolePort.println(F("--------------------"));
|
||||||
consolePort.println(F("--------------------"));
|
|
||||||
|
|
||||||
consolePort.print(F("ssid: "));
|
consolePort.print(F("ssid: "));
|
||||||
consolePort.println((char *) config.ssid);
|
consolePort.println((char *) config.ssid);
|
||||||
|
|
||||||
consolePort.print(F("password: "));
|
consolePort.print(F("password: "));
|
||||||
consolePort.println((char *) config.password);
|
consolePort.println((char *) config.password);
|
||||||
|
|
||||||
consolePort.print(F("ssid_len: "));
|
consolePort.print(F("ssid_len: "));
|
||||||
consolePort.println(config.ssid_len);
|
consolePort.println(config.ssid_len);
|
||||||
|
|
||||||
consolePort.print(F("channel: "));
|
consolePort.print(F("channel: "));
|
||||||
consolePort.println(config.channel);
|
consolePort.println(config.channel);
|
||||||
|
|
||||||
consolePort.print(F("authmode: "));
|
consolePort.print(F("authmode: "));
|
||||||
consolePort.println(AUTH_MODE_NAMES[config.authmode]);
|
consolePort.println(AUTH_MODE_NAMES[config.authmode]);
|
||||||
|
|
||||||
consolePort.print(F("ssid_hidden: "));
|
consolePort.print(F("ssid_hidden: "));
|
||||||
consolePort.println(config.ssid_hidden);
|
consolePort.println(config.ssid_hidden);
|
||||||
|
|
||||||
consolePort.print(F("max_connection: "));
|
consolePort.print(F("max_connection: "));
|
||||||
consolePort.println(config.max_connection);
|
consolePort.println(config.max_connection);
|
||||||
|
|
||||||
consolePort.print(F("beacon_interval: "));
|
consolePort.print(F("beacon_interval: "));
|
||||||
consolePort.print(config.beacon_interval);
|
consolePort.print(config.beacon_interval);
|
||||||
consolePort.println("ms");
|
consolePort.println("ms");
|
||||||
|
|
||||||
consolePort.println(F("--------------------"));
|
consolePort.println(F("--------------------"));
|
||||||
consolePort.println();
|
consolePort.println();
|
||||||
}
|
}
|
||||||
|
|
||||||
void print_system_info(Stream & consolePort)
|
void print_system_info(Stream & consolePort) {
|
||||||
{
|
const rst_info * resetInfo = system_get_rst_info();
|
||||||
const rst_info * resetInfo = system_get_rst_info();
|
consolePort.print(F("system_get_rst_info() reset reason: "));
|
||||||
consolePort.print(F("system_get_rst_info() reset reason: "));
|
consolePort.println(RST_REASONS[resetInfo->reason]);
|
||||||
consolePort.println(RST_REASONS[resetInfo->reason]);
|
|
||||||
|
|
||||||
consolePort.print(F("system_get_free_heap_size(): "));
|
consolePort.print(F("system_get_free_heap_size(): "));
|
||||||
consolePort.println(system_get_free_heap_size());
|
consolePort.println(system_get_free_heap_size());
|
||||||
|
|
||||||
consolePort.print(F("system_get_os_print(): "));
|
consolePort.print(F("system_get_os_print(): "));
|
||||||
consolePort.println(system_get_os_print());
|
consolePort.println(system_get_os_print());
|
||||||
system_set_os_print(1);
|
system_set_os_print(1);
|
||||||
consolePort.print(F("system_get_os_print(): "));
|
consolePort.print(F("system_get_os_print(): "));
|
||||||
consolePort.println(system_get_os_print());
|
consolePort.println(system_get_os_print());
|
||||||
|
|
||||||
system_print_meminfo();
|
system_print_meminfo();
|
||||||
|
|
||||||
consolePort.print(F("system_get_chip_id(): 0x"));
|
consolePort.print(F("system_get_chip_id(): 0x"));
|
||||||
consolePort.println(system_get_chip_id(), HEX);
|
consolePort.println(system_get_chip_id(), HEX);
|
||||||
|
|
||||||
consolePort.print(F("system_get_sdk_version(): "));
|
consolePort.print(F("system_get_sdk_version(): "));
|
||||||
consolePort.println(system_get_sdk_version());
|
consolePort.println(system_get_sdk_version());
|
||||||
|
|
||||||
consolePort.print(F("system_get_boot_version(): "));
|
consolePort.print(F("system_get_boot_version(): "));
|
||||||
consolePort.println(system_get_boot_version());
|
consolePort.println(system_get_boot_version());
|
||||||
|
|
||||||
consolePort.print(F("system_get_userbin_addr(): 0x"));
|
consolePort.print(F("system_get_userbin_addr(): 0x"));
|
||||||
consolePort.println(system_get_userbin_addr(), HEX);
|
consolePort.println(system_get_userbin_addr(), HEX);
|
||||||
|
|
||||||
consolePort.print(F("system_get_boot_mode(): "));
|
consolePort.print(F("system_get_boot_mode(): "));
|
||||||
consolePort.println(system_get_boot_mode() == 0 ? F("SYS_BOOT_ENHANCE_MODE") : F("SYS_BOOT_NORMAL_MODE"));
|
consolePort.println(system_get_boot_mode() == 0 ? F("SYS_BOOT_ENHANCE_MODE") : F("SYS_BOOT_NORMAL_MODE"));
|
||||||
|
|
||||||
consolePort.print(F("system_get_cpu_freq(): "));
|
consolePort.print(F("system_get_cpu_freq(): "));
|
||||||
consolePort.println(system_get_cpu_freq());
|
consolePort.println(system_get_cpu_freq());
|
||||||
|
|
||||||
consolePort.print(F("system_get_flash_size_map(): "));
|
consolePort.print(F("system_get_flash_size_map(): "));
|
||||||
consolePort.println(FLASH_SIZE_MAP_NAMES[system_get_flash_size_map()]);
|
consolePort.println(FLASH_SIZE_MAP_NAMES[system_get_flash_size_map()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
void print_wifi_general(Stream & consolePort)
|
void print_wifi_general(Stream & consolePort) {
|
||||||
{
|
consolePort.print(F("wifi_get_channel(): "));
|
||||||
consolePort.print(F("wifi_get_channel(): "));
|
consolePort.println(wifi_get_channel());
|
||||||
consolePort.println(wifi_get_channel());
|
|
||||||
|
consolePort.print(F("wifi_get_phy_mode(): "));
|
||||||
consolePort.print(F("wifi_get_phy_mode(): "));
|
consolePort.println(PHY_MODE_NAMES[wifi_get_phy_mode()]);
|
||||||
consolePort.println(PHY_MODE_NAMES[wifi_get_phy_mode()]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void secure_softap_config(softap_config * config, const char * ssid, const char * password)
|
void secure_softap_config(softap_config * config, const char * ssid, const char * password) {
|
||||||
{
|
size_t ssidLen = strlen(ssid) < sizeof(config->ssid) ? strlen(ssid) : sizeof(config->ssid);
|
||||||
size_t ssidLen = strlen(ssid) < sizeof(config->ssid) ? strlen(ssid) : sizeof(config->ssid);
|
size_t passwordLen = strlen(password) < sizeof(config->password) ? strlen(password) : sizeof(config->password);
|
||||||
size_t passwordLen = strlen(password) < sizeof(config->password) ? strlen(password) : sizeof(config->password);
|
|
||||||
|
|
||||||
memset(config->ssid, 0, sizeof(config->ssid));
|
memset(config->ssid, 0, sizeof(config->ssid));
|
||||||
memcpy(config->ssid, ssid, ssidLen);
|
memcpy(config->ssid, ssid, ssidLen);
|
||||||
|
|
||||||
memset(config->password, 0, sizeof(config->password));
|
memset(config->password, 0, sizeof(config->password));
|
||||||
memcpy(config->password, password, passwordLen);
|
memcpy(config->password, password, passwordLen);
|
||||||
|
|
||||||
config->ssid_len = ssidLen;
|
config->ssid_len = ssidLen;
|
||||||
config->channel = 1;
|
config->channel = 1;
|
||||||
config->authmode = AUTH_WPA2_PSK;
|
config->authmode = AUTH_WPA2_PSK;
|
||||||
// config->ssid_hidden = 1;
|
// config->ssid_hidden = 1;
|
||||||
config->max_connection = 4;
|
config->max_connection = 4;
|
||||||
// config->beacon_interval = 1000;
|
// config->beacon_interval = 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup()
|
void setup() {
|
||||||
{
|
// Reuse default Serial port rate, so the bootloader
|
||||||
// Reuse default Serial port rate, so the bootloader
|
// messages are also readable.
|
||||||
// messages are also readable.
|
|
||||||
|
|
||||||
Serial.begin(74880);
|
|
||||||
|
|
||||||
// Try pushing frequency to 160MHz.
|
Serial.begin(74880);
|
||||||
system_update_cpu_freq(SYS_CPU_160MHZ);
|
|
||||||
|
|
||||||
Serial.println();
|
// Try pushing frequency to 160MHz.
|
||||||
Serial.println(F("ESP starting."));
|
system_update_cpu_freq(SYS_CPU_160MHZ);
|
||||||
|
|
||||||
// System usually boots up in about 200ms.
|
Serial.println();
|
||||||
|
Serial.println(F("ESP starting."));
|
||||||
Serial.print(F("system_get_time(): "));
|
|
||||||
Serial.println(system_get_time());
|
|
||||||
|
|
||||||
// set_event_handler_cb_stream(Serial);
|
// System usually boots up in about 200ms.
|
||||||
wifi_set_event_handler_cb(wifi_event_handler_cb);
|
|
||||||
|
|
||||||
print_system_info(Serial);
|
Serial.print(F("system_get_time(): "));
|
||||||
|
Serial.println(system_get_time());
|
||||||
|
|
||||||
Serial.print(F("wifi_get_opmode(): "));
|
// set_event_handler_cb_stream(Serial);
|
||||||
Serial.print(wifi_get_opmode());
|
wifi_set_event_handler_cb(wifi_event_handler_cb);
|
||||||
Serial.print(F(" - "));
|
|
||||||
Serial.println(OP_MODE_NAMES[wifi_get_opmode()]);
|
|
||||||
|
|
||||||
Serial.print(F("wifi_get_opmode_default(): "));
|
print_system_info(Serial);
|
||||||
Serial.print(wifi_get_opmode_default());
|
|
||||||
Serial.print(F(" - "));
|
|
||||||
Serial.println(OP_MODE_NAMES[wifi_get_opmode_default()]);
|
|
||||||
|
|
||||||
Serial.print(F("wifi_get_broadcast_if(): "));
|
Serial.print(F("wifi_get_opmode(): "));
|
||||||
Serial.println(wifi_get_broadcast_if());
|
Serial.print(wifi_get_opmode());
|
||||||
|
Serial.print(F(" - "));
|
||||||
|
Serial.println(OP_MODE_NAMES[wifi_get_opmode()]);
|
||||||
|
|
||||||
softap_config config;
|
Serial.print(F("wifi_get_opmode_default(): "));
|
||||||
wifi_softap_get_config(&config);
|
Serial.print(wifi_get_opmode_default());
|
||||||
secure_softap_config(&config, "TestAP", "testtesttest");
|
Serial.print(F(" - "));
|
||||||
wifi_softap_set_config(&config);
|
Serial.println(OP_MODE_NAMES[wifi_get_opmode_default()]);
|
||||||
print_softap_config(Serial, config);
|
|
||||||
|
|
||||||
print_wifi_general(Serial);
|
Serial.print(F("wifi_get_broadcast_if(): "));
|
||||||
|
Serial.println(wifi_get_broadcast_if());
|
||||||
|
|
||||||
// This doesn't work on an ESP-01.
|
softap_config config;
|
||||||
// wifi_set_sleep_type(LIGHT_SLEEP_T);
|
wifi_softap_get_config(&config);
|
||||||
|
secure_softap_config(&config, "TestAP", "testtesttest");
|
||||||
|
wifi_softap_set_config(&config);
|
||||||
|
print_softap_config(Serial, config);
|
||||||
|
|
||||||
// Try this dirty little thing.
|
print_wifi_general(Serial);
|
||||||
// Doesn't work because ESP-01 module doesn't link XPD_DCDC -> RST.
|
|
||||||
// ESP.deepSleep(15000);
|
// This doesn't work on an ESP-01.
|
||||||
|
// wifi_set_sleep_type(LIGHT_SLEEP_T);
|
||||||
|
|
||||||
|
// Try this dirty little thing.
|
||||||
|
// Doesn't work because ESP-01 module doesn't link XPD_DCDC -> RST.
|
||||||
|
// ESP.deepSleep(15000);
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop()
|
void loop() {
|
||||||
{
|
Serial.print(F("system_get_time(): "));
|
||||||
Serial.print(F("system_get_time(): "));
|
Serial.println(system_get_time());
|
||||||
Serial.println(system_get_time());
|
delay(1000);
|
||||||
delay(1000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user