#define LuminancePin 33
#define TermoSensPin 25
#define PIRPin 23
#define LampsPin 17
#define AirConditionerPin 16
// Temp control:
const float BETA = 3950; // should match the Beta Coefficient of the thermistor
// Luminance control:
const float GAMMA = 0.7;
const float RL10 = 50;
float luminance = 0;
float temperatureCelsius = 0;
void config() {
// Inputs
pinMode(LuminancePin, INPUT);
pinMode(TermoSensPin, INPUT);
pinMode(PIRPin, INPUT);
// Outputs
pinMode(LampsPin, OUTPUT);
pinMode(AirConditionerPin, OUTPUT);
// Set initial state of outputs to LOW (off)
digitalWrite(LampsPin, LOW);
digitalWrite(AirConditionerPin, LOW);
}
void setup() {
config();
Serial.begin(115200);
Serial.println("Hello, ESP32!");
}
void getSensorData() {
// Calculate temperature
int analogValue = analogRead(TermoSensPin);
temperatureCelsius = 1 / (log(1 / (4096.0 / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
// Calculate luminance
int analogValueLuminance = analogRead(LuminancePin);
float voltage = analogValueLuminance / 4096.0 * 3.3; // Промяна на 5 към 3.3 за ESP32
float resistance = 2000 * voltage / (3.3 - voltage);
luminance = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
// Visualize sensor data:
Serial.println("New data:");
Serial.print("Room temperature: ");
Serial.print(temperatureCelsius);
Serial.println(" °C");
Serial.print("Room luminance: ");
Serial.print(luminance);
Serial.println(" lx");
Serial.print("PIR state: ");
Serial.println(digitalRead(PIRPin));
}
void startStopLamps(bool OnOff) {
digitalWrite(LampsPin, OnOff);
Serial.print("Lamps turned ");
Serial.println(OnOff ? "ON" : "OFF");
}
void startStopAirConditioner(bool OnOff) {
digitalWrite(AirConditionerPin, OnOff);
Serial.print("Air conditioner turned ");
Serial.println(OnOff ? "ON" : "OFF");
}
void loop() {
// Get sensor data
getSensorData();
// State machine
if (luminance > 80) {
startStopLamps(false);
} else if (luminance <= 80 && digitalRead(PIRPin) == HIGH) {
startStopLamps(true);
}
if (temperatureCelsius > 28.0) {
startStopAirConditioner(true);
} else if (temperatureCelsius <= 22.0) {
startStopAirConditioner(false);
}
delay(1000); // This speeds up the simulation
}