Challenge

Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter

Embedded c - Offline batch 2 - Kirubhakaran

//master code
#include <Wire.h> //library for I2C protocol
#include <LiquidCrystal.h> //library for LCD display

LiquidCrystal lcd(12, 11, 2, 3, 4, 5);//initialize the LCD

byte x=0;//global variable declaration

void setup()
{
  lcd.begin(16, 2);
  //to begin the LCD display
  lcd.print("Master Arduino");
  //to denote the master in lcd
  delay(2000);
  lcd.clear();
  
  Wire.begin();
  //to begin the I2C Comunication from master
}

void loop()
{
  Wire.requestFrom(1, 1);
  //to request data from slave
    x=Wire.read();
  	//to read data from the slave
  
  	Wire.beginTransmission(1);//to send data to the slave
  	float temp = analogRead(A0);
  	byte tmp = map(temp,0,1023,0,127);
      Wire.write(tmp);
  	Wire.endTransmission();//to stop transmitting data to slave
  	
    lcd.setCursor(0, 0);
  	//set cursor in first column first row
  	lcd.print("data frm slave");
  	//to print in the LCD display
  	lcd.setCursor(0, 1);
  	//set cursor in first column second row
  	lcd.print(x);
  	//to print the data from slave 
  delay(500);
  	lcd.clear();
  	//to clear the LCD screen  	
}
// slave code

#include<Wire.h>//I2C protocol library

int inches = 0;
int cm = 0;//global variable declaration

long readUltrasonicDistance(int triggerPin, int echoPin)
{
  pinMode(triggerPin, OUTPUT);  // Clear the trigger
  digitalWrite(triggerPin, LOW);
  delayMicroseconds(2);
  // Sets the trigger pin to HIGH state for 10 microseconds
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW);
  pinMode(echoPin, INPUT);
  // Reads the echo pin, and returns the sound wave travel time in microseconds
  return pulseIn(echoPin, HIGH);
}

void setup()
{
  Wire.begin(5);
  //to begin the I2C communication with the master  
  Wire.onRequest(rqst);
  //to return the data to the masters call.
  Serial.begin(9600);
}

void loop(void)
{
}

void rqst()
{ 
  // measure the ping time in cm
  cm = 0.01723 * readUltrasonicDistance(10, 10);
  // convert to inches by dividing by 2.54
  inches = (cm / 2.54);
  delay(100); // Wait for 100 millisecond(s)
  Wire.write(inches);//write the value to master
}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.