#include <Servo.h>
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
unsigned int count1;
#define ECHO_PIN 2
#define TRIG_PIN 3
float readDistanceCM(void);
void opend(void);
void setup() {
Serial.begin(9600);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
myservo.write(0);
lcd.init();
lcd.backlight();
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Print something
lcd.setCursor(0, 0);
lcd.print("count : ");
}
void loop() {
// for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// // in steps of 1 degree
// myservo.write(pos); // tell servo to go to position in variable 'pos'
// delay(15); // waits 15ms for the servo to reach the position
// }
// for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
// myservo.write(pos); // tell servo to go to position in variable 'pos'
// delay(15); // waits 15ms for the servo to reach the position
// }
lcd.setCursor(8,0);
lcd.print(count1);
int a1 = readDistanceCM();
Serial.print("distance : ");
Serial.println(a1);
if(a1 >120){
opend();
count1++;
Serial.println("opendoor << ");
}
}
// delay(15) เพื่อ : รอ 15 ms สำหรับ servo ไปยังตำแหน่งเป้าหมาย
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void opend(void){
myservo.write(0);
delay(2000);
myservo.write(180);
delay(2000);
myservo.write(0);
//delay(2000);
}