Inputs and Outputs - Week 3

Hey! This is just a funny experiment where I play with an Arduino, connected to a Distance Sensor and a Servo Motor. When the object is close to the sensor (Less than 5cms) the Servo motor is activate it doing a sweep movement. When the object gets away, the servo motor shuts down.

I applied this configuration to a funny exercise of adding Cream Cheese to a Bagel. Everyday breakfast in New York City.

Next you will find pictures of the process, a short video and the code!

DarioNarvaez_Portfolio_Bagel_Spread_01.jpg
Servo+Distance_DarioNarvaez.jpg
#include <Servo.h>
#define trigPin 7
#define echoPin 6

Servo servo;


void setup()

{
  
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  servo.attach(8);

}

void loop()

{

  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  int pos = 0;
  
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  
  if (distance < 5)
  
  {
  
  Serial.println("the distance is less than 5");
  
  //servo.write(120);

  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    servo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(5);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    servo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(5);                       // waits 15ms for the servo to reach the position
  }
  
  }
  
  else
  
  {
  
  servo.write(0);
  
  }
  
  if (distance > 60 || distance <= 0)
  
  {
  
  Serial.println("The distance is more than 60");
  
  }
  
  else
  
  {
  
  Serial.print(distance);
  
  Serial.println(" cm");
  
  }
  
  delay(500);

}