#define THINGER_SERIAL_DEBUG


// #include <cstdint>
// #include <WiFi.h>
// #include <ThingerESP32.h>
// #include <Servo.h>

// #include <ESP32Servo.h>
//  include <WiFiClientSecure.h>
// #include <WiFiNINA.h>


#define ECHO_PIN 3
#define TRIG_PIN 2
#define pinBuzzer 5

// #define USERNAME "ifdhal"
// #define DEVICE_ID "MotoServo"
// #define DEVICE_CREDENTIAL "TOLfu@-jax_dbdoi"

// #define SSID "Wokwi-GUEST"
// #define SSID_PASSWORD ""

//  ThingerESP32 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);
// Servo thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);


int rotasi = 90;
int interval = 0;
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 soundBuzzer(){
if(interval < 500){
tone(pinBuzzer, 250);
}else
if(interval > 500){
tone(pinBuzzer, 100,800);
};
}
void setup() {
// put your setup code here, to run once:
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.begin(115200);
pinMode(pinBuzzer, OUTPUT);
thing.attach(9);
thing.write(90);

thing.add_wifi(SSID, SSID_PASSWORD);

  thing["MotoServo"] << digitalPin(9);
  

   thing["millis"] >> outputValue(millis());
}
void loop() {
// put your main code here, to run repeatedly:
tutupPalang();
interval +=100;

thing.handle();

if(interval>1000) interval = 0;
}
void tutupPalang(){
float jarak = readDistanceCM();
if(jarak > 0 && jarak < 100 ){
soundBuzzer();
tutup();
}else{
buka();
noTone(pinBuzzer);
}
}
void tutup(){
if(rotasi <= 90){
thing.write(rotasi);
delay(100);
rotasi--;
}
if(rotasi <= 0 ) rotasi = 0;
}
void buka(){
if(rotasi <= 90){
thing.write(rotasi);
delay(100);
rotasi+=4;
}
if(rotasi >= 90 ) rotasi = 90;
}