#include <ESP32Servo.h>
#include <WiFi.h>
#include "DHT.h"
#define DHTPIN 15
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "your_ssid";
const char* password = "your_password";
const char* host = "your_hostname";
Servo myservo;
const int button1Pin = 12;
const int button2Pin = 14;
int button1State = HIGH;
int button2State = HIGH;
int currentPosition = 0;
void setup() {
//DHT setup
Serial.begin(115200);
Serial.println("DHT11 Output!");
dht.begin();
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
//servo setup
Serial.begin(9600);
myservo.attach(18);
myservo.write(currentPosition);
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
}
void loop() {
button1State = digitalRead(button1Pin);
button2State = digitalRead(button2Pin);
if (button1State == LOW) {
currentPosition = 90;
myservo.write(currentPosition);
Serial.println("Button 1 pressed, motor moved to 90 degrees.");
delay(1000);
}
if (button2State == LOW) {
currentPosition = 0;
myservo.write(currentPosition);
Serial.println("Button 2 pressed, motor moved to 0 degrees.");
delay(1000);
}
float temperature = dht.readTemperature();
if(isnan(temperature)){
Serial.println("Failed to read DHT11");
}else{
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" *C");
delay(3000);
}
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 5555;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// This will send the request to the server
client.print(String("GET http://your_hostname/iot_project/connect.php?") +
("&temperature=") + temperature +
" HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 1000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
// Read all the lines of the reply from server and print them to Serial
while(client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}