The car's parking sensor
Section 11: Smart systemsLesson 11.2 · ⏱ 8 min
If the distance is below 20 cm the buzzer rings, otherwise it is silent. tone(8, 1000) is a sound, and noTone(8) is silence.
const int TRIG = 9;
const int ECHO = 10;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(8, OUTPUT);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int d = pulseIn(ECHO, HIGH) / 58;
if (d < 20) {
tone(8, 1000);
} else {
noTone(8);
}
delay(100);
}


🖥️ What happens on the stage?
We tested it in Robo Maker: the buzzer rang at 10 cm and went quiet when we moved away to 50 cm. The challenge passed.
📌 Another example: faster beeping the closer you get
The waiting time comes from map: close = a short wait.
const int TRIG = 9;
const int ECHO = 10;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(8, OUTPUT);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int d = pulseIn(ECHO, HIGH) / 58;
if (d < 50) {
int t = map(d, 0, 50, 50, 500);
tone(8, 1000);
delay(100);
noTone(8);
delay(t);
}
}

✍️ Practise
Make the parking sensor.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
A continuous beep if it comes closer than 10 cm.
👀 Show the solution🙈 Hide the solution
const int TRIG = 9;
const int ECHO = 10;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(8, OUTPUT);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int d = pulseIn(ECHO, HIGH) / 58;
if (d < 10) {
tone(8, 1500);
} else {
noTone(8);
}
delay(100);
}

Result: silent when far, continuous when close.
Medium
A higher note the closer the thing gets (map for the frequency).
👀 Show the solution🙈 Hide the solution
const int TRIG = 9;
const int ECHO = 10;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(8, OUTPUT);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int d = pulseIn(ECHO, HIGH) / 58;
if (d < 60) {
tone(8, map(d, 0, 60, 2000, 300));
} else {
noTone(8);
}
delay(100);
}

Result: the note rises as it comes closer.
Hard
Print the distance on the Serial too.
👀 Show the solution🙈 Hide the solution
const int TRIG = 9;
const int ECHO = 10;
void setup() {
Serial.begin(9600);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(8, OUTPUT);
}
void loop() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
int d = pulseIn(ECHO, HIGH) / 58;
Serial.println(d);
if (d < 20) {
tone(8, 1000);
} else {
noTone(8);
}
delay(200);
}

50
50
12
12
12
12
12
12
12
12
12
12
Result: numbers on the Serial, and beeping.

