Skip to content

Instantly share code, notes, and snippets.

@ThomasStuetz
Last active February 19, 2018 14:49
Show Gist options
  • Save ThomasStuetz/5dea1f4cd60b5b0f19d6fd3176d95ec9 to your computer and use it in GitHub Desktop.
Save ThomasStuetz/5dea1f4cd60b5b0f19d6fd3176d95ec9 to your computer and use it in GitHub Desktop.
PlatformIO

PlatformIO

PH-Seminar ESP8266 und Android

#include <ESP8266WebServer.h>
#include <ESP8266WiFi.h>
#include <WiFiManager.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN D1 // Pin which is connected to the DHT sensor.
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT_Unified dht(DHTPIN, DHTTYPE);
uint32_t delayMS;
// Webserver läuft auf Port 80 und wartet auf Requests
ESP8266WebServer esp8266WebServer(80);
/*************************************** Callback-Funktionen für den Webserver ******************************/
/**
* Verarbeitung der Übermittlung der WLAN-Zugangsdaten
*/
void handleWifiConnectionArgs() {
Serial.println("F(handleWifiConnectionArgs())");
char* ssid =new char[20];
char* password = new char[20];
const char* response;
String ssidPar = esp8266WebServer.arg("ssid");
String passwordPar = esp8266WebServer.arg("password");
bool ok = true;
if (ssidPar.equals("")){ //Parameter not found
response = "ssid not found";
ok=false;
}
else{ //ssid found
if(passwordPar.equals("")){
response = "password not found";
ok=false;
}
else{
ssidPar.toCharArray(ssid,19);
passwordPar.toCharArray(password, 19);
response = "Restart Wifi-Connection with user and password!";
}
}
esp8266WebServer.send( 200, "text/html", response); //Returns the HTTP response
delay(2000); // Damit die Meldung am Browser ankommt
WiFiManager wifiManager;
WiFi.begin(ssid, password);
}
/*
Umwandlung einer Hexziffer (0-15) in das Hexzeichen (0-F)
*/
char getHexChar(int digit) {
if (digit < 10) {
return '0' + digit;
}
return 'A' + digit - 10;
}
/*
MAC-Adresse in entsprechenden String umwandeln
und in übergebenes char[] speichern
*/
void getMacAddress(char hexChars[]) {
uint8_t *bssid = WiFi.BSSID();
for (int i = 0; i < 6; i++) {
hexChars[i * 3] = getHexChar(bssid[i] / 16);
hexChars[i * 3 + 1] = getHexChar(bssid[i] % 16);
hexChars[i * 3 + 2] = ':';
}
hexChars[17] = 0;
}
/*
ESP meldet Statusinformationen, wie WLAN-Funk-Feldstärke oder
freien Heap-Speicher
*/
void handleStateRequest() {
char hexChars[18];
char response[50];
getMacAddress(hexChars);
sprintf(response, "espMacAddress: %s, wifiStrength: %d, freeHeap: %d",
hexChars, WiFi.RSSI(), ESP.getFreeHeap());
Serial.print("State: ");
Serial.print(response);
//Returns the HTTP response
esp8266WebServer.send( 200, "text/html", response);
}
// /*
// ESP meldet Statusinformationen, wie WLAN-Funk-Feldstärke oder
// freien Heap-Speicher
// */
// void handleStateRequest() {
// char hexChars[18];
// getMacAddress(hexChars);
// String response = "espMacAddress:" + String(hexChars) +
// ", wifiStrength:" + String(WiFi.RSSI()) +
// ", freeHeap:" + String(ESP.getFreeHeap());
// Serial.print("State: ");
// Serial.println(response);
// //Returns the HTTP response
// esp8266WebServer.send( 200, "text/html", response);
// }
/*
Ausgabe der aktuellen Temperatur und Luftfeuchtigkeit.
*/
void handleDhtRequest() {
String response;
sensors_event_t event;
dht.temperature().getEvent(&event);
if (isnan(event.temperature)) {
Serial.println("Error reading temperature!");
}
else {
response = "Temperature "+String(event.temperature)+" Grad ";
}
// Get humidity event and print its value.
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
Serial.println("Error reading humidity!");
}
else {
response = response + "Humidity: "+ String(event.relative_humidity)+"%";
}
Serial.print("DHT22: ");
Serial.println(response);
esp8266WebServer.send( 200, "text/html", response); //Returns the HTTP response
}
/*
Credentials für das WLAN werden zurückgesetzt
*/
void handleResetWifi() {
const char* response = "Wifi-Connection reset settings, reboot ESP";
esp8266WebServer.send( 200, "text/html", response); //Returns the HTTP response
delay(1000);
WiFiManager wifiManager;
wifiManager.resetSettings();
}
/*************************************** Setup ******************************/
void setup() {
Serial.begin(115200); //Initialisierung der seriellen Schnittstelle
Serial.println();
Serial.println();
Serial.println("HttpServerTest");
Serial.println("==============");
WiFiManager wifiManager; // WiFiManager anlegen
char hexChars[18]; // Macadresse ermitteln
getMacAddress(hexChars);
char apName[25];
sprintf(apName, "ESP_%s", hexChars); // SSID zusammenstoppeln
wifiManager.setConfigPortalTimeout(240);
if (!wifiManager.autoConnect(apName)) // gecachte Credentials werden verwendet
{
Serial.println(F("Failed to connect. Reset and try again..."));
delay(3000);
ESP.reset(); //reset and try again
delay(5000);
}
delay(100);
Serial.println(F("Connected to WiFi!"));
Serial.println("Webserver als Echoserver starten");
esp8266WebServer.on("/wifi", handleWifiConnectionArgs); // WLAN-Zugangsdaten per Web setzen
esp8266WebServer.on("/resetwifi", handleResetWifi); // WiFiManager resetten
esp8266WebServer.on("/state", handleStateRequest); // WiFiManager resetten
esp8266WebServer.on("/dht", handleDhtRequest); // Dht22 abfragen
esp8266WebServer.begin();
dht.begin();
}
/*************************************** Loop ******************************/
void loop() {
esp8266WebServer.handleClient();
delay(1); // braucht RTOS zur Bearbeitung der Wifi-Schnittstelle
// yield(); // geht auch
}
[platformio]
lib_extra_dirs = /opt/iot2018ph/libraries,D:\iot2018ph\seminar\libraries
[env:d1_mini]
platform = espressif8266
board = d1_mini
framework = arduino
upload_speed = 230400
;upload_speed = 115200
;upload_speed = 460800
;upload_speed = 921600
; Custom Serial Monitor baud rate
monitor_baud = 115200
;upload_port = 192.168.0.12
//InternLed.cpp
#include "InternLed.h" // "" für gleiches Verzeichnis
#define FAST_PERIOD_MS 150
#define SLOW_PERIOD_MS 750
//#define ACTIVATE_DEBUG
#ifdef ACTIVATE_DEBUG
# define D(x) x
#else
# define D(x)
#endif // ACTIVATE_DEBUG
InternLedClass::InternLedClass() { _ticker = new Ticker();}
Ticker* InternLedClass::getTicker(){ return _ticker;}
uint32_t InternLedClass::getPeriodMs(){return _periodMs;}
uint8_t InternLedClass::getTimesToBlink(){return _timesToBlink;}
void InternLedClass::setTimesToBlink(uint8_t times){_timesToBlink=times;}
void InternLedClass::init() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
}
void flip() {
int state = digitalRead(LED_BUILTIN); // get the current state of GPIO1 pin
digitalWrite(LED_BUILTIN, !state); // set pin to the opposite state
}
void InternLedClass::blinkFast() {
init();
_ticker->attach_ms(FAST_PERIOD_MS,flip);
}
void InternLedClass::blinkOff() {
_ticker->detach();
digitalWrite(LED_BUILTIN, LOW);
pinMode(LED_BUILTIN, INPUT);
}
void InternLedClass::blinkSlow() {
init();
_ticker->attach_ms(SLOW_PERIOD_MS,flip);
}
/*
Led-Zustand invertieren und sich selbst als Callback mit der gewünschten
Zeit registrieren, wenn die Anzahl noch nicht erreicht wurde.
*/
void flipSingle() {
int state = digitalRead(LED_BUILTIN); // get the current state of GPIO1 pin
digitalWrite(LED_BUILTIN, !state); // set pin to the opposite state
uint32_t period = InternLed.getPeriodMs();
uint8_t times = InternLed.getTimesToBlink()-1;
D(
Serial.print("Times: ");
Serial.println(times);
)
if(state){
InternLed.setTimesToBlink(times);
}
if(times > 0){
InternLed.getTicker()->once_ms(period,flipSingle); // noch einmal starten
}
}
void InternLedClass::blinkFast(uint8_t times) {
init();
_timesToBlink = times; // HIGH und LOW
_periodMs = FAST_PERIOD_MS;
_ticker->attach_ms(FAST_PERIOD_MS,flipSingle);
}
void InternLedClass::blinkSlow(uint8_t times) {
init();
_timesToBlink = times;
_periodMs = SLOW_PERIOD_MS;
_ticker->attach_ms(SLOW_PERIOD_MS,flipSingle);
}
// Quasi Singleton
InternLedClass InternLed;
#pragma once
#include <arduino.h>
#include <Ticker.h>
/* Die interne LED am ESP8266 kann für verschiedene Zwecke angesprochen werden
kurzes Blinken mit oder ohne vorgegebener Anzahl
langes Blinken mit oder ohne vorgegebener Anzahl
*/
class InternLedClass {
public:
InternLedClass();
void blinkFast();
void blinkSlow();
void blinkFast(uint8_t times);
void blinkSlow(uint8_t times);
void blinkOff();
// Methoden für Zugriff auf Fields mittels
// Callbackroutine (normale C-Funktion)
uint32_t getPeriodMs();
uint8_t getTimesToBlink();
void setTimesToBlink(uint8_t times);
Ticker* getTicker();
private:
void init();
Ticker* _ticker;
uint8_t _timesToBlink;
uint32_t _periodMs;
};
extern InternLedClass InternLed;
#include <InternLed.h>
void setup() {
Serial.begin(115200); //Initialisierung der seriellen Schnittstelle
Serial.println();
Serial.println();
Serial.println("LedBlinkingTest");
Serial.println("===============");
}
void loop() {
Serial.println("5 * schnell blinken");
InternLed.blinkFast(5);
delay(3000);
Serial.println("5 * langsam blinken");
InternLed.blinkSlow(5);
delay(10000);
Serial.println("4 Sekunden schnell blinken");
InternLed.blinkFast();
delay(4000);
InternLed.blinkOff();
delay(1000);
Serial.println("4 Sekunden langsam blinken");
InternLed.blinkSlow();
delay(4000);
Serial.println("4 Sekunden Pause");
InternLed.blinkOff();
delay(4000);
}
[platformio]
lib_extra_dirs = /opt/iot2018ph/libraries, D:\iot2018ph\seminar\libraries
[env:d1_mini]
platform = espressif8266
board = d1_mini
framework = arduino
; Custom Serial Monitor baud rate
monitor_baud = 115200
upload_speed = 230400
;upload_speed = 115200
;upload_speed = 460800
;upload_speed = 921600
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment