UltraSonic

Learning Intention

Understand how ultrasonic can detect distance

Understand how a branching statement (if statement) works

Success Criteria

Read the distance value from an ultrasonic sensor

Complete the if/else statement to make a LED turn off  and on

Create a function to make a LED blink when ultrasonic detects a close object

Warm Up

How does an branching statement work?
What should the robot do when an object is close?

Engage

Online Simulation: https://www.tinkercad.com/things/c5bjtk3zjda

    1. Follow wiring diagram and wire ultrasonic sensor
    2. Code Copy and Paste into Arduino.
    3. Check if it is working
    4. Make the light turn off when no object is near
    5. Create a function that will blink when object is near
    6. Check if that is working
    7. Save to network drive
    8. Up to Office 365 programming assignment
//variable for LED
int LED = 13;

//Setup the Ultrasonic Sensor 
int trigPin = 11; 
int echoPin = 3;  
long duration; 
int distance;
int obDistance;


void setup()
{
  pinMode(LED, OUTPUT);
  
   pinMode(trigPin, OUTPUT); // trigPin as output 
  pinMode(echoPin, INPUT); // echoPin as input 
  
  Serial.begin(9600); // Starts the serial communication
  Serial.println("Welcome");  
}

void loop()
{   
 obDistance = checkDistance();
	   	// Print out distance 
    Serial.println(obDistance);



  
  if(obDistance <=10) {   
    //Turn light on
    digitalWrite(LED, HIGH); // delete this and then
    // create and call a function to blink LED
  }
  else {
      //Turn light off what should happen here. 
  }
}



int checkDistance(){ //need to use int as we are returning a variable

	//  CODE FOR ULTRA SONIC SENSOR WORKS OUT DISTANCE
  	// Clears the trigPin
	digitalWrite(trigPin, LOW);
	delayMicroseconds(2);
 
	// Sets the trigPin on HIGH state for 10 micro seconds
	digitalWrite(trigPin, HIGH);
	delayMicroseconds(10);
	digitalWrite(trigPin, LOW);
 
	// Reads the echoPin, returns the sound wave travel time in microseconds
	duration = pulseIn(echoPin, HIGH);
 
	// Calculating the distance
	distance = duration*0.034/2;
  return distance;
}
Print Friendly, PDF & Email