// robotics blocks - Trafic light - Kids road  Gase
 
#include <ESP32Servo.h>
 
const int servoPin = 18;
int buttonOpenState;
int buttonCloseState;
 
#define ledRed 4
#define ledGreen 2
#define buttonOpen 12
#define buttonClose 14
int pos = 90;
Servo servo;
char gateState=0; // 0= close , 1 = open
 
 
 
 
void setup() {
    // initialize serial for debugging
  Serial.begin(115200);
  Serial.println("start....system");
 
  pinMode(buttonOpen, INPUT_PULLUP);
  pinMode(buttonClose, INPUT_PULLUP);
  pinMode(ledRed,OUTPUT);
  pinMode(ledGreen,OUTPUT);
  servo.attach(servoPin, 500, 2400);
  servo.write(90);
    digitalWrite(ledGreen,HIGH); 
     Serial.println("Road Open- kids can not  walk");
}
 
 
 
void loop() {
 
 
buttonOpenState = digitalRead(buttonOpen);
buttonCloseState = digitalRead(buttonClose) ;
          if ( (buttonOpenState==0) && (gateState==0))
              { // open gate
            digitalWrite(ledGreen, LOW); 
            digitalWrite(ledRed, HIGH);
            for (pos =90; pos <= 180; pos = pos + 1) {
             servo.write(pos);
           //  Serial.println(pos);
              digitalWrite(ledRed, HIGH);
             delay(15);
           
              }
                gateState=1;
              Serial.println("Road close- kids can walk");

          }
        
 
 
        if( (buttonCloseState==0) &&  (gateState==1) )
         { // close gate
               if(pos>=180) // check if gate is already opemed
              {
             for (pos =180; pos >= 90; pos =pos- 1) {
             servo.write(pos);
            // Serial.println(pos);
             delay(15);
            
              }
               gateState=0;
          digitalWrite(ledRed , LOW);
           digitalWrite(ledGreen,HIGH); 
             Serial.println("Road Open- kids can not  walk ");
         }
        }
          
 
 
}