For our tech demo 3, Stone and I decided to make a catapult that would launch an object when a sensor notified the servo to move. The sensor detected the distance between itself and a moving object and determined when to shoot. We laser cut a base, 2 walls to hold a metal rod that would allow the catapult to actively and frictionlessly throw the ball, and the catapult (thrower) itself. The spring in the front allows for tension to build as a weight with a string attached keeps the catapult from moving. When the servo moves, however, it pulls the weight from the catapult and the tension takes over and whips the catapult into action.
// ReadSonar - measure distance using a HC-SR04 or compatible ultrasonic ranger // // With the help of Garth Zieglin ================================================================================ // Define constant values. #include <Servo.h> // The wiring assignment. const int TRIG_PIN = 8; const int ECHO_PIN = 7; const int SERVO_PIN = 9; Servo servo; // The rated distance limit of the sensor, in cm. const int MAX_DISTANCE = 450; // A typical speed of sound, specified in cm/sec. const long SOUND_SPEED = 34000; const long TIMEOUT = (2 * MAX_DISTANCE * 1000000)/SOUND_SPEED; void setup() { // Initialize the serial UART at 9600 bits per second. Serial.begin(9600); servo.attach(SERVO_PIN); servo.write(0); // Initialize the trigger pin for output. pinMode(TRIG_PIN, OUTPUT); digitalWrite(TRIG_PIN, LOW); // Initialize the echo pin for input. pinMode(ECHO_PIN, INPUT); } // ================================================================================ // Run one iteration of the main event loop. The Arduino system will call this // function over and over forever. void loop() { long duration = ping_sonar(); // function is defined below if (duration > 0) { float distance = (duration * 1e-6 * SOUND_SPEED) / 2; if(distance < 10){ servo.write(180); } } else { // if no pulse detected Serial.println("No ping."); } // Allow a little extra time for the sonar to recover. delay(30); } long ping_sonar(void) { // Generate a short trigger pulse. digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // Measure the pulse length return pulseIn(ECHO_PIN, HIGH, TIMEOUT); }
Source: Course Website (for parts of the code)
Leave a Reply
You must be logged in to post a comment.