Ultrasonic Sensor Controlled Servo in NodeMCU

by callmeappytechie in Living > Education

8552 Views, 11 Favorites, 0 Comments

Ultrasonic Sensor Controlled Servo in NodeMCU

1.png

Hi, I'm Sridhar Janardhan today I am teaching about how to interface ultrasonic sensor and control the servo motor based on the values thrown by the ultrasonic sensor.This ibles are for the node MCU beginners and I expect the peeps to stay patient to see the intermediate stage later weeks as soon I as finish the basic ibles of node MCU Arduino and photon.

4.png
5.png
6.png
3..png

Components required to do this projects are:

  • NodeMCU
  • Breadboard
  • Jumper wire
  • Ultrasonic sensor
  • Servo motor

Let's now start with the connection

Ultrasonic Sensor Connection

IMG_20170823_234116.jpg
IMG_20170823_234103.jpg
IMG_20170823_234004.jpg
IMG_20170823_234131.jpg
IMG_20170823_234019.jpg
IMG_20170823_234256.jpg
IMG_20170823_234200.jpg

Ultrasonic sensor are connected by the following instruction

  • Trig pin: This is connected to the digital pin 13
  • ECHO pin: This is connected to the digital pin 12
  • VCC pin: this is connected to the Positive railing of the breadboard
  • GND pin: this is connected to the negative railing of the breadboard

Servo Connection

IMG_20170823_234451.jpg
IMG_20170823_234353.jpg
IMG_20170823_234434.jpg
IMG_20170823_234416.jpg
IMG_20170823_234447.jpg

The servo motors are specially designed motor used to control the acceleration and angular rotation of the shaft.

The connection of the servo motor are as follows:

  • The red wire or positive supply is given to positive supply of the breadboard
  • The black wire or negative supply is given to the GND pin of the breadboard
  • The orange wire or signal wire is connected to the pin no 3 of node MCU

Coding

2.png
#include<Servo.h>
const int trigPin = 15;
const int echoPin = 13;
long duration;
int distance;
int safetyDistance;
Servo myservo; // create servo object to control a servo // twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myservo.attach(0);Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;
safetyDistance = distance;
if (safetyDistance <= 5){
// goes from 0 degrees to 180 degrees // in steps of 1 degree
myservo.write(90); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
else{ // goes from 180 degrees to 0 degrees
myservo.write(0); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position }
Serial.print("Distance: ");
Serial.println(distance);
}

Output

Node ultra