Sourcen Update 2021

This commit is contained in:
jens 2021-12-26 14:42:41 +01:00
parent d6875d2b98
commit e0448ba915
20 changed files with 2010 additions and 97 deletions

6
.vscode/arduino.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"board": "esp32:esp32:lolin32",
"configuration": "FlashFreq=80,PartitionScheme=default,CPUFreq=240,UploadSpeed=921600",
"port": "COM5",
"sketch": "esp32_deep_sleep\\esp32_deep_sleep.ino"
}

21
.vscode/c_cpp_properties.json vendored Normal file
View File

@ -0,0 +1,21 @@
{
"configurations": [
{
"name": "Win32",
"includePath": [
"C:\\Users\\jens\\AppData\\Local\\Arduino15\\packages\\esp32\\tools\\**",
"C:\\Users\\jens\\ownCloud\\www\\jfs\\Arduino2\\libraries\\**",
"C:\\Program Files (x86)\\Arduino\\libraries\\**",
"C:\\Users\\jens\\AppData\\Local\\Arduino15\\packages\\esp32\\hardware\\esp32\\1.0.4\\**"
],
"forcedInclude": [],
"defines": [
"USBCON"
],
"intelliSenseMode": "windows-msvc-x64",
"cStandard": "c17",
"cppStandard": "c++17"
}
],
"version": 4
}

View File

@ -14,6 +14,11 @@ SSD1306 display(0x3c, 4, 15);
SSD1306 display(0x3c, 5, 4);
#endif
#include "EasyPCF8574.h"
EasyPCF8574 pcf_A(0x20,0); //PCF address, initial value
//// WIFI
const int mxSize=4;
String ssids[mxSize] ={"GAST","pipanet","FRITZ!Box Gastzugang","WLAN-DE8245"};
@ -88,6 +93,14 @@ void setup() {
display.display();
ledcAttachPin(PWM_PIN, PWM_CHANNEL); // assign pin to channel
ledcSetup(PWM_CHANNEL, PWM_FREQ, PWM_RES);
i2c_scanner();
delay(1000);
if (!pcf_A.startI2C(5,4)){
Serial.println("Not started. Check pin and address.");
while (true);
}
test_pcf8574();
}
int duty_cycle=0;
@ -107,7 +120,7 @@ void generator(){
}
void loop() {
generator();
double volt2 = ReadVoltage(36)*127000/27000;
double volt2 = ReadVoltage(36);
//double volt2 = ReadVoltage0dB(36);
//Serial.print(volt2,1);
//Serial.print(" ");
@ -117,7 +130,100 @@ void loop() {
display.drawString(0,20,"Volt 36 "+String(volt2));
//display.drawString(0,30,"Volt 14 "+String(volt2));
display.display();
delay(1);
delay(300);
}
void test_pcf8574(){
Serial.println(" Starting cycle:");
Serial.println("Initial value (as specified):");
Serial.println(pcf_A.getPCFValue());
oldFunc(pcf_A.getPCFValue());
delay(5000);
Serial.println("Setting value to (39):");
//00100111
pcf_A.setFullValue(0xFF); //like pcf address :)
Serial.println("Byte now is:");
Serial.println(pcf_A.getPCFValue());
oldFunc(pcf_A.getPCFValue());
delay(5000);
Serial.println("Checking bit 2 status:"); //bits starts in 0, from right to left
Serial.println(pcf_A.getBitValue(2));
Serial.println("Byte now is:");
Serial.println(pcf_A.getPCFValue());
oldFunc(pcf_A.getPCFValue());
delay(5000);
Serial.println("Inverting bit 2 value");
pcf_A.setInvertBit(2);
Serial.println(pcf_A.getBitValue(2));
Serial.println("Byte now is:");
Serial.println(pcf_A.getPCFValue());
oldFunc(pcf_A.getPCFValue());
delay(5000);
Serial.println("Set bit 2 up:");
pcf_A.setUpBit(2);
Serial.println(pcf_A.getBitValue(2));
Serial.println("Byte now is:");
Serial.println(pcf_A.getPCFValue());
oldFunc(pcf_A.getPCFValue());
delay(5000);
Serial.println("Set bit 2 down");
pcf_A.setDownBit(2);
Serial.println(pcf_A.getBitValue(2));
Serial.println("Byte now is:");
Serial.println(pcf_A.getPCFValue());
oldFunc(pcf_A.getPCFValue());
delay(5000);
Serial.println("Done.");
}
void i2c_scanner(){
byte error, address;
int nDevices;
for(address = 1; address < 127; address++ ) {
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0) {
nDevices++;
Serial.print("Device found @ 0x");
if (address<16) Serial.print("0");
Serial.print(address,HEX);
Serial.println(" !");
}
else if (error==4)
{
Serial.print("Unknow error @ 0x");
if (address<16) Serial.print("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0) {
Serial.println("No I2C devices found\n");
#if OLED_DISPLAY
display.drawString(0, 23 , "No I2C devices found");
display.display();
#endif
} else {
Serial.println("done\n");
}
}
void oldFunc(int var) {
for (int i = 0; i < 16; i++) {
Serial.print(((var >> i) & 1) == 1 ? "1" : "0");
}
Serial.println();
}
void newFunc(int var) {
for (unsigned int test = 0x8000; test; test >>= 1) {
Serial.write(var & test ? '1' : '0');
}
Serial.println();
}
double ReadVoltage0dB(byte pin){

View File

@ -0,0 +1,264 @@
/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-cam-video-streaming-web-server-camera-home-assistant/
IMPORTANT!!!
- Select Board "AI Thinker ESP32-CAM"
- GPIO 0 must be connected to GND to upload a sketch
- After connecting GPIO 0 to GND, press the ESP32-CAM on-board RESET button to put your board in flashing mode
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/
#include "esp_camera.h"
#include <WiFi.h>
#include "esp_timer.h"
#include "img_converters.h"
#include "Arduino.h"
#include "fb_gfx.h"
#include "soc/soc.h" //disable brownout problems
#include "soc/rtc_cntl_reg.h" //disable brownout problems
#include "esp_http_server.h"
//Replace with your network credentials
const char* ssid = "pipanet";
const char* password = "passatvr6";
#define PART_BOUNDARY "123456789000000000000987654321"
// This project was tested with the AI Thinker Model, M5STACK PSRAM Model and M5STACK WITHOUT PSRAM
#define CAMERA_MODEL_AI_THINKER
//#define CAMERA_MODEL_M5STACK_PSRAM
//#define CAMERA_MODEL_M5STACK_WITHOUT_PSRAM
// Not tested with this model
//#define CAMERA_MODEL_WROVER_KIT
#if defined(CAMERA_MODEL_WROVER_KIT)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 21
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 19
#define Y4_GPIO_NUM 18
#define Y3_GPIO_NUM 5
#define Y2_GPIO_NUM 4
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
#elif defined(CAMERA_MODEL_M5STACK_PSRAM)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM 15
#define XCLK_GPIO_NUM 27
#define SIOD_GPIO_NUM 25
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 19
#define Y8_GPIO_NUM 36
#define Y7_GPIO_NUM 18
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 5
#define Y4_GPIO_NUM 34
#define Y3_GPIO_NUM 35
#define Y2_GPIO_NUM 32
#define VSYNC_GPIO_NUM 22
#define HREF_GPIO_NUM 26
#define PCLK_GPIO_NUM 21
#elif defined(CAMERA_MODEL_M5STACK_WITHOUT_PSRAM)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM 15
#define XCLK_GPIO_NUM 27
#define SIOD_GPIO_NUM 25
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 19
#define Y8_GPIO_NUM 36
#define Y7_GPIO_NUM 18
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 5
#define Y4_GPIO_NUM 34
#define Y3_GPIO_NUM 35
#define Y2_GPIO_NUM 17
#define VSYNC_GPIO_NUM 22
#define HREF_GPIO_NUM 26
#define PCLK_GPIO_NUM 21
#elif defined(CAMERA_MODEL_AI_THINKER)
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
#else
#error "Camera model not selected"
#endif
static const char* _STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY;
static const char* _STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n";
static const char* _STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n";
httpd_handle_t stream_httpd = NULL;
static esp_err_t stream_handler(httpd_req_t *req){
camera_fb_t * fb = NULL;
esp_err_t res = ESP_OK;
size_t _jpg_buf_len = 0;
uint8_t * _jpg_buf = NULL;
char * part_buf[64];
res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
if(res != ESP_OK){
return res;
}
while(true){
fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera capture failed");
res = ESP_FAIL;
} else {
if(fb->width > 400){
if(fb->format != PIXFORMAT_JPEG){
bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len);
esp_camera_fb_return(fb);
fb = NULL;
if(!jpeg_converted){
Serial.println("JPEG compression failed");
res = ESP_FAIL;
}
} else {
_jpg_buf_len = fb->len;
_jpg_buf = fb->buf;
}
}
}
if(res == ESP_OK){
size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len);
res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen);
}
if(res == ESP_OK){
res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len);
}
if(res == ESP_OK){
res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
}
if(fb){
esp_camera_fb_return(fb);
fb = NULL;
_jpg_buf = NULL;
} else if(_jpg_buf){
free(_jpg_buf);
_jpg_buf = NULL;
}
if(res != ESP_OK){
break;
}
//Serial.printf("MJPG: %uB\n",(uint32_t)(_jpg_buf_len));
}
return res;
}
void startCameraServer(){
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.server_port = 80;
httpd_uri_t index_uri = {
.uri = "/",
.method = HTTP_GET,
.handler = stream_handler,
.user_ctx = NULL
};
//Serial.printf("Starting web server on port: '%d'\n", config.server_port);
if (httpd_start(&stream_httpd, &config) == ESP_OK) {
httpd_register_uri_handler(stream_httpd, &index_uri);
}
}
void setup() {
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
Serial.begin(115200);
Serial.setDebugOutput(false);
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.pixel_format = PIXFORMAT_JPEG;
if(psramFound()){
config.frame_size = FRAMESIZE_UXGA;
config.jpeg_quality = 10;
config.fb_count = 2;
} else {
config.frame_size = FRAMESIZE_SVGA;
config.jpeg_quality = 12;
config.fb_count = 1;
}
// Camera init
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
return;
}
// Wi-Fi connection
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("Camera Stream Ready! Go to: http://");
Serial.print(WiFi.localIP());
// Start streaming web server
startCameraServer();
}
void loop() {
delay(1);
}

View File

@ -0,0 +1,259 @@
/*********
Rui Santos
Complete project details at http://randomnerdtutorials.com
*********/
// Load Wi-Fi library
#include <WiFi.h>
#include "SSD1306.h" // alias for `#include "SSD1306Wire.h"
// jfs Wemos lolin32
// jfs Heltec WiFi kit 32 (weisses Board)
// #define HELTEC
#define DEBUG
// Initialize the OLED display using Wire library
#ifdef HELTEC
SSD1306 display(0x3c, 4, 15);
#else
SSD1306 display(0x3c, 5, 4);
#endif
//// WIFI
const int mxSize=4;
String ssids[mxSize] ={"GAST","pipanet","FRITZ!Box Gastzugang","WLAN-DE8245"};
String ssidp[mxSize] = {"passatvr6","passatvr6","praxis123","4955065570896956"};
boolean conok =false;
void netfound(int i){
display.clear();
display.setColor(BLACK);
display.fillRect(0, 0, 128, 10);
display.setColor(WHITE);
display.drawString(0,0,String(i));
display.drawString(20,0,"networks found");
display.display();
}
boolean init_wifi(){
boolean ok = false;
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0) {
Serial.println("no networks found");
netfound(0);
} else {
Serial.print(n);
Serial.println(" networks found");
netfound(n);
for (int i = 0; i < n; ++i) {
for (int p=0;p<mxSize;p++){
if (WiFi.SSID(i).equals(ssids[p])){
String pp = ssidp[p];
String ss = WiFi.SSID(i);
WiFi.begin(ss.c_str(), pp.c_str());
i=n;
ok = true;
}
}
delay(10);
}
}
return ok;
}
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
// Assign output variables to GPIO pins
const int output26 = 26;
const int output25 = 25;
// Input
const int input36 = 36;
const int input39 = 16;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
Serial.begin(115200);
display.init();
display.flipScreenVertically();
display.clear();
display.drawString(0, 0, "Starting...");
display.display();
while (!init_wifi()){
delay(200);
}
display.drawString(0, 10, "Connecting to WiFi...");
display.display();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
display.drawString(0, 20, "\nWiFi connected, IP address: ");
display.drawString(0, 30, WiFi.localIP().toString());
server.begin(); // server starten
display.display();
// Initialize the output variables as outputs
pinMode(output26, OUTPUT);
pinMode(output25, OUTPUT);
// Set outputs to LOW
digitalWrite(output26, LOW);
digitalWrite(output25, LOW);
// check server running
// SVP server 1
pinMode(input36, INPUT);
// SVN server 2
pinMode(input39, INPUT);
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns the GPIOs on and off
if (header.indexOf("GET /pw1/on") >= 0) {
Serial.println("PW1on");
digitalWrite(output25, HIGH);
delay(200);
digitalWrite(output25,LOW);
} else if (header.indexOf("GET /pw1/off") >= 0) {
Serial.println("PW1 off");
digitalWrite(output25, HIGH);
delay(5000);
digitalWrite(output25,LOW);
} else if (header.indexOf("GET /pw2/on") >= 0) {
Serial.println("PW2 on");
digitalWrite(output26, HIGH);
delay(200);
digitalWrite(output26,LOW);
} else if (header.indexOf("GET /pw2/off") >= 0) {
Serial.println("PW2 off");
digitalWrite(output26, HIGH);
delay(5000);
digitalWrite(output26,LOW);
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");
client.println("<p><a href=\"/pw1/on\"><button class=\"button\">Server 1 ON</button></a></p>");
client.println("<p><a href=\"/pw1/off\"><button class=\"button\">Server 1 OFF</button></a></p>");
if (digitalRead(input36)== HIGH){
client.println("<p>Server 1 ist online</p>");
} else {
client.println("<p>Server 1 ist offline</p>");
}
client.println("<p><a href=\"/pw2/on\"><button class=\"button\">Server 2 ON</button></a></p>");
client.println("<p><a href=\"/pw2/off\"><button class=\"button\">Server 2 OFF</button></a></p>");
if (digitalRead(input39)== HIGH){
client.println("<p>Server 2 ist online</p>");
} else {
client.println("<p>Server 2 ist offline</p>");
}
client.println("<p><a href=\"/update\"><button class=\"button\">update</button></a></p>");
/*
// Display current state, and ON/OFF buttons for GPIO 26
client.println("<p>GPIO 26 - State " + output26State + "</p>");
// If the output26State is off, it displays the ON button
//if (output26State=="off") {
client.println("<p><a href=\"/pw/on\"><button class=\"button\">ON</button></a></p>");
// else {
// client.println("<p><a href=\"/pw/off\"><button class=\"button button2\">OFF</button></a></p>");
//}
// Display current state, and ON/OFF buttons for GPIO 25
client.println("<p>GPIO 25 - State " + output25State + "</p>");
If the output25State is off, it displays the ON button
/*if (output25State=="off") {
client.println("<p><a href=\"/25/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/25/off\"><button class=\"button button2\">OFF</button></a></p>");
}
*/
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
if (digitalRead(input36)== LOW) {
digitalWrite(output25, HIGH);
delay(200);
digitalWrite(output25,LOW);
delay(10000);
}
}

View File

@ -0,0 +1,307 @@
/*********
Rui Santos
Complete project details at http://randomnerdtutorials.com
*********/
// Load Wi-Fi library
#include <WiFi.h>
#include "SSD1306.h" // alias for `#include "SSD1306Wire.h"
// jfs Wemos lolin32
// jfs Heltec WiFi kit 32 (weisses Board)
// #define HELTEC
#define DEBUG
// Initialize the OLED display using Wire library
#ifdef HELTEC
SSD1306 display(0x3c, 4, 15);
#else
SSD1306 display(0x3c, 5, 4);
#endif
//// WIFI
const int mxSize=4;
String ssids[mxSize] ={"GAST","pipanet","FRITZ!Box Gastzugang","WLAN-DE8245"};
String ssidp[mxSize] = {"passatvr6","passatvr6","praxis123","4955065570896956"};
boolean conok =false;
void netfound(int i){
display.clear();
display.setColor(BLACK);
display.fillRect(0, 0, 128, 10);
display.setColor(WHITE);
display.drawString(0,0,String(i));
display.drawString(20,0,"networks found");
display.display();
}
bool myWiFiFirstConnect = true;
boolean init_wifi(){
int stat = WL_IDLE_STATUS;
boolean ok = false;
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0) {
Serial.println("no networks found");
netfound(0);
} else {
Serial.print(n);
Serial.println(" networks found");
netfound(n);
for (int i = 0; i < n; ++i) {
for (int p=0;p<mxSize;p++){
if (WiFi.SSID(i).equals(ssids[p])){
String pp = ssidp[p];
String ss = WiFi.SSID(i);
Serial.print(stat);
stat = WiFi.begin(ss.c_str(), pp.c_str());
Serial.println(stat);
i=n;
ok = true;
}
}
delay(10);
}
}
return ok;
}
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
// Assign output variables to GPIO pins
const int output26 = 26;
const int output25 = 25;
// Input
const int input36 = 36;
const int input39 = 16;
// restart automatisch
boolean auto1 = true;
boolean auto2 = true;
boolean auto1start = false;
unsigned long auto1timer = 0;
unsigned long now1is = 0;
const long now1max = 10000;
boolean auto2start = false;
unsigned long auto2timer = 0;
unsigned long now2is = 0;
const long now2max = 10000;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
int retry = 0;
void setup() {
Serial.begin(115200);
display.init();
//display.flipScreenVertically();
display.clear();
display.drawString(0, 0, "Starting...");
display.display();
while (!init_wifi()){
delay(200);
}
display.drawString(0, 10, "Connecting to WiFi...");
display.display();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
retry++;
if (retry > 10){
esp_sleep_enable_timer_wakeup(5000000);
esp_deep_sleep_start();
}
}
display.drawString(0, 20, "\nWiFi connected, IP address: ");
display.drawString(0, 30, WiFi.localIP().toString());
server.begin(); // server starten
display.display();
// Initialize the output variables as outputs
pinMode(output26, OUTPUT);
pinMode(output25, OUTPUT);
// Set outputs to LOW
digitalWrite(output26, LOW);
digitalWrite(output25, LOW);
// check server running
// SVP server 1
pinMode(input36, INPUT);
// SVN server 2
pinMode(input39, INPUT);
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
currentTime = millis();
previousTime = currentTime;
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns the GPIOs on and off
if (header.indexOf("GET /pw1/on") >= 0) {
Serial.println("PW1on");
digitalWrite(output25, HIGH);
delay(200);
digitalWrite(output25,LOW);
} else if (header.indexOf("GET /pw1/off") >= 0) {
Serial.println("PW1 off");
digitalWrite(output25, HIGH);
delay(5000);
digitalWrite(output25,LOW);
} else if (header.indexOf("GET /pw2/on") >= 0) {
Serial.println("PW2 on");
digitalWrite(output26, HIGH);
delay(200);
digitalWrite(output26,LOW);
} else if (header.indexOf("GET /pw2/off") >= 0) {
Serial.println("PW2 off");
digitalWrite(output26, HIGH);
delay(5000);
digitalWrite(output26,LOW);
} else if (header.indexOf("GET /auto1/on") >= 0) {
Serial.println("Auto1 on");
auto1 = true;
} else if (header.indexOf("GET /auto1/off") >= 0) {
Serial.println("Auto1 off");
auto1 = false;
} else if (header.indexOf("GET /auto2/on") >= 0) {
Serial.println("Auto2 on");
auto2 = true;
} else if (header.indexOf("GET /auto2/off") >= 0) {
Serial.println("Auto2 off");
auto2 = false;
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");
client.println("<p><a href=\"/pw1/on\"><button class=\"button\">Server 1 ON</button></a></p>");
client.println("<p><a href=\"/pw1/off\"><button class=\"button\">Server 1 OFF</button></a></p>");
if (digitalRead(input36)== HIGH){
client.println("<p>Server 1 ist online</p>");
} else {
client.println("<p>Server 1 ist offline</p>");
}
if (auto1== true) {
client.println("<p><a href=\"/auto1/off\"><button class=\"button\">Auto ON</button></a></p>");
}
else {
client.println("<p><a href=\"/auto1/on\"><button class=\"button button2\">Auto OFF</button></a></p>");
}
client.println("<p><a href=\"/pw2/on\"><button class=\"button\">Server 2 ON</button></a></p>");
client.println("<p><a href=\"/pw2/off\"><button class=\"button\">Server 2 OFF</button></a></p>");
if (digitalRead(input39)== HIGH){
client.println("<p>Server 2 ist online</p>");
} else {
client.println("<p>Server 2 ist offline</p>");
}
if (auto2== true) {
client.println("<p><a href=\"/auto2/off\"><button class=\"button\">Auto ON</button></a></p>");
}
else {
client.println("<p><a href=\"/auto2/on\"><button class=\"button button2\">Auto OFF</button></a></p>");
}
client.println("<p><a href=\"/update\"><button class=\"button\">update</button></a></p>");
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
if ((auto1 == true) && (digitalRead(input36)== LOW)){
if (auto1start== true){
digitalWrite(output25, HIGH);
delay(200);
digitalWrite(output25,LOW);
auto1start = false;
auto1timer = millis();
} else {
now1is = millis();
if ( now1is - auto1timer > now1max){
auto1start = true;
}
}
}
if ((auto2 == true) && (digitalRead(input39)== LOW)){
if (auto2start== true){
digitalWrite(output26, HIGH);
delay(200);
digitalWrite(output26,LOW);
auto2start = false;
auto2timer = millis();
} else {
now2is = millis();
if ( now2is - auto2timer > now2max){
auto2start = true;
}
}
}
}

View File

@ -11,7 +11,7 @@
#define LCD_OFF // LCD_ON, if want use LCD 4 bits interface
#define LCD_I2C_OFF // LCD_I2C_ON, if want use I2C LCD (PCF8574)
#define JFS
#define TEST
//#define TEST
#define WIFI
#ifdef LCD_I2C_ON // If I2C LCD enabled
@ -57,6 +57,8 @@ void netfound(int i){
display.display();
}
boolean init_wifi(){
boolean ok = false;
WiFi.mode(WIFI_STA);
@ -106,7 +108,7 @@ bool flag = true; // Fla
uint32_t overflow = 20000; // Max Pulse Counter value
int16_t pulses = 0; // Pulse Counter value
uint32_t multPulses = 0; // Quantidade de overflows do contador PCNT
uint32_t sample_time = 1000000; // sample time of 1 second to count pulses 1000000
uint32_t sample_time = 100000; // 1ooms | sample time of 1 second to count pulses 1000000
uint32_t osc_freq = 1254312; // Oscillator frequency - initial 12543 Hz (may be 1 Hz to 40 MHz)
uint32_t mDuty = 0; // Duty value
uint32_t resolution = 0; // Resolution value
@ -121,6 +123,7 @@ esp_timer_create_args_t create_args; // Cre
esp_timer_handle_t timer_handle; // Create an single timer
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; // portMUX_TYPE to do synchronism
int retry = 0;
//----------------------------------------------------------------------------------------
void setup()
@ -162,6 +165,11 @@ while (!init_wifi()){
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
retry++;
if (retry > 10){
esp_sleep_enable_timer_wakeup(5000000);
esp_deep_sleep_start();
}
}
display.drawString(0, 20, "\nWiFi connected, IP address: ");
display.drawString(0, 30, WiFi.localIP().toString());
@ -314,8 +322,11 @@ void loop()
frequency = (pulses + (multPulses * overflow)) / 2 ; // Calculation of frequency
#ifdef JFS
factor = 1000000/sample_time;
frequenz = frequency*factor; // correct frequency if sample_time is smaller then 1sec
Serial.println(frequency);
frequenz = frequency*factor;
dtostrf(frequenz, 0, 0, buf );// correct frequency if sample_time is smaller then 1sec
String s = String(buf);
s = ">"+s+"<";
Serial.println(s);
#else
printf("Frequency : %s", (ltos(frequency, buf, 10))); // Print frequency with commas
printf(" Hz \n"); // Print unity Hz
@ -367,13 +378,13 @@ void loop()
{
Serial.println(inputString);
#ifdef JFS
if (inputString.startsWith("s")){
if (inputString.startsWith("s")){ // set sample time ms
inputString.remove(0,1);
Serial.println(inputString);
sample_time = inputString.toInt();
Serial.println(sample_time);
}
if (inputString.startsWith("o")){
if (inputString.startsWith("o")){ // set frequency
inputString.remove(0,1);
Serial.println(inputString);
osc_freq = inputString.toInt();

View File

@ -0,0 +1,187 @@
#include <WiFi.h>
#include <PubSubClient.h>
#include "SSD1306.h" // alias for `#include "SSD1306Wire.h"
// jfs Wemos lolin32
// jfs Heltec WiFi kit 32 (weisses Board)
//define HELTEC
#define DEBUG
// Initialize the OLED display using Wire library
#ifdef HELTEC
SSD1306 display(0x3c, 4, 15);
#else
SSD1306 display(0x3c, 5, 4);
#endif
const char* mqttServer = "192.168.2.71";
const int mqttPort = 1883;
const char* clientID = "esp_32_relay";
const char* channelName = "/Urs/";
WiFiClient MQTTclient;
PubSubClient client(MQTTclient);
const int relay = 25;
void callback(char* topic, byte* payload, unsigned int length) {
String payload_buff;
for (int i=0;i<length;i++) {
payload_buff = payload_buff+String((char)payload[i]);
if (payload_buff[0] == '1'){
Serial.print("on ");
digitalWrite(relay, LOW);
}
if (payload_buff[0] == '0'){
Serial.print("off ");
digitalWrite(relay, HIGH);
}
}
Serial.println(payload_buff); // Print out messages.
}
long lastReconnectAttempt = 0;
boolean reconnect() {
if (client.connect(clientID)) {
client.subscribe(channelName); // Subscribe to channel.
}
return client.connected();
}
unsigned long previousMillis = 0; // Letzter Update-Zeitstempel
const long interval = 1000; // Sende-Intervall in ms
//// WIFI
const int mxSize=4;
String ssids[mxSize] ={"Home","pipanet","FRITZ!Box Gastzugang","WLAN-DE8245"};
String ssidp[mxSize] = {"2Drittel%13579","passatvr6","praxis123","4955065570896956"};
boolean conok =false;
void netfound(int i){
display.clear();
display.setColor(BLACK);
display.fillRect(0, 0, 128, 10);
display.setColor(WHITE);
display.drawString(0,0,String(i));
display.drawString(20,0,"networks found");
display.display();
}
boolean init_wifi(){
boolean ok = false;
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0) {
Serial.println("no networks found");
netfound(0);
} else {
Serial.print(n);
Serial.println(" networks found");
netfound(n);
for (int i = 0; i < n; ++i) {
for (int p=0;p<mxSize;p++){
if (WiFi.SSID(i).equals(ssids[p])){
String pp = ssidp[p];
String ss = WiFi.SSID(i);
WiFi.begin(ss.c_str(), pp.c_str());
i=n;
ok = true;
}
}
delay(10);
}
}
return ok;
}
///// WIFI
void setup() {
// test
adcAttachPin(37);
analogSetClockDiv(1); // 1338mS
analogSetPinAttenuation(37,ADC_0db);
pinMode(relay,OUTPUT);
digitalWrite(relay,HIGH);
// put your setup code here, to run once:
#ifdef HELTEC
pinMode(16,OUTPUT); digitalWrite(16, LOW); delay(50); digitalWrite(16, HIGH);
#endif
Serial.begin(115200);
display.init();
display.flipScreenVertically();
display.clear();
display.drawString(0, 0, "Starting...");
display.display();
while (!init_wifi()){
delay(200);
}
display.drawString(0, 10, "Connecting to WiFi...");
display.display();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
display.drawString(0, 20, "\nWiFi connected, IP address: ");
display.drawString(0, 30, WiFi.localIP().toString());
client.setServer(mqttServer, mqttPort); // Connect to PubNub.
client.setCallback(callback);
lastReconnectAttempt = 0;
display.display();
display.init();
}
void loop() {
if (!client.connected()) {
long now = millis();
if (now - lastReconnectAttempt > 5000) { // Try to reconnect.
lastReconnectAttempt = now;
if (reconnect()) { // Attempt to reconnect.
lastReconnectAttempt = 0;
}
}
} else { // Connected.
client.loop();
publishit(); // Publish message.
delay(100);
}
}
void publishit() {
char buffer[10];
double volt2 = ReadVoltage(36)*127000/27000;
double volt1 = ReadVoltage0dB(37);
//Serial.print(volt2,1);
//Serial.print(" ");
//Serial.println(volt1);
dtostrf(volt1, 6, 2, buffer);
client.publish("/ESP_32_AD/V1",buffer); // Publish message.
dtostrf(volt2, 6, 2, buffer);
client.publish("/ESP_32_AD/V2",buffer); // Publish message.
display.clear();
display.drawString(0,20,"Volt 1 "+String(volt1));
display.drawString(0,30,"Volt 2 "+String(volt2));
display.display();
delay(2000);
}
// test
double ReadVoltage0dB(byte pin){
double reading = analogRead(pin); // Reference voltage is 3v3 so maximum reading is 3v3 = 4095 in range 0 to 4095
if(reading < 1 || reading > 4095) return 0;
return reading/4095;
}
double ReadVoltage(byte pin){
double reading = analogRead(pin); // Reference voltage is 3v3 so maximum reading is 3v3 = 4095 in range 0 to 4095
if(reading < 1 || reading > 4095) return 0;
// return -0.000000000009824 * pow(reading,3) + 0.000000016557283 * pow(reading,2) + 0.000854596860691 * reading + 0.065440348345433;
return -0.000000000000016 * pow(reading,4) + 0.000000000118171 * pow(reading,3)- 0.000000301211691 * pow(reading,2)+ 0.001109019271794 * reading + 0.034143524634089;
} // Added an improved polynomial, use either, comment out as required

View File

@ -0,0 +1,83 @@
int xPin = A0;
int yPin = A1;
int buttonPin = 2;
int xPosition = 0;
int yPosition = 0;
int buttonState = 0;
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
pinMode(3, OUTPUT);
digitalWrite(3, LOW);
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
pinMode(5, OUTPUT);
digitalWrite(5, LOW);
pinMode(6, OUTPUT);
digitalWrite(7, LOW);
pinMode(7, OUTPUT);
//activate pull-up resistor on the push-button pin
pinMode(buttonPin, INPUT_PULLUP);
// For versions prior to Arduino 1.0.1
// pinMode(buttonPin, INPUT);
// digitalWrite(buttonPin, HIGH);
}
void loop() {
xPosition = analogRead(xPin);
yPosition = analogRead(yPin);
buttonState = digitalRead(buttonPin);
//Serial.print("X: ");
//Serial.print(xPosition);
//Serial.print(" | Y: ");
//Serial.print(yPosition);
//Serial.print(" | Button: ");
//Serial.println(buttonState);
if (buttonState == 0) {
Serial.println("pressed");
digitalWrite(3,HIGH);
delay(100);
digitalWrite(3,LOW);
delay(500);
}
if (xPosition < 400) {
Serial.println("x <<< ");
digitalWrite(4,HIGH);
delay(100);
digitalWrite(4,LOW);
//delay(500);
}
if (xPosition > 600) {
Serial.println("x >>> ");
digitalWrite(5,HIGH);
delay(100);
digitalWrite(5,LOW);
//delay(500);
}
if (yPosition < 400) {
Serial.println("y <<< ");
digitalWrite(6,HIGH);
delay(100);
digitalWrite(6,LOW);
//delay(500);
}
if (yPosition > 600) {
Serial.println("y >>> ");
digitalWrite(7,HIGH);
delay(100);
digitalWrite(7,LOW);
//delay(500);
}
delay(50); // add some delay between reads
}

View File

@ -0,0 +1,84 @@
#include "SSD1306.h" // alias for `#include "SSD1306Wire.h" // Board Handling
// jfs Wemos lolin32
// jfs Heltec WiFi kit 32 (weisses Board)
// #define HELTEC
// Initialize the OLED display using Wire library
#ifdef HELTEC
SSD1306 display(0x3c, 4, 15);
#else
SSD1306 display(0x3c, 5, 4);
#endif
#define uS_TO_S_FACTOR 1000000 /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 30 /* Time ESP32 will go to sleep (in seconds) */
#define OLED
RTC_DATA_ATTR int bootCount = 0;
#define BUTTON_PIN_BITMASK 0x1000000000000000
void print_wakeup_reason(){
esp_sleep_wakeup_cause_t wakeup_reason;
wakeup_reason = esp_sleep_get_wakeup_cause();
switch(wakeup_reason)
{
case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
}
}
String reason = " Don't know ! ";
void get_wakeup_reason(){
esp_sleep_wakeup_cause_t wakeup_reason;
wakeup_reason = esp_sleep_get_wakeup_cause();
switch(wakeup_reason)
{
case ESP_SLEEP_WAKEUP_EXT0 : reason = "using RTC_IO"; break;
case ESP_SLEEP_WAKEUP_EXT1 : reason = "using RTC_CNTL"; break;
case ESP_SLEEP_WAKEUP_TIMER : reason = "by timer"; break;
case ESP_SLEEP_WAKEUP_TOUCHPAD : reason = "by touchpad"; break;
case ESP_SLEEP_WAKEUP_ULP : reason = "by ULP program"; break;
default : reason = "Dont know"; break;
}
}
void setup(){
Serial.begin(115200);
delay(10); //Take some time to open up the Serial Monitor
//Increment boot number and print it every reboot
++bootCount;
print_wakeup_reason();
get_wakeup_reason();
#ifdef OLED
#ifdef HELTEC
pinMode(16,OUTPUT); digitalWrite(16, LOW); delay(50); digitalWrite(16, HIGH);
#endif
display.init();
//display.flipScreenVertically();
display.clear();
display.drawString(0,10,String(bootCount));
display.drawString(0,20,reason);
display.display();
#endif
Serial.println("Boot number: " + String(bootCount));
esp_sleep_enable_ext0_wakeup(GPIO_NUM_15,1); //1 = High, 0 = Low
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
Serial.println("Setup ESP32 to sleep for every " + String(TIME_TO_SLEEP) +
" Seconds");
Serial.println("Going to sleep now");
delay(1000);
Serial.flush();
esp_deep_sleep_start();
Serial.println("This will never be printed");
}
void loop(){}

View File

@ -0,0 +1,2 @@
# EasyPCF8574
A simple PCF8574 control

View File

@ -0,0 +1,56 @@
#include "EasyPCF8574.h"
EasyPCF8574 pcf_A(0x27,0); //PCF address, initial value
EasyPCF8574 pcf_B(0x29,0);
void setup() {
Serial.begin(9600);
//ESP32 example. You can use overloaded function with no parameters in startI2C() method.
if (!pcf_A.startI2C(21,22)){
Serial.println("Not started. Check pin and address.");
while (true);
}
}
void loop() {
Serial.println(" Starting cycle:");
Serial.println("Initial value (as specified):");
Serial.println(pcf_A.getPCFValue());
delay(500);
Serial.println("Setting value to (39):");
//00100111
pcf_A.setFullValue(0x27); //like pcf address :)
Serial.println("Byte now is:");
Serial.println(pcf_A.getPCFValue());
delay(500);
Serial.println("Checking bit 2 status:"); //bits starts in 0, from right to left
Serial.println(pcf_A.getBitValue(2));
Serial.println("Byte now is:");
Serial.println(pcf_A.getPCFValue());
delay(500);
Serial.println("Inverting bit 2 value");
pcf_A.setInvertBit(2);
Serial.println(pcf_A.getBitValue(2));
Serial.println("Byte now is:");
Serial.println(pcf_A.getPCFValue());
delay(500);
Serial.println("Set bit 2 up:");
pcf_A.setUpBit(2);
Serial.println(pcf_A.getBitValue(2));
Serial.println("Byte now is:");
Serial.println(pcf_A.getPCFValue());
delay(500);
Serial.println("Set bit 2 down");
pcf_A.setDownBit(2);
Serial.println(pcf_A.getBitValue(2));
Serial.println("Byte now is:");
Serial.println(pcf_A.getPCFValue());
delay(500);
Serial.println("Done.");
}

View File

@ -0,0 +1,21 @@
{
"name": "EasyPCF8574",
"keywords": "i2c,wire",
"description": "Generic library for PCF8574 easy to use",
"repository":
{
"type": "git",
"url": "https://github.com/DjamesSuhanko/EasyPCF8574"
},
"authors":
{
"name": "Djames Suhanko",
"url": "https://github.com/DjamesSuhanko",
"maintainer": true
},
"version": "1.0.4",
"license": "MIT",
"frameworks": "arduino",
"platforms": "*"
}

View File

@ -0,0 +1,9 @@
name=EasyPCF8574
version=1.0.4
author=Djames Suhanko
maintainer=Djames Suhanko
sentence=Generic library for PCF8574 easy to use
paragraph=Generic library for PCF8574 easy to use
category=Device Control
url=https://github.com/DjamesSuhanko/EasyPCF8574
architectures=esp32

View File

@ -0,0 +1,109 @@
#include "EasyPCF8574.h"
EasyPCF8574::EasyPCF8574(uint8_t pcf_addr, uint8_t initial_value){
this->pcf_address = pcf_addr;
this->started = false;
this->pcf_last_value = initial_value;
}
void EasyPCF8574::setPCFaddress(uint8_t addr){
this->pcf_address = addr;
}
void EasyPCF8574::setFullValue(uint8_t value){
if (this->started){
Wire.beginTransmission(this->pcf_address);
Wire.write(value);
Wire.endTransmission();
}
}
void EasyPCF8574::setFullValue(uint8_t value, uint8_t pcf_addr){
if (this->started){
Wire.beginTransmission(pcf_addr);
Wire.write(value);
Wire.endTransmission();
}
}
void EasyPCF8574::setInvertBit(uint8_t bit_to_change){
if (!this->started) return;
this->pcf_last_value = pcf_last_value^(1<<bit_to_change);
this->setFullValue(this->pcf_last_value);
}
void EasyPCF8574::setInvertBit(uint8_t bit_to_change, uint8_t pcf_addr){
this->pcf_last_value = pcf_last_value^(1<<bit_to_change);
this->setFullValue(this->pcf_last_value, pcf_addr);
}
void EasyPCF8574::setDownBit(uint8_t bit_to_change){
this->pcf_last_value = pcf_last_value&~(1<<bit_to_change);
this->setFullValue(this->pcf_last_value);
}
void EasyPCF8574::setDownBit(uint8_t bit_to_change, uint8_t pcf_addr){
this->pcf_last_value = pcf_last_value&~(1<<bit_to_change);
this->setFullValue(this->pcf_last_value, pcf_addr);
}
void EasyPCF8574::setUpBit(uint8_t bit_to_change){
this->pcf_last_value = pcf_last_value|(1<<bit_to_change);
this->setFullValue(this->pcf_last_value);
}
void EasyPCF8574::setUpBit(uint8_t bit_to_change, uint8_t pcf_addr){
this->pcf_last_value = pcf_last_value|(1<<bit_to_change);
this->setFullValue(this->pcf_last_value, pcf_addr);
}
uint8_t EasyPCF8574::getPCFValue(){
Wire.requestFrom(this->pcf_address,1);
if (Wire.available()){
return Wire.read();
}
else{
return 0;
}
}
uint8_t EasyPCF8574::getPCFValue(uint8_t pcf_addr){
Wire.requestFrom(pcf_addr,1);
if (Wire.available()){
return Wire.read();
}
else{
return 0;
}
}
uint8_t EasyPCF8574::getBitValue(uint8_t bit_position){
Wire.requestFrom(this->pcf_address,1);
if (Wire.available()){
this->pcf_last_value = Wire.read();
}
return this->pcf_last_value&(1<<bit_position);
}
uint8_t EasyPCF8574::getBitValue(uint8_t bit_position, uint8_t pcf_addr){
Wire.requestFrom(pcf_addr,1);
if (Wire.available()){
this->pcf_last_value = Wire.read();
}
return this->pcf_last_value&(1<<bit_position);
}
bool EasyPCF8574::startI2C(uint8_t sda_pin, uint8_t scl_pin){
if (Wire.begin(sda_pin,scl_pin)){
this->started = true;
return true;
}
}
bool EasyPCF8574::startI2C(){
if (Wire.begin()){
this->started = true;
return true;
}
}

View File

@ -0,0 +1,57 @@
#include <Arduino.h>
#include <Wire.h>
/*
PCF8574 handler - by: Djames Suhanko <djames.suhanko@gmail.com> - 10.01.2020 v.1.0
*/
class EasyPCF8574{
public:
bool started;
//! save last value read.
uint8_t pcf_last_value;
EasyPCF8574(uint8_t pcf_addr, uint8_t initial_value);
//! just a default address value.
uint8_t pcf_address;
//! change default PCF8574 address to a new one.
void setPCFaddress(uint8_t addr);
//! No matter the old value, this function will ignore it.
void setFullValue(uint8_t value);
//! Overriding method, passing pcf_address if more than one is connected
void setFullValue(uint8_t value, uint8_t pcf_addr);
//! invert a bit, no matter if actual value is 0 or 1.
void setInvertBit(uint8_t bit_to_change);
//! Overriding method, passing pcf_address if more than one is connected
void setInvertBit(uint8_t bit_to_change, uint8_t pcf_addr);
//! Turn bit value 0, no metter if bit already was 0.
void setDownBit(uint8_t bit_to_change);
//! Overriding method, passing pcf_address if more than one is connected
void setDownBit(uint8_t bit_to_change, uint8_t pcf_addr);
//! Turn bit value 1, no matter if bit already was 1.
void setUpBit(uint8_t bit_to_change);
//! Overriding method, passing pcf_address if more than one is connected
void setUpBit(uint8_t bit_to_change, uint8_t pcf_addr);
//! Gets PCF8574 actual value.
uint8_t getPCFValue();
//! Overloaded (or 'Overriding'?) method, passing pcf_address if more than one is connected
uint8_t getPCFValue(uint8_t pcf_addr);
//! Gets a specific bit value
uint8_t getBitValue(uint8_t bit_position);
//! Overriding method, passing pcf_address if more than one is connected
uint8_t getBitValue(uint8_t bit_position, uint8_t pcf_addr);
//! Starts wire with specific pins and returns status.
bool startI2C(uint8_t sda_pin, uint8_t scl_pin);
//! Overriding method, passing pcf_address if more than one is connected
bool startI2C();
//! Prints help on Serial.
void help();
};

View File

@ -11,6 +11,9 @@
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <PubSubClient.h>
#include <WiFiClient.h>
//define the pins used by the LoRa transceiver module
#define SCK 5
@ -34,25 +37,120 @@
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RST);
#include <WiFiClientSecure.h>
const char* ssid = "Home"; // WiFi SSID
const char* password = "2Drittel%13579"; // WiFi Password
const char* mqttServer = "192.168.2.71";
const int mqttPort = 1883;
const char* clientID = "lora_esp_32";
const char* channelName = "/Drive/CMD/#";
long interval = 1000; // Sende-Intervall in ms
WiFiClient MQTTclient;
PubSubClient client(MQTTclient);
const int relay = 22;
const int check = 23;
void callback(char* topic, byte* payload, unsigned int length) {
//String payload_buff;
//for (int i=0;i<length;i++) {
//payload_buff = payload_buff+String((char)payload[i]);
//}
//Serial.println(payload_buff); // Print out messages.
String line0;
Serial.print("Message arrived [");
Serial.print(topic);
Serial.println("] ");
line0=topic;
if (line0.endsWith("licht")) {
int x = payload[0]-'0';
if (x==1){
Serial.print("on ");
digitalWrite(relay, LOW);
}
if (x==0){
Serial.print("off ");
digitalWrite(relay, HIGH);
}
Serial.println(x);
}
if (line0.endsWith("check")){
int state = digitalRead(check);
if (state==LOW){
client.publish("/drive/check","ON");
Serial.println("ON");
} else{
client.publish("/drive/check","OFF");
Serial.println("OFF");
}
}
}
long lastReconnectAttempt = 0;
boolean reconnect() {
if (client.connect(clientID)) {
client.subscribe(channelName); // Subscribe to channel.
}
return client.connected();
}
const char* ssid = "pipanet"; // WiFi SSID
const char* password = "passatvr6"; // WiFi Password
char buffer[10];
int count = 0;
String LoRaData;
void setup() {
//initialize Serial Monitor
Serial.begin(115200);
// relay
pinMode(relay,OUTPUT);
digitalWrite(relay,HIGH);
// check
pinMode(check,INPUT);
//reset OLED display via software
pinMode(OLED_RST, OUTPUT);
digitalWrite(OLED_RST, LOW);
delay(20);
digitalWrite(OLED_RST, HIGH);
//initialize OLED
Wire.begin(OLED_SDA, OLED_SCL);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3c, false, false)) { // Address 0x3C for 128x32
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
//initialize Serial Monitor
display.clearDisplay();
display.setRotation(2);
display.setTextColor(WHITE);
display.setTextSize(1);
display.setCursor(0,0);
display.print("LORA low power sender ");
display.display();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
display.clearDisplay();
display.setCursor(0,0);
display.print("Wifi search ");
display.setCursor(30,10);
int i = count % 2;
if (i == 0){
display.print("/");
}
else {
display.print("\\");
}
count += 1;
display.display();
delay(100);
}
@ -60,33 +158,10 @@ void setup() {
Serial.print("Connected to ");
Serial.println(ssid);
Serial.println( WiFi.localIP().toString());
//reset OLED display via software
pinMode(OLED_RST, OUTPUT);
digitalWrite(OLED_RST, LOW);
delay(20);
digitalWrite(OLED_RST, HIGH);
//initialize OLED
Wire.begin(OLED_SDA, OLED_SCL);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3c, false, false)) { // Address 0x3C for 128x32
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(1);
display.setCursor(0,0);
display.print("LORA RECEIVER ");
display.display();
Serial.println("LoRa Receiver Test");
//SPI LoRa pins
SPI.begin(SCK, MISO, MOSI, SS);
//setup LoRa transceiver module
@ -97,13 +172,32 @@ void setup() {
while (1);
}
Serial.println("LoRa Initializing OK!");
display.setCursor(0,10);
display.println("LoRa Initializing OK!");
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(1);
display.setCursor(0,0);
display.print("LORA low power sender ");
display.display();
client.setServer(mqttServer, mqttPort); // Connect to PubNub.
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
long now = millis();
if (now - lastReconnectAttempt > 5000) { // Try to reconnect.
lastReconnectAttempt = now;
if (reconnect()) { // Attempt to reconnect.
lastReconnectAttempt = 0;
}
}
} else { // Connected.
client.loop();
}
//try to parse packet
int packetSize = LoRa.parsePacket();
if (packetSize) {
@ -114,17 +208,33 @@ void loop() {
while (LoRa.available()) {
LoRaData = LoRa.readString();
Serial.print(LoRaData);
if (LoRaData.startsWith("!") == true)
{
client.publish("/drive/find","detect");
} else
{
LoRaData.toCharArray(buffer,LoRaData.length());
client.publish("/drive/volt",buffer);
}
}
//print RSSI of packet
int rssi = LoRa.packetRssi();
Serial.print(" with RSSI ");
Serial.println(rssi);
String b;
b = String(rssi);
b.toCharArray(buffer,b.length()+1);
client.publish("/drive/rssi",buffer);
// Dsiplay information
display.clearDisplay();
display.setCursor(0,0);
display.print("LORA RECEIVER");
display.print("LORA ");
display.setCursor(30,0);
display.print(WiFi.localIP().toString());
display.setCursor(0,20);
display.print("Received packet:");
display.setCursor(0,30);
@ -135,4 +245,6 @@ void loop() {
display.print(rssi);
display.display();
}
}

View File

@ -0,0 +1,167 @@
/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/ttgo-lora32-sx1276-arduino-ide/
*********/
#define OLED
#define BAT
//Libraries for LoRa
#include <SPI.h>
#include <LoRa.h>
//Libraries for OLED Display
#ifdef OLED
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#endif
//#include "SSD1306.h" // alias for `#include "SSD1306Wire.h"
//define the pins used by the LoRa transceiver module
#define SCK 5
#define MISO 19
#define MOSI 27
#define SS 18
#define RST 14
#define DIO0 26
//433E6 for Asia
//866E6 for Europe
//915E6 for North America
#define BAND 866E6
#ifdef OLED
//OLED pins
#define OLED_SDA 4
#define OLED_SCL 15
#define OLED_RST 16
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RST);
#endif
#ifdef SLEEP
// deep sleep
#define uS_TO_S_FACTOR 1000000 // conversion factor for micro seconds to seconds
#define TIME_TO_SLEEP 360 // time ESP32 will go to sleep (in seconds) - 99 for (about) 1% duty cycle
uint64_t sleepfor = uS_TO_S_FACTOR * TIME_TO_SLEEP;
#endif
// stores the data on the RTC memory so that it will not be deleted during the deep sleep
RTC_DATA_ATTR int bootCount = 0;
RTC_DATA_ATTR int pckCounter = 0; // sending packet number...
#define BUTTON_PIN_BITMASK 0x1000000000 // 2^36 in hex
#ifdef BAT
const uint8_t vbatPin = 37;
double VBAT; // battery voltage from ESP32 ADC read
#endif
String reason = "Dont know ";
void setup() {
Serial.begin(115200);
pinMode(2,OUTPUT);
Serial.println("LoRa low power Sender Test");
//SPI LoRa pins
SPI.begin(SCK, MISO, MOSI, SS);
//setup LoRa transceiver module
LoRa.setPins(SS, RST, DIO0);
if (!LoRa.begin(BAND)) {
Serial.println("Starting LoRa failed!");
while (1);
}
Serial.println("LoRa init completed");
print_wakeup_reason();
esp_sleep_enable_ext0_wakeup(GPIO_NUM_36,1); //1 = High, 0 = Low
#ifdef OLED
//reset OLED display via software
pinMode(OLED_RST, OUTPUT);
digitalWrite(OLED_RST, LOW);
delay(20);
digitalWrite(OLED_RST, HIGH);
//initialize OLED
Wire.begin(OLED_SDA, OLED_SCL);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3c, false, false)) { // Address 0x3C for 128x32
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(1);
display.setCursor(0,0);
display.print("LORA low power sender ");
display.setCursor(0,10);
display.print(reason);
display.display();
delay(1000);
#endif
//Increments boot number and prints it every reboot
bootCount++;
Serial.println("Boot number: " + String(bootCount));
#ifdef SLEEP
esp_sleep_enable_timer_wakeup(sleepfor);
Serial.println("Setup ESP32 to sleep for every " + String(TIME_TO_SLEEP) + " Seconds");
#endif
Serial.println("Going to sleep now");
Serial.flush(); // waits for the transmission of outgoing serial data to complete
digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
delay(1000);
esp_deep_sleep_start();
}
void loop() { }
void print_wakeup_reason(){
esp_sleep_wakeup_cause_t wakeup_reason;
wakeup_reason = esp_sleep_get_wakeup_cause();
switch(wakeup_reason)
{
case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO");
// send packet
reason = "Found someone "+String(bootCount);
LoRa.beginPacket();
LoRa.print("! Found someone ");
LoRa.print(bootCount);
LoRa.endPacket();
break;
case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer");
// send packet
reason = "Timer ";
#ifdef BAT
VBAT = ReadVoltage(vbatPin);
Serial.print("Vbat = "); Serial.print(VBAT); Serial.println(" Volts");
LoRa.beginPacket();
LoRa.print(String(VBAT));
LoRa.print(bootCount);
LoRa.endPacket();
#endif
break;
case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
}
}
#ifdef BAT
double ReadVoltage(byte pin){
double reading = analogRead(pin); // Reference voltage is 3v3 so maximum reading is 3v3 = 4095 in range 0 to 4095
if(reading < 1 || reading > 4095) return 0;
// return -0.000000000009824 * pow(reading,3) + 0.000000016557283 * pow(reading,2) + 0.000854596860691 * reading + 0.065440348345433;
return -0.000000000000016 * pow(reading,4) + 0.000000000118171 * pow(reading,3)- 0.000000301211691 * pow(reading,2)+ 0.001109019271794 * reading + 0.034143524634089;
} // Added an improved polynomial, use either, comment out as required
#endif

View File

@ -0,0 +1,103 @@
#include <SPI.h>
#include <Wire.h>
#include <SSD1306.h>
#include <LoRa.h>
//#include "images.h"
//#define LORA_BAND 433
//#define LORA_BAND 868
#define LORA_BAND 868
#define OLED_SDA 4
#define OLED_SCL 15
#define OLED_RST 16
#define SCK 5 // GPIO5 -- SX1278's SCK
#define MISO 19 // GPIO19 -- SX1278's MISO
#define MOSI 27 // GPIO27 -- SX1278's MOSI
#define SS 18 // GPIO18 -- SX1278's CS
#define RST 14 // GPIO14 -- SX1278's RESET
#define DI0 26 // GPIO26 -- SX1278's IRQ(Interrupt Request)
SSD1306 display(0x3c, OLED_SDA, OLED_SCL);
// Forward declarations
void displayLoraData(String countStr);
void showLogo();
void setup() {
Serial.begin(115200);
while (!Serial);
Serial.println();
Serial.println("LoRa Transmitter");
// Configure the LED an an output
pinMode(LED_BUILTIN, OUTPUT);
// Configure OLED by setting the OLED Reset HIGH, LOW, and then back HIGH
pinMode(OLED_RST, OUTPUT);
digitalWrite(OLED_RST, HIGH);
delay(100);
digitalWrite(OLED_RST, LOW);
delay(100);
digitalWrite(OLED_RST, HIGH);
display.init();
display.flipScreenVertically();
//showLogo();
delay(2000);
display.clear();
display.setFont(ArialMT_Plain_16);
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString(display.getWidth() / 2, display.getHeight() / 2, "LoRa Transmitter");
display.display();
delay(2000);
// Configure the LoRA radio
SPI.begin(SCK, MISO, MOSI, SS);
LoRa.setPins(SS, RST, DI0);
if (!LoRa.begin(LORA_BAND * 1E6)) {
Serial.println("Starting LoRa failed!");
while (1);
}
Serial.println("init ok");
}
void loop() {
static int counter = 0;
// send packet
LoRa.beginPacket();
LoRa.print("hello ");
LoRa.print(counter);
LoRa.endPacket();
String countStr = String(counter, DEC);
Serial.println(countStr);
displayLoraData(countStr);
// toggle the led to give a visual indication the packet was sent
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
delay(250);
counter++;
delay(1500);
}
void displayLoraData(String countStr) {
display.clear();
display.setTextAlignment(TEXT_ALIGN_LEFT);
display.setFont(ArialMT_Plain_10);
display.drawString(0, 0, "Sending packet: ");
display.drawString(90, 0, countStr);
display.display();
}
© 2021 GitHub, Inc.

View File

@ -1,51 +0,0 @@
const int buttonPin = 2; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
int buttonState = 0;
int count = 0;
boolean now =false;
unsigned long times;
void setup() {
// declare the ledPin as an OUTPUT:
Serial.begin(115200);
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
if (now==false){
if (times ==0){
times = millis();
count += +1;
Serial.println(count);
} else {
unsigned long delta;
delta = millis() -times;
if (delta >1000){
count += +1;
Serial.println(count);
}
}
now=true;
}
digitalWrite(ledPin, LOW);
} else {
// turn LED off:
now= false;
times = 0;
digitalWrite(ledPin, HIGH);
}
}