Published on

Day 3 Assignment Solutions

Table of Contents

Assignment 1 Solution

Code:


#define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04

// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
  Serial.println("with Arduino UNO R3");
}
void loop() {
  // Clears the trigPin condition
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  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; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  int writer=0;
  writer=map(distance,0,100,0,255);//google what the map function is
  analogWrite(10,distance);
  digitalWrite(11,LOW);
}

Assignment 2 Solution

Schematic:

IR

Code:

int irPin = 8;

int motorPin1 = 10;
int motorPin2 = 11;

int val = 0;
int num = 0;

void setup()
{
  pinMode(irPin,INPUT);

  pinMode(motorPin1,OUTPUT);
  pinMode(motorPin2,OUTPUT);

  Serial.begin(9600);
}

void loop()
{
  val = digitalRead(irPin);

  if(val==0)
  {
    num = val;
  }

    while(num == 0)
    {
      analogWrite(motorPin1,255);
      analogWrite(motorPin2,0);

      val = digitalRead(irPin);
      if(val==0)
      {
        num = 1;
      }
    }

    while(num == 1)
    {
      analogWrite(motorPin1,0);
      analogWrite(motorPin2,255);

      val = digitalRead(irPin);
      if(val==0)
      {
        num = 0;
      }
    }
}