Arduino Assignment 2
Arduino Assignment 2
Circuit diagram
Outputs
OBJECT
DISTANCE
LED
when distance is greater than 60 (100 in this case), the led
shows green colour
• Vcc: +5vdc
• Trig: trigger (input)
• Echo: echo (output)
• Gnd: gnd
After the connections of sensor were made with Arduino, I took a RGB led bulb and connect its pins to
Arduino (cathode to gnd and colour pins to I/O pins of Arduino). Then I assigned pins number
according to the connections made. That’s pretty much my construction, let’s move on to working.
Working
Initially all the LED are set at low output. A pulse of 10 microseconds is generated for the Trigger pin of
sensor by changing its value from low to high and back to low with 5 microsecond delay. Then input is
recorded from echo pin inside an integer “time” by using “pulseIn” command. A pulseIn reads a pulse
(either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH,
starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in
microseconds or 0 if no complete pulse was received within the timeout. Once the time is recorded, it
is converted to distance by using simple formula “ Distance = Speed x Time ”. we recorded the time
and multiply it with speed of sound (0.0343). this time is basically the total time ultrasonic signal takes
to hit the object and return to sensor so, we divide it with 2. The we simply use “if” command and set
the outputs of LED color according to the distance of the object from sensor. such as:
However, there is a limitation in current sensor I used, it works at minimum distance of 2.5 cm. any
object smaller then 2 cm and within 2.5 cm range of sensor will not activate it. And circuit will gives
green color.
int echoPin = 6;
int redPin = 3;
int bluePin = 2;
int greenPin = 1;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
if (distance > 60){ // If the distance is larger than 60cm Turn On Green Leds
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
digitalWrite(bluePin, LOW);
if (distance > 40 && distance < 60) { // If the distance is larger than 40cm and under 60 Turn On blue
Leds
digitalWrite(redPin, LOW);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, HIGH);
if (distance < 40){ // If the distance is less than 40cm Turn On red Led
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
digitalWrite(bluePin, LOW);
delay(250);