// definimos pines de direcion y step para el motor
const int stepPin = 4;
const int dirPin = 5;
int cm, retraso; // Defines variables a utilizar
long tiempo(int triggerPin, int echoPin) //funcion para retonar el tiempo del HC-SR04
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns
// the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
float speedUp() { //funcion para calcular a que velocidad gira el motor
cm = 0.0344/2 * tiempo(3, 2);// convertimos el tiempo obtenido a cm
int vel = map(cm, 0, 400, 4000, 300); //mapeo de distancia a retraso del motor
return vel;
}
void setup() {
// Sets the two pins as Outputs
Serial.begin(9600);
pinMode(stepPin,OUTPUT);
pinMode(dirPin,OUTPUT);
digitalWrite(dirPin,HIGH); //Enables the motor to move in a particular direction
}
void loop() {
retraso = speedUp(); // Gets custom delay values from the custom speedUp function
// Makes pules with custom delay, depending on the Potentiometer, from which the speed of the motor depends
Serial.println(retraso);
digitalWrite(stepPin, HIGH);
delayMicroseconds(retraso);
digitalWrite(stepPin, LOW);
delayMicroseconds(retraso);
}