Monday, August 3, 2020

Servo Catapult with ultrasonic distance sensor

A Popsicle stick and rubber band catapult waits for something to get close and launches a cotton ball at it. 
  • An ultrasonic sensor is used to test distance to nearest object. 
  • A servo motor releases the catapult.

Wiring

Servo motor connections:
  • brown to Neg on 9V battery
  • red to Pos on 9Vbattery
  • yellow to signal output pin on Arduino
    • use analog pin or PWM pin marked with ~
Ultrasonic distance sensor connections;
  • Gnd to Gnd on Ardiuno [black]
  • Trigger to Arduino (using pin ) [green]
  • Echo  to Arduino (using pin )   [blue]
  • VCC to 5V on Ardiuno [red]

Code

#include <Servo.h>
Servo cata;      // servo
const int cataPin = 2; // servo on pin 2

// degree positions for Catapult
const int launchCata = 0;   //degrees
const int resetCata  = 180; //degrees

// Ultrasonic distance sensor
// wiring...
// GND to  Ardiuno GND - black
const int trigger = 4; // green  
const int echo    = 3; // blue
// VCC signal  - red

const int sonicDelay = 100; // min of 10ms =100 microsecs
const int tooClose = 40; // 40 cm is too close

void setup() {
  // ultrasonic sensor pins for catapult
  pinMode(trigger, OUTPUT);   
  pinMode(echo, INPUT);
  cata.attach(cataPin);             
  Serial.begin(9600);
}

// sonicBat - use ultrasonic sensor to find distance to nearest object like a bat does
int sonicBat () {  
    long duration, distance; 
    digitalWrite(trigger,HIGH); 
    delayMicroseconds(sonicDelay); 
    digitalWrite(trigger,LOW);
    duration = pulseIn(echo,HIGH);  
            // pulseIn- Reads a pulse (HIGH/LOW) on a pin. 
            //   When the pin goes HIGH it starts timing 
            //   til it's Low and stops timing.
            //   Returns the length of the pulse in ms
    distance = (duration/2)/29.1; // speed of sound is: ~29.1 microsecs/cm or 1/29.1 cm/microsec
    delay(sonicDelay);
    return distance;   
}

void loop() {
  long distance;
  distance = sonicBat();
  Serial.println(distance);

  if (distance >= tooClose) {  
    cata.write(resetCata); 
    delay(10);
  }
  else { // distance < tooClose 
      cata.write(launchCata);
      delay(1600);
      cata.write(resetCata);
      delay(1600);
  }
}

No comments:

Post a Comment

Arduino and pump

Motor Driver witn 9110 or 9110S  https://www.laskakit.cz/user/related_files/l9110_2_channel_motor_driver.pdf https://docs.sunfounder.com/pro...