(Note: This is another project made by my son. This tutorial is written by him)
This project is made with the Sonar and Servo Bricks. It was fully created by me, and I am surprised that this creation worked out on its first try. The Sonar Brick detects an object in front of it and triggers the Servo Brick to move the gantry upwards. It then delays for one second before closing the gantry.
Connect:
- Sonar Brick to Port 4A
- Servo Brick to Port 2C
Try out this code:
// Ports
var sv = new Servo(PORT_2C);
var u = new Sonar(PORT_4A);
var s = 10; // Speed of mouth opening and closing
var x = 0; // Velocity of mouth opening and closing
var limits = [35,75]; // Limits of mouth position
var pos = limits[1]; // Position of mouth
var canClose = true; // Mouth can close
sv.setPos(pos); // Reset mouth position
while (true) {
delay(50);
if (parseInt(u.getDistance()) < 20) { // Check if object is less than 20 centimetres in front of Sonar Brick
canClose = false;
x = -s; // Open mouth at full speed
}
else {
if (canClose) {
x = s/2; // Close mouth at half speed (to allow for objects to be thrown in mouth easier)
}
else {
delay(1000); // Waits one second (1000 milliseconds) to close mouth
canClose = true
}
}
if (pos > limits[1]) { // If mouth is closed too far, stops moving
pos = limits[1];
}
else if (pos < limits[0]) { // If mouth is opened to far, stop moving
pos = limits[0];
}
else {
pos += x; // Change mouth position by velocity
sv.setPos(pos); // Set mouth position to position variable
}
}
Here is the Monster House in all its glory: