The main objectiv of that project is to know how it works and ultrasound and the microcontroller arduino, in order to create a sensor of distance that calculates how long is the objecte from the ultrasound. We also added a Led to see how it works defining the pins and outputs and how works the boolean variable.
#define ULTRASOUND_PIN 2 //We define the number of the pin of the outputs used
#define LED_PIN 3
void setup() { //We define the pins of the outputs and inputs that we use
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(ULTRASOUND_PIN, OUTPUT);
pinMode(LED_PIN, INPUT);
}
float readDistanceCM() { // We define a variable that is a float number called readDistanceCM
digitalWrite(LED_PIN, LOW); // We put a delay to configure the time that the led will be opened or closed.
delayMicroseconds(2);
digitalWrite(LED_PIN, HIGH); //We do the same with the ultrasonds
delayMicroseconds(10);
digitalWrite(LED_PIN, LOW);
int duration = pulseIn(ULTRASOUND_PIN, HIGH);
return duration * 0.034 / 2;
}
void loop() {
float distance = readDistanceCM(); // We establize a relation of the tow variables that we create previosuly
bool isNearby = distance < 3; // We create a boolean variable that it only works with a 0 or 1. When it's 1 the led will be opened and vicevers.
digitalWrite(LED_BUILTIN, isNearby); // the computer will put neary or ot nearly if the led will open or not
Serial.print("Measured distance: "); // We print a text that tell you at what distance is the object over the sensor
Serial.println(readDistanceCM());
delay(100);
}