#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <OneWire.h> // Water profe temp sescer
#include <DallasTemperature.h> // Water profe temp sescer 3-5V
#include <Adafruit_MPU6050.h> //Gyro VDD 2.375V-3.46V 2.375V-3.46V
#include <Adafruit_Sensor.h> //Gyro
#include <Wire.h> //Helps with pins
#include "RTClib.h"
#include <SPI.h> //Helps with pins
#include <WiFi.h> //Wifi
#include <Adafruit_GFX.h>//Adafruit GFX graphics core
#include <Adafruit_SSD1306.h> //OLED Supply voltage: DC : 2.0-5.5V
#include <Adafruit_AHTX0.h> //Temp Supply voltage: DC : 2.0-5.5V
#include <MFRC522.h> //NFC reader 3.3v
#include <SD.h> //SD card 5v
#include <BluetoothSerial.h> //Bluetooth Serial
#include <SparkFun_I2C_Mux_Arduino_Library.h> //I2C Multy plax board
#include <gpio_viewer.h> // To viwe what pins are high or low over wifi. 192.168.1.27:8080
#include <WebServer.h> //The web page
#include <WebSocketsServer.h> //Sending the
#include <Arduino.h>
///////////////////////////////////////////////////////////////////////////////////////////start of funcutions
// list of function prototype in othere tabs
void Webserver();
void DisplyRTC();
void wificonect();
void Jackupordown();
void displayGyrompu2();
void displayGyrompu1();
void Oliverlight();
void displaydcVoltage();
void displayac();
//void Touchbutton();
void Helloworld();
void NFC();
void EBRACKLEDLIGHT();
void Bedroomdata();
void Livingroomdata();
void Ufloor1data();
void Passthrowdata();
void startdisplay();
void getwaterlevel();
void displayonscreen(int delay_time_in_ms); //When you put this in the loop you can put a time in for the delay
void displayTEST();
void watertemp();
void printWifiStatus();
void Fresh_water_temp();
void Outside_temp();
/////////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------ Interrupts pin Startup Oliver test
//const int buttonPin =35
#define Testlight 19
int Testlightbutton = 45;
//-------------------------------------------------Safty
#define EBrakeLED 20
//-------------------------------------------------NFC
#define SS_PIN 10
#define RST_PIN 5
#define RELAY_PIN A5 // the Arduino pin connects to relay
MFRC522 rfid(SS_PIN, RST_PIN);
byte authorizedUID1[4] = {0x3A, 0xC9, 0x6A, 0xCB};
byte authorizedUID2[4] = {0x30, 0x01, 0x8B, 0x15};
//------------------------------------------------ Blynk Startup
//-------------------------------------------------2 cors Startup
//https://github.com/garyexplains/examples/blob/master/Dual_Core_for_RP2040_ESP32_ESP32-S3/esp32_dual_core_example/esp32_dual_core_example.ino
//-------------------------------------------------Screen
//-------------------------------------------------TouchScreen
//-------------------------------------------------Relay
//Close overhang.
//Water on and off.
//open or close the bathroom vent.
//-------------------------------------------------SDCard
File dataFile;
/*
CS = 5;
MOSI = 23;
MISO = 19;
SCK = 18;
*/
//-------------------------------------------------WIFI Startup
//Phone Wifi
//const char* ssid = "iPhone 12 max";
//const char* password = "Godisg00d!";
//Home wifi
const char* ssid = "PGC";
const char* password = "Johnmc12";
const long timeout = 600000; // 10 minutes in milliseconds
//-------------------------------------------------Webserver
int status = WL_IDLE_STATUS;
WebServer server(80); //Put in IP to see web page.
WebSocketsServer webSocket = WebSocketsServer(81); //Port 81 is the port the webSocket will use to update the info.
// GPIOViewer gpio_viewer; // To viwe what pins are high or low over wifi. IP+8080
//-------------------------------------------------BlueTooth
//-------------------------------------------------OLED Screens
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for SSD1306 display connected using I2C
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Declaration for SSD1306 display connected using software SPI:
//#define OLED_MOSI 9
//#define OLED_CLK 10
//#define OLED_DC 11
//#define OLED_CS 12
//#define OLED_RESET 13
//Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);
//-------------------------------------------------Real Time Clock Startup
char daysOfTheWeek[7][24] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
RTC_DS1307 rtc;
#define RTCI2C_SDA 8
#define RTCI2C_SCL 9
//-------------------------------------------------MPU6050 Gyro Sensor Startup
Adafruit_MPU6050 mpu1; //This is the 1st Gyro Sensor
Adafruit_MPU6050 mpu2; //This is the 2nd Gyro Sensor
double currentGYROValue; //The slowed down math
#define jackup 48 //Jackup relay
#define jackdown 47 //Jackdown relay
#define jackbuttonPin 2
int jackbuttonState;
// https://forum.arduino.cc/t/2-mpu6050-with-1-esp32/969374/5
const int Gyro_offset_potentiometer = 17;
int Offsetval;
//-------------------------------------------------Temp/Humidity Startup
//Outside temp
float Outside_temp_sensors = 0.0;
float Fresh_water_temp_sensors = 0.0;
// Data wire is plugged into digital pin 2 on the Arduino
int onewirebuspin = 3;
// Setup a oneWire instance to communicate with any OneWire device
OneWire oneWire(onewirebuspin);
// Pass oneWire reference to DallasTemperature library
DallasTemperature sensors(&oneWire);
//-------------------------------------------------AHT20 Startup
Adafruit_AHTX0 aht;
Adafruit_AHTX0 Bedroom;
Adafruit_AHTX0 Livingroom;
Adafruit_AHTX0 Ufloor1;
Adafruit_AHTX0 Passthrow;
//-------------------------------------------------Water/DC/AC Startup
const int Water_Level = 10; // Analog pin GOI00 pin1 connected to the voltage divider output
const float WR1 = 1000.0; // Resistance of WR1 in the voltage divider in ohms https://ohmslawcalculator.com/voltage-divider-calculator
const float WR2 = 1000.0; // Resistance of WR2 in the voltage divider in ohms
const int DC_Volts = 11; // Analog pin GOI00 pin1 connected to the voltage divider output
const float DCR1 = 10000.0; // Resistance of DCR1 in the voltage divider in ohms
const float DCR2 = 10000.0; // Resistance of DCR2 in the voltage divider in ohms
const int AC_votles = 12; // Analog pin GOI00 pin1 connected to the voltage divider output
const float ACR1 = 10000.0; // Resistance of ACR1 in the voltage divider in ohms
const float ACR2 = 10000.0; // Resistance of ACR2 in the voltage divider in ohms
const int CamperEbrack_votles = 14; // Analog pin GOI00 pin1 connected to the voltage divider output
const float EBR1 = 10000.0; // Resistance of ACR1 in the voltage divider in ohms
const float EBR2 = 10000.0; // Resistance of ACR2 in the voltage divider in ohms
float Water_state; //
float perc; //
// declare sensor and voltage variables
int DCsensorValue;
float DCvoltage;
int ACsensorValue;
float ACvoltage;
int watersensorValue;
float watervoltage;
int camperebrake;
float camperebrakevoltage;
//------------------------------------------------ Interrupts pin Startup
//pinMode(pushButton_pin, INPUT_PULLUP);
// attachInterrupt(buttonPin, getwaterlevel, RISING);
//-------------------------------------------------Touchbutton to move jack
//https://arduinogetstarted.com/tutorials/arduino-touch-sensor
// constants won't change. They're used here to set pin numbers:
const int SENSOR_Buttoon_PIN = 7; // the Arduino's input pin that connects to the sensor's SIGNAL pin
// Variables will change:
int lastState = LOW; // the previous state from the input pin
int currentState; // the current reading from the input pin
//-------------------------------------------------Loop count Startup
int count = 0; //Counts the number of loops from last startup.
/////////////////////////////////////////////////////////////////////////////////////////////////////
void setup()
{ //Started Serial
Serial.begin(115200); // Initialize serial communication
while (!Serial) {
delay(1); // wait for serial port to connect.
}
Serial.println ("SETUP STARTED");
//------------------------------------------------WIFI setup
// Connect to home WiFi
connectToWiFi();
//-------------------------------------------------PIN MODE, List of all pins used.
pinMode(Water_Level, INPUT); //pin 10 "This will help you know when the tank is fill with out running instde to chack"
pinMode(DC_Volts, INPUT); //pin 11 "This will log the power being used from the batterys. We can use this we turn off some things to save power"
pinMode(AC_votles, INPUT); //pin 12 "This will log the power coming in"
pinMode(CamperEbrack_votles, INPUT); //pin 14 "This is to allert you that the Ebrack is on."
pinMode(EBrakeLED, OUTPUT); //pin 20 "This is to allert you that the Ebrack is on."
pinMode(jackup, OUTPUT); //pin 48 "This relay will level the front jack up"
pinMode(jackdown, OUTPUT); //pin 47 "This relay will level the front jack down"
pinMode(jackbuttonPin, INPUT); //pin 36 "This will send the comand to level the front jack. Must be a momentary seitch so if it is not working a person can stop it."
//pinMode(OLED, SDA SCL); //SDA SCL address 0xc3
//pinMode(AHT20, SDA SCL); //SDA SCL address 0x38
//pinMode(SDCard, "",); //
//pinMode(Bedroom1, INPUT); //SDA SCL "To see if it is better to sleep there"
//pinMode(Livingroom1, INPUT); //SDA SCL "To see if it is better to sleep there"
//pinMode(Ufloor1, INPUT); //SDA SCL "Temp senser betwen the floor and the inslation to see tank leaks"
//pinMode(PassThrow1, INPUT); //SDA SCL "Temp senser in the passthrow storage to see water leak and water freez"
pinMode(Testlight, OUTPUT); //pin 19 "For Oliver to play with and let me know this is working"
pinMode(Testlightbutton, INPUT); //pin 45 "For Oliver to play with"
pinMode(Gyro_offset_potentiometer, INPUT); //pin 35 "Defult address 0x68 can be 0x69 of the gyro. This input is to change the offset how level it will be"
pinMode(SENSOR_Buttoon_PIN, INPUT); //pin 7
//pinMode(RELAY_PIN, OUTPUT); // initialize pin as an output.
//digitalWrite(RELAY_PIN, LOW); // deactivate the relay
//pinMode(All onewire temp sensors, INPUT);//pin 3
Wire.begin();
//This it to remind me what pins this board is looking for.
Serial.print("SDA");
Serial.print(SDA);
Serial.print("SCL");
Serial.print(SCL);
/*
//For bigger screens.
//#define OLED_MOSI 9
//#define OLED_CLK 10
//#define OLED_DC 11
//#define OLED_CS 12
//#define OLED_RESET 13
*/
Serial.println("Pin Started are done");
//------------------------------------------------- AHT20 setup
aht.begin();
Serial.println("AHT10 or AHT20 found");
//-------------------------------------------------Webserver setup
// Start WebSocket server
Serial.println("line 243");
webSocket.begin();
Serial.println("Line 245");
webSocket.onEvent(handleWebSocketEvent);
Serial.println("WebSocket server started");
// Start HTTP server
server.on("/", handleRoot);
server.begin();
Serial.println("HTTP server started");
//-------------------------------------------------Touchbutton setup
//-------------------------------------------------2 core setup
//https://www.circuitstate.com/tutorials/how-to-write-parallel-multitasking-applications-for-esp32-using-freertos-arduino/
//-------------------------------------------------SDCard setup
Serial.println("Initialize SD card");
SD.begin(10);
//-------------------------------------------------Relay setup
//-------------------------------------------------BlueTooth setup
//-------------------------------------------------OLED Screens setup
{ // initialize the OLED object
if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
// Uncomment this if you are using SPI
//if(!display.begin(SSD1306_SWITCHCAPVCC)) {
// Serial.println(F("SSD1306 allocation failed"));
// for(;;); // Don't proceed, loop forever
}
// Clear the buffer.
display.clearDisplay();
// Display Text to test. "Hello world"
Helloworld(); //This will help test that you can see all the screen.
//-------------------------------------------------Water setup
//------------------------------------------------Webserver setup
/*
startdisplay();
printWifiStatus(); //This will give me the IP
displayonscreen(10000);
*/
//------------------------------------------------Gyro setup
//boolean mpu_1_is_working = mpu1.begin();
//boolean mpu_2_is_working = mpu2.begin();
mpu1.begin(0x68);
//mpu2.begin(0x69);
mpu1.setAccelerometerRange(MPU6050_RANGE_16_G);
mpu1.setGyroRange(MPU6050_RANGE_250_DEG);
mpu1.setFilterBandwidth(MPU6050_BAND_21_HZ);
Serial.println("mpu1 started");
/*
//If you want to have 2 gyros
mpu2.setAccelerometerRange(MPU6050_RANGE_16_G);
mpu2.setGyroRange(MPU6050_RANGE_250_DEG);
mpu2.setFilterBandwidth(MPU6050_BAND_21_HZ);
Serial.println("mpu2 started");
*/
//------------------------------------------------Real Time Clock setup
/*
Wire.begin(RTCI2C_SDA, RTCI2C_SCL);
if (! rtc.begin())
{
Serial.println("Couldn't find RTC");
Serial.flush();
abort();
}
*/
//----------------------------------------------- Blynk setup core 1
//------------------------------------------------NFC setup
/* SPI.begin(); // init SPI bus
rfid.PCD_Init(); // init MFRC522
pinMode(RELAY_PIN, OUTPUT); // initialize pin as an output.
digitalWrite(RELAY_PIN, LOW); // deactivate the relay
Serial.println("Tap RFID/NFC Tag on reader");
*/
//------------------------------------------------ gpio_viewer
// gpio_viewer.begin();
Serial.println("Setup Complete");
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
void loop()
{ //core 0
webSocket.loop();
server.handleClient();
neopixelWrite(RGB_BUILTIN,0,0,0);//LED off
delay(1000);
neopixelWrite(RGB_BUILTIN,0,0,RGB_BRIGHTNESS); // Blue
//-------------------------------------------------Touchbutton
Touchbutton();
//-------------------------------------------------Bluetooth
//-------------------------------------------------SDCard loop
displaySDcard();
//-------------------------------------------------Relay loop
//-------------------------------------------------BlueTooth loop
//-------------------------------------------------OLED Screens loop
//-------------------------------------------------Temp/Humidity loop
startdisplay();
Outside_temp();
Fresh_water_temp();
displayonscreen(1000);
startdisplay();
Bedroomdata();
Livingroomdata();
Ufloor1data();
Passthrowdata();
displayonscreen(1000);
aht20temp();
//-------------------------------------------------Water loop
// May end up doing LEDs or a alart
watersensorValue = analogRead(Water_Level); // Read the analog input
watervoltage = watersensorValue * (3.3 / 4095.0); // Convert the analog reading to voltage (3.3V is the ESP32-S3 voltage)
watervoltage = watervoltage * (WR1 + WR2) / WR2; // Calculate the actual voltage using the voltage divider formula
//Water level lights.
Water_state = Water_Level * 3.3/1023;
perc = map(Water_state, 4.0, 10.0, 0, 100);
startdisplay();
getwaterlevel();
displayonscreen(1000);
//------------------------------------------------ DC/AC voltage loop
DCsensorValue = analogRead(DC_Volts); // Read the analog input
DCvoltage = DCsensorValue * (3.3 / 4095.0); // Convert the analog reading to voltage (3.3V is the ESP32-S3 voltage)
DCvoltage = DCvoltage * (DCR1 + DCR2) / DCR2; // Calculate the actual voltage using the voltage divider formula
startdisplay();
displaydcVoltage();
ACsensorValue = analogRead(AC_votles); // Read the analog input
ACvoltage = ACsensorValue * (3.3 / 4095.0); // Convert the analog reading to voltage (3.3V is the ESP32-S3 voltage)
ACvoltage = ACvoltage * (ACR1 + ACR2) / ACR2; // Calculate the actual voltage using the voltage divider formula
displayac();
displayonscreen(1000);
//-------------------------------------------------Safety
startdisplay();
EBRACKLEDLIGHT(); // This will alert me that the Ebrack is on
displayonscreen(1000);
//-------------------------------------------------Count to see how long it has worked.
neopixelWrite(RGB_BUILTIN,RGB_BRIGHTNESS,0,0); // Red
delay(1000);
neopixelWrite(RGB_BUILTIN,0,RGB_BRIGHTNESS,0); // Green
delay(1000);
Oliverlight();
Serial.println ("OLIVER Light");
//-------------------------------------------------Gyro loop 1
//This will setup gyro 1
sensors_event_t a1, g1, temp1;
mpu1.getEvent(&a1, &g1, &temp1);
/*
//This will setup gyro 1
sensors_event_t a2, g2, temp2;
mpu2.getEvent(&a2, &g2, &temp2);
*/
startdisplay();
displayGyrompu1();
displayonscreen(1000);
startdisplay();
// displayGyrompu2();
displayonscreen(1000);
Serial.println("Jack");
// Jackupordown();// The button will level the camper.
Serial.println(jackbuttonState);
//This will stop the jack.
digitalWrite(jackup, LOW);
digitalWrite(jackdown, LOW);
//-------------------------------------------------WIFI loop
// // Check if connected to WiFi
/* if (WiFi.status() == WL_CONNECTED) {
// Connected to WiFi
Serial.println("Connected to WiFi!");
// Your main code here
// Add delay if needed to prevent flooding
delay(100);
} else {
// Failed to connect to WiFi
Serial.println("Failed to connect to WiFi!");
// Try to create an access point after timeout
if (millis() > timeout) {
createAccessPoint();
}
// Retry connection to home WiFi
// connectToWiFi();
}
*/
SensordataWebSocket();
//-------------------------------------------------Real Time Clock loop 1
/*
startdisplay();
DateTime now = rtc.now();
DisplyRTC();
displayonscreen(1000);
*/
//-------------------------------------------------Webserver
//-------------------------------------------------NFC
// NFC();
Serial.print("Loop Count Value: ");
Serial.println(++count);
}
////////////////////////////////////////////////////////////////////////////////
void Outside_temp(){
sensors.requestTemperatures(); //Read all 1-wire temp sensors.
//You can tell it what sensor you are asking for by changing the number in the (). Count starts at 0.
Outside_temp_sensors = sensors.getTempFByIndex(0); //Temp in fahrenheit. sensors.getTempCByIndex for Celsius
Serial.print("1-Wire Outside Temperature is: ");
Serial.println(Outside_temp_sensors);}
void Fresh_water_temp(){
sensors.requestTemperatures(); //Read all 1-wire temp sensors.
//You can tell it what sensor you are asking for by changing the number in the (). Count starts at 0.
Fresh_water_temp_sensors = sensors.getTempFByIndex(1); //Temp in fahrenheit. sensors.getTempCByIndex for Celsius
Serial.print("1-Wire Water Temperature is: ");
Serial.println(Fresh_water_temp_sensors);}
void aht20temp()
{
sensors_event_t humidity, temp;
aht.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data
display.print("Temperature: "); display.print(temp.temperature); display.println(" degrees C");
Serial.print("Temperature: "); Serial.print(temp.temperature); Serial.println(" degrees C");
display.print("Humidity: "); display.print(humidity.relative_humidity); display.println("% rH");
Serial.print("Humidity: "); Serial.print(humidity.relative_humidity); Serial.println("% rH");
}
void Bedroomdata()
{
sensors_event_t humidity, temp;
aht.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data
display.println("Bedroomdata");
Serial.println("Bedroomdata");
display.print("Temperature: "); display.print((temp.temperature * 9) / 5 + 32); display.println(" degrees F");
Serial.print("Temperature: "); Serial.print((temp.temperature * 9) / 5 + 32); Serial.println(" degrees F");
display.print("Humidity: "); display.print(humidity.relative_humidity); display.println("% rH");
Serial.print("Humidity: "); Serial.print(humidity.relative_humidity); Serial.println("% rH");
}
void Livingroomdata()
{
sensors_event_t humidity, temp;
aht.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data
display.println("Livingroomdata");
Serial.println("Livingroomdata");
display.print("Temperature: "); display.print((temp.temperature * 9) / 5 + 32); display.println(" degrees F");
Serial.print("Temperature: "); Serial.print((temp.temperature * 9) / 5 + 32); Serial.println(" degrees F");
display.print("Humidity: "); display.print(humidity.relative_humidity); display.println("% rH");
Serial.print("Humidity: "); Serial.print(humidity.relative_humidity); Serial.println("% rH");
}
void Ufloor1data()
{
sensors_event_t humidity, temp;
aht.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data
display.println("Ufloor1data");
Serial.println("Ufloor1data");
display.print("Temperature: "); display.print((temp.temperature * 9) / 5 + 32); display.println(" degrees F");
Serial.print("Temperature: "); Serial.print((temp.temperature * 9) / 5 + 32); Serial.println(" degrees F");
display.print("Humidity: "); display.print(humidity.relative_humidity); display.println("% rH");
Serial.print("Humidity: "); Serial.print(humidity.relative_humidity); Serial.println("% rH");
}
void Passthrowdata()
{
display.setCursor(0,0);
sensors_event_t humidity, temp;
aht.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data
display.println("Passthrow");
Serial.println("Passthrow");
display.print("Temperature: "); display.print((temp.temperature * 9) / 5 + 32); display.println(" degrees F");
Serial.print("Temperature: "); Serial.print((temp.temperature * 9) / 5 + 32); Serial.println(" degrees F");
display.print("Humidity: "); display.print(humidity.relative_humidity); display.println("% rH");
Serial.print("Humidity: "); Serial.print(humidity.relative_humidity); Serial.println("% rH");
}
/*
byte celsius = 26;
byte fahrenheit = (celsius * 9) / 5 + 32;
*/
// get_Humidity(); and get_Temp(); add the name of the sensor in to the ()
float get_Humidity(Adafruit_AHTX0 sensor){
sensors_event_t humidity, temp;
sensor.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data
return humidity.relative_humidity;
}
float get_Temp(Adafruit_AHTX0 sensor){
sensors_event_t humidity, temp;
sensor.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data
return temp.temperature;
}
//---------------------------------------------------Touch button
void Touchbutton()
{
// read the state of the the input pin:
currentState = digitalRead(SENSOR_Buttoon_PIN);
if(lastState == LOW && currentState == HIGH)
Serial.println("The sensor is touched");
else if(lastState == HIGH && currentState == LOW)
Serial.println("The sensor is is released");
// save the the last state
lastState = currentState;
}
//void Touchbutton(){Serial.println("SDA");}
//https://docs.arduino.cc/software/ide-v2/tutorials/ide-v2-serial-plotter/
//-------------------------------------------------Gyro
void displayGyrompu1()
{
//Offset user a potentiometer Gyro_offset_potentiometer pin 13
Offsetval = analogRead(Gyro_offset_potentiometer); //Reads the value of the potentiometer
Offsetval = map(Offsetval, 0, 4095, -50, 50); //Min Max for the offset. 4095 for esp32 1023 UNOs
sensors_event_t a1, g1, temp1;
mpu1.getEvent(&a1, &g1, &temp1);
display.setCursor(0,0);
display.print("accx1,");
display.print("accY1,");
display.print("accZ1,");
display.setCursor(0,10);
display.print(a1.acceleration.x + Offsetval);
display.print(",");
display.print(a1.acceleration.y);
display.print(",");
display.print(a1.acceleration.z);
display.setCursor(0,20);
display.print("gyrox1,");
display.print("gyroY1,");
display.print("gyroZ1,");
display.setCursor(0,30);
display.print(",");
display.print(g1.gyro.x);
display.print(",");
display.print(g1.gyro.y);
display.print(",");
display.print(g1.gyro.z);
display.print("");
Serial.print("accx1,");
Serial.print(a1.acceleration.x + Offsetval);
Serial.print(",");
Serial.print("accY1,");
Serial.print(a1.acceleration.y);
Serial.print(",");
Serial.println("accZ1,");
Serial.print(a1.acceleration.z);
Serial.print(",");
Serial.print("gyrox1,");
Serial.print(g1.gyro.x);
Serial.print(",");
Serial.print("gyroY1,");
Serial.print(g1.gyro.y);
Serial.print(",");
Serial.println("gyroZ1,");
Serial.print(g1.gyro.z);
Serial.print(",");
Serial.println("");
Serial.print("Gyro1 Temperature: ");
Serial.print(temp1.temperature);
Serial.println(" degC");
/*
//Serial.printf("offset: %i + %f ?= %f\n", Offsetval, a1.acceleration.x, a1.acceleration.x + Offsetval);
//Serial.printf("accX: %2f , accY: %2f , accZ: %2f \nGyroX: %2f , GyroY: %2f , GyroZ: %2f\nTemp: %2f Celcius\n", a1.acceleration.x, a1.acceleration.y, a1.acceleration.z, g1.gyro.x, g1.gyro.y, g1.gyro.z, temp1.temperature);
char outStr[150];
sprintf(outStr, "accX: %2f , accY: %2f , accZ: %2f \nGyroX: %2f , GyroY: %2f , GyroZ: %2f\nTemp: %2f Celcius\n", a1.acceleration.x, a1.acceleration.y, a1.acceleration.z, g1.gyro.x, g1.gyro.y, g1.gyro.z, temp1.temperature);
Serial.print(outStr);
display.print(outStr);
*/
}
void displayGyrompu2()
{
Offsetval = analogRead(Gyro_offset_potentiometer); //Reads the value of the potentiometer (value between 0 and 1023)
Offsetval = map(Offsetval, 0, 4095, -50, 50); //Min Max for the offset. 4095 for esp32 1023 UNOs
sensors_event_t a2, g2, temp2;
mpu2.getEvent(&a2, &g2, &temp2);
display.setCursor(0,0);
Serial.print("accx2,");
display.print("accx2,");
Serial.print("accY2,");
display.print("accY2,");
Serial.println("accZ2,");
display.print("accZ2,");
display.setCursor(0,10);
Serial.print(a2.acceleration.x + Offsetval);
display.print(a2.acceleration.x);
Serial.print(",");
display.print(",");
Serial.print(a2.acceleration.y);
display.print(a2.acceleration.y);
Serial.print(",");
display.print(",");
Serial.println(a2.acceleration.z);
display.print(a2.acceleration.z);
display.setCursor(0,20);
Serial.print("gyrox2,");
display.print("gyrox2,");
Serial.print("gyroY2,");
display.print("gyroY2,");
Serial.println("gyroZ2,");
display.print("gyroZ2,");
display.setCursor(0,30);
Serial.print(",");
display.print(",");
Serial.print(g2.gyro.x);
display.print(g2.gyro.x);
Serial.print(",");
display.print(",");
Serial.print(g2.gyro.y);
display.print(g2.gyro.y);
Serial.print(",");
display.print(",");
Serial.print(g2.gyro.z);
display.print(g2.gyro.z);
Serial.println("");
display.print("");
Serial.print("Temperature:2 ");
Serial.print(temp2.temperature);
Serial.println(" degC");
}
//-------------------------------------------------Jackupordown
void Jackupordown ()
{
sensors_event_t a1, g1, temp1;
mpu1.getEvent(&a1, &g1, &temp1);
double newValue = a1.acceleration.y; // get the true instant reading
currentGYROValue = 0.9* currentGYROValue + 0.1 * newValue; // 90% of the old value, 10% of the new value
jackbuttonState = digitalRead(jackbuttonPin);
int counter = 0;
while (jackbuttonState == HIGH)
{
Serial.println(jackbuttonState);
jackbuttonState = digitalRead(jackbuttonPin);
newValue = a1.acceleration.y;
if (newValue > 1)
{
digitalWrite(jackup, HIGH);
Serial.println("UP");
Serial.println(newValue);
digitalWrite(jackdown, LOW);
jackbuttonState = digitalRead(jackbuttonPin);
delay(500);
}
if(newValue>-1 && newValue<1) {digitalWrite(jackup, LOW);
digitalWrite(jackdown, LOW); delay(500); break;}
else if (newValue < -1)
{
digitalWrite(jackdown, HIGH);
Serial.println("down");
Serial.println(newValue);
digitalWrite(jackup, LOW);
jackbuttonState = digitalRead(jackbuttonPin);
delay(500);
}
}
}
//---------------------------------------------------NFC
void NFC()
{
//Tutorial page: https://arduinogetstarted.com/tutorials/arduino-rfid-nfc-relay
if (rfid.PICC_IsNewCardPresent())
{ // new tag is available
if (rfid.PICC_ReadCardSerial())
{ // NUID has been readed
MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
if (rfid.uid.uidByte[0] == authorizedUID1[0] &&
rfid.uid.uidByte[1] == authorizedUID1[1] &&
rfid.uid.uidByte[2] == authorizedUID1[2] &&
rfid.uid.uidByte[3] == authorizedUID1[3] )
{
Serial.println("Authorized Tag 1");
digitalWrite(RELAY_PIN, HIGH); // activate the relay for 2 seconds
delay(2000);
digitalWrite(RELAY_PIN, LOW); // deactivate the relay
}
else
if (rfid.uid.uidByte[0] == authorizedUID2[0] &&
rfid.uid.uidByte[1] == authorizedUID2[1] &&
rfid.uid.uidByte[2] == authorizedUID2[2] &&
rfid.uid.uidByte[3] == authorizedUID2[3] )
{
Serial.println("Authorized Tag 2");
digitalWrite(RELAY_PIN, HIGH); // activate the relay for 2 seconds
delay(2000);
digitalWrite(RELAY_PIN, LOW); // deactivate the relay
}
else
{
Serial.print("Unauthorized Tag with UID:");
for (int i = 0; i < rfid.uid.size; i++)
{
Serial.print(rfid.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(rfid.uid.uidByte[i], HEX);
}
Serial.println();
}
rfid.PICC_HaltA(); // halt PICC
rfid.PCD_StopCrypto1(); // stop encryption on PCD
}
}
}
//-------------------------------------------------OLED Screens
void displayTEST()
{ // Clear the display
display.clearDisplay();
//Set the color - always use white despite actual display color
display.setTextColor(WHITE);
//Set the font size
display.setTextSize(1);
//Set the cursor coordinates
for(int i =0; i< 55;i+=9)
{
display.setCursor(0,i);
display.println(i);
display.display();
delay(1000);
}
}
void startdisplay()
{
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
}
void displayonscreen(int delay_time_in_ms)
{
display.display();
delay(delay_time_in_ms);
}
//---------------------------------------------------Screen test
void Helloworld()
{
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("Hello world!");
display.setCursor(0,10);
display.println("Hello world!");
display.setCursor(0,20);
display.println("Hello world!");
display.setCursor(0,30);
display.println("Hello world!");
display.setCursor(0,40);
display.println("Hello world!");
display.setCursor(0,50);
display.println("Hello world!");
display.display();
delay(2000);
display.clearDisplay();
}
//---------------------------------------------------Oliver test light
void Oliverlight()
{
if (Testlightbutton = 0){digitalWrite(Testlight, HIGH);}
else {digitalWrite(Testlight, LOW);}
}
//-------------------------------------------------Real Time Clock
void DisplyRTC()
{
DateTime now = rtc.now();
display.setCursor(0,0);
Serial.print("Date: ");
display.print("Date: ");
Serial.print(now.year(), DEC);
display.print(now.year(), DEC);
Serial.print('/');
display.print('/');
Serial.print(now.month(), DEC);
display.print(now.month(), DEC);
Serial.print('/');
display.print('/');
Serial.print(now.day(), DEC);
display.print(now.day(), DEC);
display.setCursor(0,10);
Serial.print(" (");
display.print("(");
Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
display.print(daysOfTheWeek[now.dayOfTheWeek()]);
Serial.print(") ");
display.print(") ");
Serial.print(now.hour(), DEC);
display.print(now.hour(), DEC);
Serial.print(':');
display.print(':');
Serial.print(now.minute(), DEC);
display.print(now.minute(), DEC);
Serial.print(':');
display.print(':');
Serial.print(now.second(), DEC);
display.print(now.second(), DEC);
Serial.println();
}
//-------------------------------------------------SDCard
/*
MOSI - pin 23.
MISO - pin 19.
CLK - pin 18.
CS - pin 5.
*/
void displaySDcard()
{ //The gole is to have a long term doc to see trends
/*
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
// Log data to SD card
dataFile = SD.open("data.txt", FILE_WRITE);
if (dataFile) {
/*
dataFile.print ("Bedroom Temperature: ");
dataFile.print (temp.temperature);
dataFile.print (",");
dataFile.print ("Livingroom Temperature: ");
dataFile.print (temp.temperature);
dataFile.print (",");
dataFile.print ("Under Floor Temperature: ");
dataFile.print (temp.temperature);
dataFile.print (",");
dataFile.print ("Pasthrow Temperature: ");
dataFile.print (temp.temperature);
dataFile.print (",");
dataFile.print ("Bedroom Humidity: ");
dataFile.print (humidity.relative_humidity);
dataFile.print (",");
dataFile.print ("Livingroom Humidity: ");
dataFile.print (humidity.relative_humidity);
dataFile.print (",");
dataFile.print ("Under Floor Humidity: ");
dataFile.print (humidity.relative_humidity);
dataFile.print (",");
dataFile.print ("Pasthrow Humidity: ");
dataFile.print (humidity.relative_humidity);
dataFile.print (",");
dataFile.print ("Fresh water temp");
dataFile.print
dataFile.print (",");
dataFile.print ("Fresh water level");
dataFile.print
dataFile.print (",");
dataFile.print ("Outside temp");
dataFile.print
dataFile.print (",");
dataFile.print ("Ebrack on or off")
dataFile.print
dataFile.print (",");
dataFile.print ("Water level: ");
dataFile.print ((perc);, ("%");)
dataFile.print (",");
dataFile.print ("AC Voltage: ");
dataFile.print (vol);
dataFile.print (",");
dataFile.print ("DC Voltage: ");
dataFile.print (vol);
dataFile.print (",");
dataFile.print ("Gyro #1:");
dataFile.print(a1.acceleration.x);
dataFile.print (",");
dataFile.printa1.acceleration.y);
dataFile.print (",");
dataFile.print(a1.acceleration.z);
dataFile.print (",");
dataFile.print(g1.gyro.x);
dataFile.print (",");
dataFile.print(g1.gyro.y);
dataFile.print (",");
dataFile.print(g1.gyro.z);
dataFile.print (",");
dataFile.print("Last NFC Read");
dataFile.print
dataFile.print (",");
dataFile.println
dataFile.close();
Serial.println("Data written to SD card.");
display.println("Data written to SD card.");
} else {
Serial.println("Error opening data.txt for writing.");
display.println("Error opening data.txt for writing.");
}
display.display();
}
*/
}
/*
SD card attached to SPI bus as follows:
** SDO - pin 11
** SDI - pin 12
** CLK - pin 13
** CS - depends on your SD card shield or module.
Pin 10 used here for consistency with other Arduino examples
(for MKR Zero SD: SDCARD_SS_PIN)
*/
//---------------------------------------------------DC/AC
void displaydcVoltage()
{
Serial.print("DC Voltage: ");
Serial.print(DCvoltage);
Serial.println("V");
display.setCursor(0,0);
display.print("DC Voltage: ");
display.print(DCvoltage);
display.print(" V");
}
void displayac()
{
display.setCursor(0,20);
display.print("AC Voltage:");
Serial.print("AC Voltage: ");
display.print(ACvoltage);
Serial.print(ACvoltage);
display.print("V");
Serial.println("V");
}
//---------------------------------------------------Safety
void EBRACKLEDLIGHT()
{
camperebrakevoltage = analogRead(CamperEbrack_votles); // Read the analog input
camperebrake = camperebrakevoltage * (3.3 / 4095.0); // Convert the analog reading to voltage (3.3V is the ESP32-S3 voltage)
camperebrake = camperebrake * (EBR1 + EBR2) / EBR2;
/*ACsensorValue = analogRead(AC_votles); // Read the analog input
ACvoltage = ACsensorValue * (3.3 / 4095.0); // Convert the analog reading to voltage (3.3V is the ESP32-S3 voltage)
ACvoltage = ACvoltage * (ACR1 + ACR2) / ACR2; // Calculate the actual voltage using the voltage divider formula
*/
Serial.print("EBrake Voltage: ");
Serial.print(camperebrakevoltage);
Serial.println("V");
display.setCursor(0,0);
display.print("EBrake Voltage: ");
display.print(camperebrakevoltage);
display.print(" V");
if (camperebrake > 1){
digitalWrite(EBrakeLED, HIGH);}
else {
digitalWrite(EBrakeLED, LOW);}
}
//---------------------------------------------------Water
void getwaterlevel()
{
if (watervoltage >= 8.0 && watervoltage <= 20.0) {Serial.println("Low Water");}
if (watervoltage >= 6.0 && watervoltage <= 7.0) {Serial.println("Half Water");}
if (watervoltage >= 4.0 && watervoltage <= 5.0) {Serial.println("Full Water");}
//if (myVal > lowerBound && myVal < upperBound) {do this}
display.setCursor(0,0);
display.print("Water Voltage:");
Serial.print("Water Voltage: ");
display.print(watervoltage);
Serial.print(watervoltage);
display.print("V");
Serial.println(" V");
display.setCursor(0,20);
display.print("Water Level");
Serial.print("Water Level");
display.print(perc);
Serial.print(perc);
display.print("%");
Serial.println("%");
}
//---------------------------------------------------Webserver
// This will let me know whay the IP address is for me to connect to. both on Serial.print and OLED
void printWifiStatus() // IP address
{
// print your board's IP address:
display.setCursor(0,0);
Serial.print("IP Address: ");
display.print("IP Address: ");
Serial.println(WiFi.localIP());
display.println(WiFi.localIP());
// print the received signal strength:
display.setCursor(0,10);
Serial.print("signal strength (RSSI):");
display.print("signal strength (RSSI):");
Serial.print(WiFi.RSSI());
display.print(WiFi.RSSI());
Serial.println(" dBm");
display.println(" dBm");
}
void connectToWiFi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(500);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\nWiFi connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("\nFailed to connect to WiFi!");
}
}
void createAccessPoint() {
Serial.println("Creating access point...");
WiFi.disconnect(); // Disconnect from previous WiFi connection
WiFi.softAP("MyArduinoAP", "password"); // Set up soft access point
Serial.println("Access point created!");
Serial.print("IP address: ");
Serial.println(WiFi.softAPIP());
}
void handleRoot() {
Serial.println("HandleRoot started");
String html = "<!DOCTYPE html><html><head><title>ESP32 Sensor Data</title></head><body>";
html += "<h1>ESP32 Sensor Data</h1>";
html += "<h1> </h1>";
html += "<h3>Temperature - Humidity</h3>";
html += "<p>Temperature: <span id='temp'></span> °C</p>";
html += "<p>Humidity: <span id='hum'></span> %</p>";
html += "<p>Bedroom Temperature: <span id='Bedroomtemp'></span> °C</p>";
html += "<p>Bedroom Humidity: <span id='Bedroomhum'></span> %</p>";
html += "<p>Livingroom Temperature: <span id='Livingroomtemp'></span> °C</p>";
html += "<p>Livingroom Humidity: <span id='Livingroomhum'></span> %</p>";
html += "<p>Ufloor1 Temperature: <span id='Ufloor1temp'></span> °C</p>";
html += "<p>Ufloor1 Humidity: <span id='Ufloor1hum'></span> %</p>";
html += "<p>Passthrow Temperature: <span id='Passthrowtemp'></span> °C</p>";
html += "<p>Passthrow Humidity: <span id='Passthrowhum'></span> %</p>";
html += "<h1> </h1>";
html += "<h3>Water Level, Tank Temp</h3>";
html += "<p>Fresh Water Temp: <span id='Fresh_Water_Temp'></span></p>";
html += "<p>Outside Temp: <span id='Outside_temp'></span></p>";
html += "<p>Water Perc Full: <span id='Waterperc'></span></p>";
html += "<h1> </h1>";
html += "<h3>Gyro</h3>";
html += "<p>Accelerometer X: <span id='accel_x'></span></p>";
html += "<p>Accelerometer Y: <span id='accel_y'></span></p>";
html += "<p>Accelerometer Z: <span id='accel_z'></span></p>";
html += "<p>Gyro X: <span id='gyro_x'></span></p>";
html += "<p>Gyro Y: <span id='gyro_y'></span></p>";
html += "<p>Gyro Z: <span id='gyro_z'></span></p>";
html += "<h1> </h1>";
html += "<h3>Votage</h3>";
html += "<p>DC Voltage: <span id='DCvoltage'></span></p>";
html += "<p>AC Voltage: <span id='ACvoltage'></span></p>";
html += "<p>Camper E-brake Voltage: <span id='camperebrakevoltage'></span></p>";
html += "<script>var socket = new WebSocket('ws://' + window.location.hostname + ':81/');";
html += "socket.onmessage = function(event) { var data = JSON.parse(event.data);";
html += "document.getElementById('Bedroomtemp').innerHTML = data.Bedroomtemperature;";
html += "document.getElementById('Bedroomhum').innerHTML = data.Bedroomhumidity;";
html += "document.getElementById('Livingroomtemp').innerHTML = data.Livingroomtemperature;";
html += "document.getElementById('Livingroomhum').innerHTML = data.Livingroomhumidity;";
html += "document.getElementById('Ufloor1temp').innerHTML = data.Ufloor1temperature;";
html += "document.getElementById('Ufloor1hum').innerHTML = data.Ufloor1humidity;";
html += "document.getElementById('Passthrowtemp').innerHTML = data.Passthrowtemperature;";
html += "document.getElementById('Passthrowhum').innerHTML = data.Passthrowhumidity;";
html += "document.getElementById('Outside_temp').innerHTML = data.Outside_temp;";
html += "document.getElementById('Fresh_Water_Temp').innerHTML = data.Fresh_Water_Temp;";
html += "document.getElementById('Waterperc').innerHTML = data.Waterperc;";
html += "document.getElementById('accel_x').innerHTML = data.a1.accelerometer.x;";
html += "document.getElementById('accel_y').innerHTML = data.a1.accelerometer.y;";
html += "document.getElementById('accel_z').innerHTML = data.a1.accelerometer.z;";
html += "document.getElementById('gyro_x').innerHTML = data.a1.gyro.x;";
html += "document.getElementById('gyro_y').innerHTML = data.a1.gyro.y;";
html += "document.getElementById('gyro_z').innerHTML = data.a1.gyro.z;";
html += "document.getElementById('DCvoltage').innerHTML = data.DCvoltage;";
html += "document.getElementById('ACvoltage').innerHTML = data.ACvoltage;";
html += "document.getElementById('camperebrakevoltage').innerHTML = data.camperebrakevoltage;};</script>";
html += "</body></html>";
server.send(200, "text/html", html);
Serial.println("HandleRoot done");
}
void handleWebSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
Serial.println("handleWebSocketEvent started.");
// Handle WebSocket events here if needed
switch(type) {
case WStype_DISCONNECTED:
Serial.printf("[%u] WebSocket client disconnected\n", num);
break;
case WStype_CONNECTED:
Serial.printf("[%u] WebSocket client connected from IP %s\n", num, webSocket.remoteIP(num).toString().c_str());
break;
case WStype_TEXT:
Serial.printf("[%u] Received text: %s\n", num, payload);
break;
case WStype_BIN:
Serial.printf("[%u] Received binary data\n", num);
break;
default:
break;
}
}
void SensordataWebSocket(){
Serial.println("SensordataWebSocket started.");
sensors_event_t a1, g1, temp1;
mpu1.getEvent(&a1, &g1, &temp1);
//AHT20temp
String sensorData =
"{\"humidity\":" + String(get_Humidity(aht)) + ",\"temperature\":" + String(get_Temp(aht)) +
",\"Bedroomhumidity\":" + String(get_Humidity(Bedroom)) + ",\"Bedroomtemperature\":" + String(get_Temp(Bedroom)) +
",\"Livingroomhumidity\":" + String(get_Humidity(Livingroom)) + ",\"Livingroomtemperature\":" + String(get_Temp(Livingroom)) +
",\"Ufloor1humidity\":" + String(get_Humidity(Ufloor1)) + ",\"Ufloor1temperature\":" + String(get_Temp(Ufloor1)) +
",\"Passthrowhumidity\":" + String(get_Humidity(Passthrow)) + ",\"Passthrowtemperature\":" + String(get_Temp(Passthrow)) +
Serial.println("Temp sent");
//Water level, Temp Water/Outside
",\"Outside_temp\":" + String(Outside_temp_sensors) +
",\"Fresh_Water_Temp\":" + String(Fresh_water_temp_sensors) +
",\"Waterperc\":" + String(perc) +
//Gyro
",\"gyro_x\":" + String(g1.gyro.x) +
",\"gyro_y\":" + String(g1.gyro.y) +
",\"gyro_z\":" + String(g1.gyro.z) +
",\"acceleration_z\":" + String(a1.acceleration.z) +
",\"acceleration_y\":" + String(a1.acceleration.y) +
",\"acceleration_x_Offsetval\":" + String(a1.acceleration.x + Offsetval) +
",\"Gyrotemperature\":" + String(temp1.temperature) +
Serial.println("Gyro sent");
//Votage
",\"DCvoltage\":" + String(DCvoltage) +
",\"ACvoltage\":" + String(ACvoltage) +
",\"camperebrakevoltage\":" + String(camperebrakevoltage) +
Serial.println("voltage and weater sent");
"}";
webSocket.broadcastTXT(sensorData);
// Debug message
Serial.println("Sensor data sent over WebSocket");
}
//ToDoList Add Time stamp to the website