// Mover servo de derecha a izquierda al oprimir el pulsador de cada lado 
// el servo regresa automaticamente al centro (Direccion de Carro)

#include <Servo.h>       // Incluye la libreria Servo
 
Servo MServo1;           // Crea el objeto MServo1 con las caracteristicas de Servo
        
int tiempo=35; // velocidad de motor

float MinimaTension=4.51;
int Ubicacion=0;

void setup() 
{ 
  Serial.begin(115200);
  MServo1.attach(5,544,2400);    // Asocia el Mservo1 al pin 5, define el min y max del ancho del pulso  
                                // eso depende del fabricante del servo
  pinMode(A0, INPUT);
      
}

void loop() 
{
  if (Ubicacion == 0)
  {
    scaneo();
    Serial.println(MinimaTension);
    Serial.println(Ubicacion);
  }
/*
  do{
        if (MinimaTension < analogRead(A0))
           {
            Ubicacion++;   
                  if   (Ubicacion < 180)
                  {     
                    MServo1.write(Ubicacion);                 
                    delay(tiempo); 
                    }   
                    else
                    {
                    if (MinimaTension > analogRead(A0))     
                      {   
                                 scaneo();
                      }   
                    }        
            }     
          }  while (MinimaTension != 4.51);   
             scaneo();   */
}

void  scaneo()
{
  int i=0;
  float TesionLdr=0;
  MServo1.write(i);
  delay(tiempo);

 for ( i=0; i < 179; i++)
  {
      MServo1.write(i);
      delay(tiempo);
      TesionLdr=analogRead(A0);
      TesionLdr =(TesionLdr * 4.51)/1024; //por la tension de ref en 10bits
        if (TesionLdr < MinimaTension)
          {
            MinimaTension=TesionLdr;
            Ubicacion=i;
          }
 } 
  MServo1.write(Ubicacion); 
}