// Name: Infrared and Ultrasound
// Purpose: This lab will explore both infra-red and ultrasonic sensors, by detecting the object with the given distances with an LED indicator.
// Comment: Part 3 of Lab_7
// Author: Karl Edward Sarmiento
// IP/Domain: MIT
// infrareds
int inf_pin = A1; // infrared analog pin
int inf_val = 0; // infrared value
// ultrasounds
int pin_trig = 8; // ultrasound trigger pin
int pin_echo = 7; // ultrasound echo pin
float us_val = 0; // ultrasound value
// LED
int LED_in = 33;
int LED_out = 32;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(pin_echo, INPUT); // echo pin is set to input
pinMode(pin_trig, OUTPUT); // trigger pin is set to output
// LED
pinMode(LED_in, INPUT); // RED LED light
pinMode(LED_out, OUTPUT); // Ground LED
}
void loop() {
// put your main code here, to run repeatedly:
long dt; // the duration of the pulse
us_val = digitalRead(pin_echo);
digitalWrite(pin_trig, LOW);
delayMicroseconds(2);
digitalWrite(pin_trig, HIGH);
delayMicroseconds(10); // the trigger pulse duration
digitalWrite(pin_trig, LOW);
dt = pulseIn(pin_echo, HIGH);
us_val = float (dt) * 0.034/2.0; // calculation to get distance in cm
Serial.print("Distance measured: ");
Serial.println(us_val); // prints the "Distance measured: "
inf_val = analogRead(inf_pin);
Serial.print("Analog value: ");
Serial.println(inf_val); // prints the analog value
if (inf_val >= 9, us_val < 10.0){
digitalWrite(LED_in, HIGH);
delay(1000);
}
else if (us_val > 99.0){ // greater than 1m
digitalWrite(LED_in, HIGH);
}
else{ // turn off when it is less than 1m or less than 8
digitalWrite(LED_in, LOW);
delay(1000);
}
}