🍀ค่ายคอมพิวเตอร์ SMT ม.1, ม.4 ปีการศึกษา 2568
โรงเรียนพนมเบญจา อ.เขาพนม จ.กระบี่🤟
โรงเรียนพนมเบญจา อ.เขาพนม จ.กระบี่🤟
เอกสารประกอบการอบรม
Code Arduino
int ledPin = 2; // LED บนบอร์ด ESP32 ส่วนใหญ่ใช้ GPIO 2
void setup() {
pinMode(ledPin, OUTPUT); // กำหนดขาเป็น Output
}
void loop() {
digitalWrite(ledPin, HIGH); // เปิดไฟ
delay(1000); // หน่วงเวลา 1 วินาที
digitalWrite(ledPin, LOW); // ปิดไฟ
delay(1000); // หน่วงเวลา 1 วินาที
}
int redPin = 25;
int greenPin = 26;
int bluePin = 27;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
// สีแดง
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
digitalWrite(bluePin, HIGH);
delay(1000);
// สีเขียว
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, HIGH);
delay(1000);
// สีน้ำเงิน
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, HIGH);
digitalWrite(bluePin, LOW);
delay(1000);
// สีขาว
digitalWrite(redPin, LOW);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, LOW);
delay(1000);
}
int vrPin = 34;
int buzzerPin = 25;
int vrValue = 0;
void setup() {
Serial.begin(115200);
pinMode(buzzerPin, OUTPUT);
}
void loop() {
vrValue = analogRead(vrPin);
Serial.print("VR Value = ");
Serial.println(vrValue);
if (vrValue > 2000) {
digitalWrite(buzzerPin, HIGH);
Serial.println("Buzzer ON");
}
else {
digitalWrite(buzzerPin, LOW);
Serial.println("Buzzer OFF");
}
Serial.println("------------------");
delay(500);
}
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
int vrPin = 34;
int buzzerPin = 25;
int vrValue = 0;
void setup() {
Serial.begin(115200);
pinMode(buzzerPin, OUTPUT);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println("OLED not found");
while(true);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
}
void loop() {
vrValue = analogRead(vrPin);
Serial.print("VR Value = ");
Serial.println(vrValue);
display.clearDisplay();
display.setCursor(0,0);
display.println("VR Sensor");
display.setTextSize(2);
display.setCursor(0,20);
display.println(vrValue);
if(vrValue > 2000){
digitalWrite(buzzerPin, HIGH);
display.setTextSize(1);
display.setCursor(0,50);
display.println("BUZZER ON");
} else {
digitalWrite(buzzerPin, LOW);
display.setTextSize(1);
display.setCursor(0,50);
display.println("BUZZER OFF");
}
display.display();
delay(300);
}
const int buttonPin = 4;
const int ledPin = 2;
bool ledState = false;
bool lastButtonState = HIGH;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
}
void loop() {
bool currentButtonState = digitalRead(buttonPin);
// ตรวจจับการกดปุ่ม
if (lastButtonState == HIGH && currentButtonState == LOW) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
Serial.println("Button Pressed");
delay(200); // debounce แบบง่าย
}
lastButtonState = currentButtonState;
}
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "COM325_2G";
const char* password = "COM325325";
IPAddress local_IP(172,16,15,100);
IPAddress gateway(172,16,15,1);
IPAddress subnet(255,255,255,0);
WebServer server(80);
const int buttonPin = 4;
const int ledPin = 2;
bool ledState = false;
bool lastButtonState = HIGH;
void handleRoot() {
String html = "<html><head><title>ESP32 LED</title></head><body>";
html += "<h1>ESP32 LED Control</h1>";
if(ledState)
html += "<p>LED Status : ON</p>";
else
html += "<p>LED Status : OFF</p>";
html += "<a href=\"/on\"><button style='font-size:30px'>ON</button></a>";
html += "<a href=\"/off\"><button style='font-size:30px'>OFF</button></a>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void ledOn() {
ledState = true;
digitalWrite(ledPin, HIGH);
handleRoot();
}
void ledOff() {
ledState = false;
digitalWrite(ledPin, LOW);
handleRoot();
}
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
// ตั้งค่า Fixed IP
if (!WiFi.config(local_IP, gateway, subnet)) {
Serial.println("STA Failed to configure");
}
WiFi.begin(ssid, password);
Serial.print("Connecting WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi Connected");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.on("/on", ledOn);
server.on("/off", ledOff);
server.begin();
}
void loop() {
server.handleClient();
bool currentButtonState = digitalRead(buttonPin);
if(lastButtonState == HIGH && currentButtonState == LOW){
ledState = !ledState;
digitalWrite(ledPin, ledState);
Serial.println("Button Pressed");
delay(200);
}
lastButtonState = currentButtonState;
}
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "COM325_2G";
const char* password = "COM325325";
IPAddress local_IP(172,16,15,100);
IPAddress gateway(172,16,15,1);
IPAddress subnet(255,255,255,0);
WebServer server(80);
const int buttonPin = 4;
const int ledPin = 2;
bool ledState = false;
bool lastButtonState = HIGH;
void handleRoot(){
String html = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{
font-family: Arial;
text-align:center;
background:linear-gradient(135deg,#1f4037,#99f2c8);
color:white;
margin-top:60px;
}
.card{
background:white;
color:black;
width:320px;
margin:auto;
padding:30px;
border-radius:20px;
box-shadow:0 10px 20px rgba(0,0,0,0.2);
}
h1{
margin-bottom:20px;
}
.status{
font-size:24px;
margin-bottom:20px;
}
button{
width:120px;
height:50px;
font-size:20px;
border:none;
border-radius:10px;
margin:10px;
cursor:pointer;
}
.on{
background:#2ecc71;
color:white;
}
.off{
background:#e74c3c;
color:white;
}
button:hover{
opacity:0.8;
}
</style>
</head>
<body>
<div class="card">
<h1>ESP32 LED Control</h1>
<div class="status">
LED STATUS : %STATE%
</div>
<a href="/on"><button class="on">ON</button></a>
<a href="/off"><button class="off">OFF</button></a>
</div>
</body>
</html>
)rawliteral";
if(ledState)
html.replace("%STATE%","ON");
else
html.replace("%STATE%","OFF");
server.send(200,"text/html",html);
}
void ledOn(){
ledState = true;
digitalWrite(ledPin,HIGH);
handleRoot();
}
void ledOff(){
ledState = false;
digitalWrite(ledPin,LOW);
handleRoot();
}
void setup(){
Serial.begin(115200);
pinMode(ledPin,OUTPUT);
pinMode(buttonPin,INPUT_PULLUP);
if(!WiFi.config(local_IP,gateway,subnet)){
Serial.println("WiFi Config Failed");
}
WiFi.begin(ssid,password);
Serial.print("Connecting WiFi");
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi Connected");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
server.on("/",handleRoot);
server.on("/on",ledOn);
server.on("/off",ledOff);
server.begin();
}
void loop(){
server.handleClient();
bool currentButtonState = digitalRead(buttonPin);
if(lastButtonState==HIGH && currentButtonState==LOW){
ledState=!ledState;
digitalWrite(ledPin,ledState);
Serial.println("Button Pressed");
delay(200);
}
lastButtonState=currentButtonState;
}
#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>
#define LED_PIN 2
#define DHTPIN 5
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
WebServer server(80);
const char* ssid = "COM325_2G";
const char* password = "COM325325";
IPAddress local_IP(172,16,15,100);
IPAddress subnet(255,255,255,0);
IPAddress gateway(172,16,15,1);
bool ledState = false;
String webpage = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ESP32 Sensor</title>
<style>
body{
font-family: Arial;
background:#0f172a;
color:white;
text-align:center;
}
.card{
background:#1e293b;
padding:20px;
margin:20px auto;
width:300px;
border-radius:15px;
box-shadow:0 0 10px rgba(0,0,0,0.4);
}
.value{
font-size:40px;
margin:10px;
}
button{
padding:12px 30px;
font-size:18px;
border:none;
border-radius:10px;
background:#38bdf8;
color:white;
cursor:pointer;
}
button:hover{
background:#0284c7;
}
.status{
font-size:20px;
margin-top:10px;
}
</style>
</head>
<body>
<h2>ESP32 Environment Monitor</h2>
<div class="card">
Temperature
<div class="value" id="temp">-- °C</div>
</div>
<div class="card">
Humidity
<div class="value" id="hum">-- %</div>
</div>
<div class="card">
LED Control
<br><br>
<button onclick="toggleLED()">Toggle LED</button>
<div class="status" id="led">Status : --</div>
</div>
<script>
function updateData(){
fetch("/data")
.then(res => res.json())
.then(data =>{
document.getElementById("temp").innerHTML = data.temp + " °C";
document.getElementById("hum").innerHTML = data.hum + " %";
document.getElementById("led").innerHTML = "Status : " + data.led;
})
}
function toggleLED(){
fetch("/led")
}
setInterval(updateData,2000)
</script>
</body>
</html>
)rawliteral";
void handleRoot(){
server.send(200,"text/html",webpage);
}
void handleLED(){
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
server.sendHeader("Access-Control-Allow-Origin","*");
server.send(200,"text/plain","OK");
}
void handleData(){
float h = dht.readHumidity();
float t = dht.readTemperature();
String ledStatus = ledState ? "ON" : "OFF";
String json = "{";
json += "\"temp\":"+String(t)+",";
json += "\"hum\":"+String(h)+",";
json += "\"led\":\""+ledStatus+"\"";
json += "}";
server.sendHeader("Access-Control-Allow-Origin","*");
server.send(200,"application/json",json);
}
void setup(){
Serial.begin(115200);
pinMode(LED_PIN,OUTPUT);
dht.begin();
WiFi.config(local_IP,gateway,subnet);
WiFi.begin(ssid,password);
Serial.print("Connecting");
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println(WiFi.localIP());
server.on("/",handleRoot);
server.on("/led",handleLED);
server.on("/data",handleData);
server.begin();
}
void loop(){
server.handleClient();
}
#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>
#define LED_PIN 2
#define DHTPIN 5
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
WebServer server(80);
const char* ssid = "COM325_2G";
const char* password = "COM325325";
IPAddress local_IP(172,16,15,100);
IPAddress subnet(255,255,255,0);
IPAddress gateway(172,16,15,1);
bool ledState = false;
float temperature = 0;
float humidity = 0;
unsigned long lastRead = 0;
String webpage = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ESP32 Sensor</title>
<style>
body{
font-family: Arial;
background:#0f172a;
color:white;
text-align:center;
}
.card{
background:#1e293b;
padding:20px;
margin:20px auto;
width:300px;
border-radius:15px;
box-shadow:0 0 10px rgba(0,0,0,0.4);
}
.value{
font-size:40px;
margin:10px;
}
button{
padding:12px 30px;
font-size:18px;
border:none;
border-radius:10px;
background:#38bdf8;
color:white;
cursor:pointer;
}
button:hover{
background:#0284c7;
}
.status{
font-size:20px;
margin-top:10px;
}
</style>
</head>
<body>
<h2>ESP32 Environment Monitor</h2>
<div class="card">
Temperature
<div class="value" id="temp">-- °C</div>
</div>
<div class="card">
Humidity
<div class="value" id="hum">-- %</div>
</div>
<div class="card">
LED Control
<br><br>
<button onclick="toggleLED()">Toggle LED</button>
<div class="status" id="led">Status : --</div>
</div>
<script>
function updateData(){
fetch("/data")
.then(res => res.json())
.then(data =>{
document.getElementById("temp").innerHTML = data.temp + " °C";
document.getElementById("hum").innerHTML = data.hum + " %";
document.getElementById("led").innerHTML = "Status : " + data.led;
})
}
function toggleLED(){
fetch("/led")
}
setInterval(updateData,2000)
</script>
</body>
</html>
)rawliteral";
void handleRoot(){
server.send(200,"text/html",webpage);
}
void handleLED(){
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
server.sendHeader("Access-Control-Allow-Origin","*");
server.send(200,"text/plain","OK");
}
void handleData(){
String ledStatus = ledState ? "ON" : "OFF";
String json = "{";
json += "\"temp\":"+String(temperature)+",";
json += "\"hum\":"+String(humidity)+",";
json += "\"led\":\""+ledStatus+"\"";
json += "}";
server.sendHeader("Access-Control-Allow-Origin","*");
server.send(200,"application/json",json);
}
void setup(){
Serial.begin(115200);
pinMode(LED_PIN,OUTPUT);
dht.begin();
WiFi.config(local_IP,gateway,subnet);
WiFi.begin(ssid,password);
Serial.print("Connecting");
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("IP Address : ");
Serial.println(WiFi.localIP());
server.on("/",handleRoot);
server.on("/led",handleLED);
server.on("/data",handleData);
server.begin();
}
void loop(){
server.handleClient();
/* อ่านค่า DHT ทุก 2 วินาที */
if(millis() - lastRead > 2000){
lastRead = millis();
float h = dht.readHumidity();
float t = dht.readTemperature();
if(!isnan(h) && !isnan(t)){
humidity = h;
temperature = t;
}
Serial.print("Temperature : ");
Serial.print(temperature);
Serial.print(" °C ");
Serial.print("Humidity : ");
Serial.print(humidity);
Serial.println(" %");
}
}
const int buzzerPin = 25;
void setup() {
Serial.begin(115200);
// รูปแบบใหม่ (ESP32 Core 3.x)
ledcAttach(buzzerPin, 1000, 8); // pin, frequency, resolution
}
void loop() {
// เปิดเสียง 1000Hz
ledcWrite(buzzerPin, 128); // 50% duty cycle
delay(1000);
// ปิดเสียง
ledcWrite(buzzerPin, 0);
delay(1000);
}
// Ultrasonic + Buzzer 3 Level Warning
const int trigPin = 5;
const int echoPin = 18;
const int buzzerPin = 25;
long duration;
float distance;
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
ledcAttach(buzzerPin, 1000, 8); // PWM แบบใหม่ ESP32
}
void loop() {
// ส่งคลื่น Ultrasonic
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// รับคลื่นสะท้อน
duration = pulseIn(echoPin, HIGH);
// คำนวณระยะ (cm)
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// ====== เงื่อนไข 3 ระดับ ======
if (distance > 50) {
ledcWrite(buzzerPin, 0); // ปิดเสียง
}
else if (distance > 20 && distance <= 50) {
ledcChangeFrequency(buzzerPin, 1000, 8);
ledcWrite(buzzerPin, 128);
delay(500);
ledcWrite(buzzerPin, 0);
delay(500);
}
else if (distance <= 20) {
ledcChangeFrequency(buzzerPin, 2000, 8);
ledcWrite(buzzerPin, 128);
delay(100);
ledcWrite(buzzerPin, 0);
delay(100);
}
delay(100);
}
// ===========================
// VR + Buzzer + Serial Monitor
// ===========================
const int vrPin = 34; // ขา Analog
const int buzzerPin = 25; // ขา Buzzer
int sensorValue = 0;
int percentage = 0;
void setup() {
Serial.begin(115200);
pinMode(buzzerPin, OUTPUT);
Serial.println("=== ระบบทดสอบ VR ควบคุม Buzzer ===");
Serial.println("เงื่อนไข: ถ้ามากกว่า 50% → มีเสียง");
Serial.println("------------------------------------");
}
void loop() {
// อ่านค่า Analog (0 - 4095)
sensorValue = analogRead(vrPin);
// แปลงเป็นเปอร์เซ็นต์
percentage = map(sensorValue, 0, 4095, 0, 100);
// แสดงผลใน Serial Monitor
Serial.print("ค่า Analog = ");
Serial.print(sensorValue);
Serial.print(" | เปอร์เซ็นต์ = ");
Serial.print(percentage);
Serial.print("%");
// เงื่อนไขควบคุมเสียง
if (percentage > 50) {
digitalWrite(buzzerPin, HIGH);
Serial.println(" → สถานะ: BUZZER ON 🔊");
} else {
digitalWrite(buzzerPin, LOW);
Serial.println(" → สถานะ: BUZZER OFF");
}
delay(500);
}
//โปรแกรม 02-Button-Web-LED
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "ESP32_99";
const char* password = "12345678"; // ต้องอย่างน้อย 8 ตัว
WebServer server(80);
const int ledPin = 2;
const int buttonPin = 4;
bool ledState = false;
bool lastButtonState = HIGH;
void handleRoot() {
String html = "<!DOCTYPE html><html>";
html += "<head>";
html += "<meta name='viewport' content='width=device-width, initial-scale=1'>";
html += "<meta http-equiv='refresh' content='2'>";
html += "<style>";
html += "body{font-family:sans-serif;text-align:center;}";
html += "button{width:120px;height:50px;font-size:18px;margin:10px;}";
html += "</style></head>";
html += "<body>";
html += "<h2>ESP32 Access Point</h2>";
html += "<h3>Status: ";
html += (ledState ? "ON" : "OFF");
html += "</h3>";
html += "<a href='/on'><button>ON</button></a>";
html += "<a href='/off'><button>OFF</button></a>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void handleOn() {
ledState = true;
digitalWrite(ledPin, HIGH);
server.sendHeader("Location", "/");
server.send(303);
}
void handleOff() {
ledState = false;
digitalWrite(ledPin, LOW);
server.sendHeader("Location", "/");
server.send(303);
}
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
// เปิดโหมด Access Point
WiFi.softAP(ssid, password);
Serial.println("Access Point Started");
Serial.print("IP Address: ");
Serial.println(WiFi.softAPIP());
server.on("/", handleRoot);
server.on("/on", handleOn);
server.on("/off", handleOff);
server.begin();
}
void loop() {
server.handleClient();
bool currentButtonState = digitalRead(buttonPin);
// ปุ่มจริง Toggle
if (lastButtonState == HIGH && currentButtonState == LOW) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
delay(200);
}
lastButtonState = currentButtonState;
}
// Install Library DHT sensor library by Adafruit befor
#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>
#define DHTPIN 5
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "ESP32_LED_Control";
const char* password = "12345678";
WebServer server(80);
const int ledPin = 2;
const int buttonPin = 4;
bool ledState = false;
bool lastButtonState = HIGH;
void handleRoot() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
String html = "<!DOCTYPE html><html>";
html += "<head>";
html += "<meta name='viewport' content='width=device-width, initial-scale=1'>";
html += "<meta http-equiv='refresh' content='5'>";
html += "<style>";
html += "body{margin:0;font-family:Arial;background:linear-gradient(135deg,#4e73df,#1cc88a);color:white;text-align:center;}";
html += ".container{padding:20px;}";
html += ".card{background:white;color:#333;border-radius:20px;padding:20px;margin:15px auto;max-width:300px;box-shadow:0 10px 20px rgba(0,0,0,0.2);}";
html += ".title{font-size:18px;margin-bottom:10px;color:#888;}";
html += ".value{font-size:36px;font-weight:bold;}";
html += ".led-on{color:#1cc88a;font-weight:bold;}";
html += ".led-off{color:#e74a3b;font-weight:bold;}";
html += "button{width:120px;height:45px;border:none;border-radius:25px;font-size:16px;margin:8px;color:white;cursor:pointer;}";
html += ".btn-on{background:#1cc88a;}";
html += ".btn-off{background:#e74a3b;}";
html += "</style></head>";
html += "<body>";
html += "<div class='container'>";
html += "<h2>ESP32 IoT Dashboard</h2>";
html += "<div class='card'>";
html += "<div class='title'>🌡 Temperature</div>";
html += "<div class='value'>" + String(temperature) + " °C</div>";
html += "</div>";
html += "<div class='card'>";
html += "<div class='title'>💧 Humidity</div>";
html += "<div class='value'>" + String(humidity) + " %</div>";
html += "</div>";
html += "<div class='card'>";
html += "<div class='title'>💡 LED Status</div>";
html += "<div class='value ";
html += (ledState ? "led-on'>" : "led-off'>");
html += (ledState ? "ON" : "OFF");
html += "</div>";
html += "<a href='/on'><button class='btn-on'>ON</button></a>";
html += "<a href='/off'><button class='btn-off'>OFF</button></a>";
html += "</div>";
html += "</div></body></html>";
server.send(200, "text/html", html);
}
void handleOn() {
ledState = true;
digitalWrite(ledPin, HIGH);
server.sendHeader("Location", "/");
server.send(303);
}
void handleOff() {
ledState = false;
digitalWrite(ledPin, LOW);
server.sendHeader("Location", "/");
server.send(303);
}
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
dht.begin();
WiFi.softAP(ssid, password);
Serial.println("Access Point Started");
Serial.print("IP Address: ");
Serial.println(WiFi.softAPIP());
server.on("/", handleRoot);
server.on("/on", handleOn);
server.on("/off", handleOff);
server.begin();
}
void loop() {
server.handleClient();
bool currentButtonState = digitalRead(buttonPin);
if (lastButtonState == HIGH && currentButtonState == LOW) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
delay(200);
}
lastButtonState = currentButtonState;
}
#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>
#define DHTPIN 5
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "SmartFarmPro";
const char* password = "12345678";
WebServer server(80);
const int ledPin = 2;
const int buttonPin = 4;
bool ledState = false;
bool lastButtonState = HIGH;
void handleData() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature)) temperature = 0;
if (isnan(humidity)) humidity = 0;
String json = "{";
json += "\"temp\":" + String(temperature) + ",";
json += "\"hum\":" + String(humidity) + ",";
json += "\"led\":" + String(ledState ? 1 : 0);
json += "}";
server.send(200, "application/json", json);
}
void handleOn() {
ledState = true;
digitalWrite(ledPin, HIGH);
server.send(200, "text/plain", "OK");
}
void handleOff() {
ledState = false;
digitalWrite(ledPin, LOW);
server.send(200, "text/plain", "OK");
}
void handleRoot() {
String html = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Smart Farm Pro</title>
<style>
body{
margin:0;
font-family:Arial;
background:linear-gradient(135deg,#0f2027,#203a43,#2c5364);
color:white;
text-align:center;
}
.container{padding:20px;}
.card{
background:white;
color:#333;
border-radius:20px;
padding:20px;
margin:15px auto;
max-width:340px;
box-shadow:0 8px 20px rgba(0,0,0,0.3);
}
/* ===== Gauge ครึ่งวงกลม ===== */
.gauge-wrap{
width:220px;
margin:20px auto;
}
.gauge{
width:100%;
height:110px;
background:#ddd;
border-top-left-radius:110px;
border-top-right-radius:110px;
position:relative;
overflow:hidden;
}
.gauge-fill{
position:absolute;
width:100%;
height:100%;
background:#00ff88;
transform-origin:center bottom;
transform:rotate(0deg);
transition:0.5s;
}
.gauge-cover{
width:160px;
height:80px;
background:white;
border-top-left-radius:80px;
border-top-right-radius:80px;
position:absolute;
bottom:0;
left:50%;
transform:translateX(-50%);
display:flex;
align-items:center;
justify-content:center;
font-size:26px;
font-weight:bold;
color:#333;
}
/* ===== Humidity Bar ===== */
.bar{
height:20px;
background:#ddd;
border-radius:10px;
overflow:hidden;
}
.bar-fill{
height:100%;
width:0%;
background:#3498db;
transition:0.5s;
}
button{
padding:10px 20px;
border:none;
border-radius:25px;
font-size:16px;
margin:5px;
color:white;
cursor:pointer;
}
.on{background:#27ae60;}
.off{background:#e74c3c;}
</style>
</head>
<body>
<div class="container">
<h2>Smart Home / บ้านของฉัน</h2>
<div class="card">
<h3>Temperature</h3>
<div class="gauge-wrap">
<div class="gauge">
<div class="gauge-fill" id="tempFill"></div>
<div class="gauge-cover" id="tempValue">0°C</div>
</div>
</div>
</div>
<div class="card">
<h3>Humidity</h3>
<div class="bar">
<div class="bar-fill" id="humBar"></div>
</div>
<p id="humValue">0%</p>
</div>
<div class="card">
<h3>LED Control</h3>
<p id="ledStatus">OFF</p>
<button class="on" onclick="ledOn()">ON</button>
<button class="off" onclick="ledOff()">OFF</button>
</div>
</div>
<script>
function updateData(){
fetch("/data")
.then(res => res.json())
.then(data => {
let temp = data.temp;
let hum = data.hum;
document.getElementById("tempValue").innerHTML = temp + "°C";
document.getElementById("humValue").innerHTML = hum + "%";
// ===== Semi Gauge Calculation =====
let degree = (temp * 180) / 50;
let color = "#00ff88";
if(temp > 30) color = "#e74c3c";
else if(temp > 25) color = "#f39c12";
document.getElementById("tempFill").style.transform =
"rotate(" + degree + "deg)";
document.getElementById("tempFill").style.background = color;
document.getElementById("humBar").style.width = hum + "%";
document.getElementById("ledStatus").innerHTML =
data.led ? "ON" : "OFF";
});
}
function ledOn(){ fetch("/on"); }
function ledOff(){ fetch("/off"); }
setInterval(updateData, 2000);
updateData();
</script>
</body>
</html>
)rawliteral";
server.send(200, "text/html", html);
}
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
dht.begin();
WiFi.softAP(ssid, password);
server.on("/", handleRoot);
server.on("/data", handleData);
server.on("/on", handleOn);
server.on("/off", handleOff);
server.begin();
}
void loop() {
server.handleClient();
bool currentButtonState = digitalRead(buttonPin);
if (lastButtonState == HIGH && currentButtonState == LOW) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
delay(200);
}
lastButtonState = currentButtonState;
}
// =============================
// ESP32 + L298N Motor Control
// =============================
const int ena = 25; // PWM
const int in1 = 26;
const int in2 = 27;
void setup() {
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
// PWM แบบใหม่ ESP32
ledcAttach(ena, 1000, 8); // pin, freq, resolution
Serial.begin(115200);
}
void loop() {
// หมุนไปข้างหน้า
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
// ค่อย ๆ เพิ่มความเร็ว
for (int speed = 0; speed <= 255; speed += 20) {
ledcWrite(ena, speed);
Serial.println(speed);
delay(500);
}
delay(2000);
// หยุด
ledcWrite(ena, 0);
delay(2000);
// หมุนกลับทาง
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
ledcWrite(ena, 150);
delay(3000);
ledcWrite(ena, 0);
delay(3000);
}
#include <WiFi.h>
#include <WebServer.h>
#include <ArduinoJson.h>
const char* ssid = "ESP99";
const char* password = "12345678";
WebServer server(80);
// Motor pins
const int ena = 25;
const int in1 = 26;
const int in2 = 27;
void handleRoot() {
server.send(200, "text/html", htmlPage);
}
void handleControl() {
if (server.method() == HTTP_POST) {
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, server.arg("plain"));
if (!error) {
String direction = doc["direction"];
int speed = doc["speed"];
// ควบคุมทิศทาง
if (direction == "forward") {
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
}
else if (direction == "backward") {
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
}
else {
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
speed = 0;
}
ledcWrite(ena, speed);
}
}
server.send(200, "application/json", "{\"status\":\"ok\"}");
}
String htmlPage = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32 JSON Motor</title>
<style>
body { text-align:center; font-family:Arial; background:#121212; color:white; }
button { padding:15px; margin:10px; font-size:18px; }
input { width:80%; }
</style>
</head>
<body>
<h2>🚗 Smart Motor JSON</h2>
<input type="range" min="0" max="255" value="0" id="speedSlider">
<p>Speed: <span id="speedValue">0</span></p>
<button onclick="sendData('forward')">Forward</button>
<button onclick="sendData('backward')">Backward</button>
<button onclick="sendData('stop')">Stop</button>
<script>
function sendData(direction){
let speed = document.getElementById("speedSlider").value;
document.getElementById("speedValue").innerHTML = speed;
fetch("/control", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
direction: direction,
speed: parseInt(speed)
})
});
}
</script>
</body>
</html>
)rawliteral";
void setup() {
Serial.begin(115200);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
ledcAttach(ena, 1000, 8);
WiFi.softAP(ssid, password);
server.on("/", handleRoot);
server.on("/control", HTTP_POST, handleControl);
server.begin();
Serial.println("AP Started");
Serial.println(WiFi.softAPIP());
}
void loop() {
server.handleClient();
}
#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>
// ================= WiFi =================
const char* ssid = "T322"; // ชื่อ wifi เฉพาะย่าน 2.4G เท่านั้น
const char* password = "1111100000"; // รหัสผ่าน wifi
// Static IP
IPAddress local_IP(192,168,1,101);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
// ================= Hardware =================
#define DHTPIN 4
#define DHTTYPE DHT11
#define LEDPIN 2
DHT dht(DHTPIN, DHTTYPE);
// ================= Server =================
WebServer server(80);
// ================= Variables =================
float temperature;
float humidity;
bool ledState = false;
// ================= HTML =================
void handleRoot() {
String page = R"====(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ESP32 Smart Node</title>
<style>
body{
font-family:Arial;
background:#0f2027;
background:linear-gradient(120deg,#2c5364,#203a43,#0f2027);
color:white;
text-align:center;
margin:0;
}
.container{
max-width:400px;
margin:auto;
padding:20px;
}
.card{
background:white;
color:#333;
padding:20px;
margin:15px;
border-radius:15px;
box-shadow:0 4px 10px rgba(0,0,0,0.3);
}
.value{
font-size:40px;
font-weight:bold;
}
button{
width:150px;
height:50px;
font-size:18px;
border:none;
border-radius:10px;
background:#2196F3;
color:white;
cursor:pointer;
}
button:hover{
background:#1976D2;
}
</style>
<script>
function updateData(){
fetch("/data")
.then(response=>response.json())
.then(data=>{
document.getElementById("temp").innerHTML = data.temp + " °C";
document.getElementById("hum").innerHTML = data.hum + " %";
document.getElementById("led").innerHTML = data.led;
});
}
setInterval(updateData,2000);
function ledOn(){
fetch("/on");
}
function ledOff(){
fetch("/off");
}
</script>
</head>
<body onload="updateData()">
<div class="container">
<h2>ESP32 IoT Dashboard</h2>
<div class="card">
<h3>Temperature</h3>
<div class="value" id="temp">--</div>
</div>
<div class="card">
<h3>Humidity</h3>
<div class="value" id="hum">--</div>
</div>
<div class="card">
<h3>LED Status</h3>
<div class="value" id="led">--</div>
<br>
<button onclick="ledOn()">LED ON</button>
<button onclick="ledOff()">LED OFF</button>
</div>
</div>
</body>
</html>
)====";
server.send(200,"text/html",page);
}
// ================= JSON DATA =================
void handleData(){
temperature = dht.readTemperature();
humidity = dht.readHumidity();
String ledText = ledState ? "ON" : "OFF";
String json = "{";
json += "\"temp\":" + String(temperature) + ",";
json += "\"hum\":" + String(humidity) + ",";
json += "\"led\":\"" + ledText + "\"";
json += "}";
server.send(200,"application/json",json);
}
// ================= LED =================
void ledOn(){
ledState = true;
digitalWrite(LEDPIN,HIGH);
server.send(200,"text/plain","ON");
}
void ledOff(){
ledState = false;
digitalWrite(LEDPIN,LOW);
server.send(200,"text/plain","OFF");
}
// ================= Setup =================
void setup(){
Serial.begin(115200);
pinMode(LEDPIN,OUTPUT);
dht.begin();
WiFi.config(local_IP,gateway,subnet);
WiFi.begin(ssid,password);
Serial.print("Connecting");
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi Connected");
Serial.print("IP Address : ");
Serial.println(WiFi.localIP());
server.on("/",handleRoot);
server.on("/data",handleData);
server.on("/on",ledOn);
server.on("/off",ledOff);
server.begin();
}
// ================= Loop =================
void loop(){
server.handleClient();
}
#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>
#define LED_PIN 2
#define DHTPIN 4
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
WebServer server(80);
const char* ssid = "T322";
const char* password = "1111100000";
IPAddress local_IP(192,168,1,101);
IPAddress gateway(192,168,1,111);
IPAddress subnet(255,255,255,0);
bool ledState = false;
String webpage = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ESP32 Sensor</title>
<style>
body{
font-family: Arial;
background:#0f172a;
color:white;
text-align:center;
}
.card{
background:#1e293b;
padding:20px;
margin:20px auto;
width:300px;
border-radius:15px;
box-shadow:0 0 10px rgba(0,0,0,0.4);
}
.value{
font-size:40px;
margin:10px;
}
button{
padding:12px 30px;
font-size:18px;
border:none;
border-radius:10px;
background:#38bdf8;
color:white;
cursor:pointer;
}
button:hover{
background:#0284c7;
}
.status{
font-size:20px;
margin-top:10px;
}
</style>
</head>
<body>
<h2>ESP32 Environment Monitor</h2>
<div class="card">
Temperature
<div class="value" id="temp">-- °C</div>
</div>
<div class="card">
Humidity
<div class="value" id="hum">-- %</div>
</div>
<div class="card">
LED Control
<br><br>
<button onclick="toggleLED()">Toggle LED</button>
<div class="status" id="led">Status : --</div>
</div>
<script>
function updateData(){
fetch("/data")
.then(res => res.json())
.then(data =>{
document.getElementById("temp").innerHTML = data.temp + " °C";
document.getElementById("hum").innerHTML = data.hum + " %";
document.getElementById("led").innerHTML = "Status : " + data.led;
})
}
function toggleLED(){
fetch("/led")
}
setInterval(updateData,2000)
</script>
</body>
</html>
)rawliteral";
void handleRoot(){
server.send(200,"text/html",webpage);
}
void handleLED(){
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
server.sendHeader("Access-Control-Allow-Origin","*");
server.send(200,"text/plain","OK");
}
void handleData(){
float h = dht.readHumidity();
float t = dht.readTemperature();
String ledStatus = ledState ? "ON" : "OFF";
String json = "{";
json += "\"temp\":"+String(t)+",";
json += "\"hum\":"+String(h)+",";
json += "\"led\":\""+ledStatus+"\"";
json += "}";
server.sendHeader("Access-Control-Allow-Origin","*");
server.send(200,"application/json",json);
}
void setup(){
Serial.begin(115200);
pinMode(LED_PIN,OUTPUT);
dht.begin();
WiFi.config(local_IP,gateway,subnet);
WiFi.begin(ssid,password);
Serial.print("Connecting");
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println(WiFi.localIP());
server.on("/",handleRoot);
server.on("/led",handleLED);
server.on("/data",handleData);
server.begin();
}
void loop(){
server.handleClient();
}
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8">
<title>IoT Classroom Dashboard</title>
<style>
body{
font-family:Arial;
background:#0f172a;
color:white;
margin:0;
padding:20px;
}
h1{
text-align:center;
margin-bottom:30px;
}
.grid{
display:grid;
grid-template-columns:repeat(auto-fit,minmax(250px,1fr));
gap:20px;
}
.card{
background:#1e293b;
padding:20px;
border-radius:15px;
box-shadow:0 0 10px rgba(0,0,0,0.4);
text-align:center;
}
.value{
font-size:35px;
margin:10px;
}
.temp{ color:#f87171; }
.hum{ color:#38bdf8; }
.status{
font-size:18px;
margin-top:10px;
}
button{
padding:10px 25px;
border:none;
border-radius:8px;
background:#22c55e;
color:white;
font-size:16px;
cursor:pointer;
}
button:hover{
background:#16a34a;
}
.offline{
color:#f87171;
}
</style>
</head>
<body>
<h1>📊 IoT Classroom Dashboard</h1>
<div class="grid" id="dashboard"></div>
<script>
const groups = [
{ id:1 , ip:"192.168.1.101"},
{ id:2 , ip:"192.168.1.102"},
{ id:3 , ip:"192.168.1.103"},
{ id:4 , ip:"192.168.1.104"},
{ id:5 , ip:"192.168.1.105"},
{ id:6 , ip:"192.168.1.106"},
{ id:7 , ip:"192.168.1.107"},
{ id:8 , ip:"192.168.1.108"},
{ id:9 , ip:"192.168.1.109"},
{ id:10 , ip:"192.168.1.110"}
]
const dashboard = document.getElementById("dashboard")
groups.forEach(g=>{
dashboard.innerHTML += `
<div class="card">
<h2>กลุ่ม ${g.id}</h2>
<div>🌡️ Temperature</div>
<div class="value temp" id="temp${g.id}">--</div>
<div>💧 Humidity</div>
<div class="value hum" id="hum${g.id}">--</div>
<div class="status" id="led${g.id}">LED : --</div>
<br>
<button onclick="toggleLED('${g.ip}')">Toggle LED</button>
</div>
`
})
function loadData(){
groups.forEach(g=>{
fetch(`http://${g.ip}/data`)
.then(res=>res.json())
.then(data=>{
document.getElementById(`temp${g.id}`).innerHTML = data.temp + " °C"
document.getElementById(`hum${g.id}`).innerHTML = data.hum + " %"
document.getElementById(`led${g.id}`).innerHTML = "LED : " + data.led
})
.catch(()=>{
document.getElementById(`temp${g.id}`).innerHTML = "Offline"
document.getElementById(`hum${g.id}`).innerHTML = "Offline"
document.getElementById(`led${g.id}`).innerHTML = "Offline"
})
})
}
function toggleLED(ip){
fetch(`http://${ip}/led`)
}
setInterval(loadData,3000)
loadData()
</script>
</body>
</html>