The smart garage gate
Section 11: Smart systemsLesson 11.4 · ⏱ 8 min
A car closer than 15 cm? The gate (a servo) opens to 90 degrees. Otherwise it closes to 0. Servo is a ready library: gate.write(90).
#include <Servo.h>
const int TRIG = 9;
const int ECHO = 10;
Servo gate;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
gate.attach(6);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int d = pulseIn(ECHO, HIGH) / 58;
if (d < 15) {
gate.write(90);
} else {
gate.write(0);
}
delay(100);
}


🖥️ What happens on the stage?
We ran this code in Robo Maker and the challenge passed: “Bravo! It works”.
📌 Another example: a gate that opens from far away
The limit is 30 cm instead of 15: the gate opens before the car comes very close.
#include <Servo.h>
const int TRIG = 9;
const int ECHO = 10;
Servo gate;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
gate.attach(6);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int d = pulseIn(ECHO, HIGH) / 58;
if (d < 30) {
gate.write(90);
} else {
gate.write(0);
}
delay(200);
}


✍️ Practise
Make the gate.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
The gate opens to 180 instead of 90.
👀 Show the solution🙈 Hide the solution
#include <Servo.h>
const int TRIG = 9;
const int ECHO = 10;
Servo gate;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
gate.attach(6);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int d = pulseIn(ECHO, HIGH) / 58;
if (d < 15) {
gate.write(180);
} else {
gate.write(0);
}
delay(200);
}

Result: fully open.
Medium
It stays open for 3 seconds after the car passes.
👀 Show the solution🙈 Hide the solution
#include <Servo.h>
const int TRIG = 9;
const int ECHO = 10;
Servo gate;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
gate.attach(6);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int d = pulseIn(ECHO, HIGH) / 58;
if (d < 15) {
gate.write(90);
delay(3000);
} else {
gate.write(0);
}
delay(200);
}

Result: still open after the car has gone.
Hard
It opens gradually: 30, then 60, then 90.
👀 Show the solution🙈 Hide the solution
#include <Servo.h>
const int TRIG = 9;
const int ECHO = 10;
Servo gate;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
gate.attach(6);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int d = pulseIn(ECHO, HIGH) / 58;
if (d < 15) {
for (int a = 30; a <= 90; a += 30) {
gate.write(a);
delay(300);
}
delay(1500);
} else {
gate.write(0);
}
delay(200);
}

Result: it opens step by step.

