#include <LiquidCrystal_I2C.h>
#include <Servo.h>
Servo myservo; //สร้าง obj โดยไม่กำหนดคอนสตั๊ก
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
#define ECHO_PIN 2
#define TRIG_PIN 3
bool f1 = true;
const float BETA = 3950; // should match the Beta Coefficient of the thermistor
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
unsigned int sum1;
unsigned int sum2;
void setup() {
Serial.begin(9600);
lcd.init();
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("test");
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(A0,INPUT);
myservo.attach(9);
lcd.clear();
}
void loop() {
lcd.setCursor(0,0);
lcd.print("pass : ");
lcd.setCursor(0,1);
lcd.print("Not pass : ");
myservo.write(0);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// การอ่านค่าแบบนี้ใช้ได้เฉพาะในเว็บไซต์เท่านั้นไม่สามารถใช้งานของจริงได้
int duration = pulseIn(ECHO_PIN, HIGH);
int a1 = duration/58;
Serial.print("Distance in CM: ");
Serial.println(a1);
// lcd.setCursor(0,0);
// lcd.print("distan : ");
// lcd.print(a1);
//อ่านค่าอุณหภูมิจาก NTC thermistor ของจริงไม่ได้ใช้งานตัวนี้
int analogValue = analogRead(A0);
float celsius = 1 / (log(1 / (1023. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
Serial.print("Temperature: ");
Serial.print(celsius);
Serial.println(" ℃");
// lcd.setCursor(0,1);
// lcd.print("temp : ");
// lcd.print(int(celsius));
delay(200);
// การใช้งาน servo ต้องจ่ายการทำงานด้วย pwm เท่านั้น
// ทดสอบหมุนของ servo
if(a1>20 && a1<40 && f1 ){
// กรณีผ่าน
if(int(celsius)<40 && int(celsius)>=35){
sum1++;
myservo.write(90);
delay(3000);
f1 = false;
lcd.setCursor(8,0);
lcd.print(sum1);
}
//กรณีไม่ผ่าน
else{
sum2++;
lcd.setCursor(12,1);
lcd.print(sum2);
delay(1000);
}
}
if(a1>40)f1 = true; // รีเซ็น bool เพื่อให้ระยะห่างออกจากเซ็นเซอร์ก่อน
}
// โครงงาน ระบบวัดอุณหภูมิแบบไร้สัมผัสเพื่อเปิดประตูพร้อมนับจำนวนแสดงผลผ่านจอ lcd
//https://blog.wokwi.com/learn-servo-motor-using-wokwi-logic-analyzer/
// ตัวอย่างการใช้งาน เซอโว