Robotika ● שיעור 2Lesson 2
קורס ארדואינו · מפגש 2Arduino course · Session 2

חיישן מרחק (סונאר)
ותצוגת ספרות
Distance sensor (sonar)
and a digit display

היום נלמד איך המחשב "רואה" מרחק בעזרת קול, נציג את המספר על תצוגה, ונוסיף נורית אזהרה חכמה. Today: how the computer "sees" distance using sound, shows the number on a display, and adds a smart warning light.

1. סונאר → מסך המחשבSonar → computer screen
2. הוספת תצוגת ספרותAdd the digit display
3. נורית שמהבהבת מהר יותר בקרבהLED that blinks faster up close

ניווט: חצים ← → במקלדת, או הכפתורים למטה · לחצו EN לבדיקת מונחים באנגלית Navigate: ← → arrow keys, or the buttons below · press עב for Hebrew

2מה נעשה היוםWhat we'll do today

רעיונותIdeas

  • זרימת תוכנית: אם / אחרת (if / else)Program flow: if / else
  • איך סונאר מודד מרחק בעזרת קולHow sonar measures distance with sound
  • איך החיישן בנוי — ולמה יש "חוט שעון"How the parts work — and why there's a "clock wire"
  • לחבר קלט + פלט + קוד יחדWire input + output + code together

הבנייה — בשלושה שלביםThe build — in three levels

  • שלב 1: סונאר שכותב מרחק למוניטורLevel 1: sonar prints distance to the monitor
  • שלב 2: מוסיפים פלט — תצוגת הספרותLevel 2: add an output — the digit display
  • שלב 3: נורית שדופקת מהר יותר ככל שמתקרבים (מנקודת התחלה)Level 3: an LED that pulses faster as it gets closer (from a start point)

3תזכורת קצרה משיעור 1Quick recap of Lesson 1

digitalWrite / digitalRead

שולטים בפין ומדליקים/מכבים — נורית שהבהבה.Drive a pin on/off — the blinking LED.

analogRead

קוראים ערך משתנה — חיישן האור.Read a changing value — the light sensor.

setup() / loop()

setup רץ פעם אחת, loop חוזר שוב ושוב.setup runs once, loop repeats forever.

היום מוסיפים חיישן שמדבר בזמן (לא במתח), ופלט חדש שמדבר בתקשורת טורית. Today we add a sensor that speaks in time (not voltage), and a new output that speaks over serial communication.

4זרימת תוכנית: אם / אחרתProgram flow: if / else

התוכנית מקבלת החלטה: אם התנאי נכון — עושים דבר אחד; אחרת — דבר אחר. The program makes a decision: if the condition is true — do one thing; else — do another.

if (distance > 30) {
  // far — all clear
  ledOff();
} else {
  // close — warn!
  blink();
}

גררו את המרחק ותראו איזה ענף "נדלק":Drag the distance and watch which branch lights up:

מרחקDistance: 45 cm

5איך סונאר מודד מרחקHow sonar measures distance

החיישן צועק צליל על-קולי (אנחנו לא שומעים אותו), הצליל פוגע בעצם וחוזר כהד. החיישן מודד כמה זמן לקח לצליל לצאת ולחזור. The sensor shouts an ultrasonic sound (we can't hear it), it hits an object and echoes back. The sensor measures the time for the sound to go and return.

מהירות הקול ≈ 343 מטר לשנייה = 0.0343 ס״מ בכל מיקרו-שנייה (µs). Speed of sound ≈ 343 m/s = 0.0343 cm per microsecond (µs).

הנוסחהThe formula

distance = (time × 0.0343) / 2

למה חלקי 2? כי הזמן שמדדנו הוא לשם ובחזרה — הלוך ושוב. Why divide by 2? Because the time measured is for the trip there AND back.

זמןtime: — µs · — cm

שימושים אפשרייםPossible uses

  • חיישני חנייה ומניעת התנגשות ברכבParking sensors & car collision-avoidance
  • רובוט שנמנע ממכשוליםA robot that avoids obstacles
  • מדידת מפלס מים במיכלMeasuring the water level in a tank
  • פתיחה אוטומטית של דלת או ברזAn automatic door or faucet

▶ רכב עם מניעת התנגשותcollision-avoidance car

6החיישן מקרוב — Trig ו-EchoThe sensor up close — Trig & Echo

לחיישן הסונאר יש 4 פינים. שניים לחשמל, ושניים ל"שיחה" עם הארדואינו: The sonar has 4 pins. Two for power, two to "talk" with the Arduino:

  • VCC → 5V  ·  GND → GND (חשמלpower)
  • Trig → אנחנו שולחים פולס קצר של 10µs = "עכשיו תמדוד!"we send a short 10µs pulse = "measure now!"
  • Echo → החיישן מחזיר פין שנשאר גבוה בדיוק כמשך הזמן של ההד. אנחנו מודדים אותו עם pulseIn().the sensor holds this pin HIGH for exactly the echo time. We measure it with pulseIn().
שימו לב: Trig הוא פולס חד-פעמי להתחלה — הוא לא חוט שעון. את חוט השעון נפגוש בתצוגה (השקף הבא). Note: Trig is a one-shot start pulse — it is not a clock wire. We'll meet the clock wire in the display (next slide).

רצף המדידהThe measurement sequence

// 1) fire the trigger
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);

// 2) time the echo (round trip, µs)
long t = pulseIn(echo, HIGH);

// 3) time -> distance
float cm = t * 0.0343 / 2;

7התצוגה — ולמה יש "חוט שעון"?The display — and why a "clock wire"?

תצוגת הספרות מקבלת מידע בשני חוטים:The digit display receives data on two wires:

  • DIO — נתונים: הביטים עצמם (0 או 1)data: the bits themselves (0 or 1)
  • CLK — שעון: פעימה שאומרת "עכשיו! קרא ביט"clock: a beat that says "now! read a bit"

בלי שעון משותף, הצד המקבל לא יודע מתי כל ביט תקף. השעון הוא המטרונום ששני הצדדים סופרים לפיו — זו "תקשורת טורית". Without a shared clock, the receiver wouldn't know when each bit is valid. The clock is the metronome both sides count to — this is "serial communication".

בכל עלייה של השעון, התצוגה "צובטת" את הערך שנמצא כרגע על חוט הנתונים. On every rising edge of the clock, the display "latches" whatever value is on the data wire.
נקלטcaptured: ________ = —

8חיווט הכל יחדWiring it all together

טבלת חיבוריםConnection table

ComponentPinArduino
HC-SR04TrigD9
HC-SR04EchoD10
TM1637CLKD4
TM1637DIOD5
LED (+)via 220ΩD6
AllVCC / GND5V / GND
הרגל הארוכה של הנורית = פלוס (+). תמיד נגד 220Ω בסדרה כדי לא לשרוף אותה. The LED's long leg = plus (+). Always a 220Ω resistor in series so it doesn't burn out.

9שלב 1 — סונאר למסךLevel 1 — sonar to the screen

המטרה: מספר מרחק מתעדכן בחלון המוניטור הטורי.Goal: a live distance number in the Serial Monitor.

const int trigPin = 9;
const int echoPin = 10;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH); delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH);
  float distanceCm = duration * 0.0343 / 2;

  Serial.print("Distance: ");
  Serial.print(distanceCm);
  Serial.println(" cm");
  delay(200);
}

10שלב 2 — מוסיפים תצוגהLevel 2 — add the display

מעבירים את הקריאה לפונקציה משלנו, ומדפיסים על התצוגה. צריך את הספרייה TM1637Display. Move the reading into our own function, and print on the display. Needs the TM1637Display library.

#include <TM1637Display.h>
const int trigPin=9, echoPin=10, CLK=4, DIO=5;
TM1637Display display(CLK, DIO);

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT);
  display.setBrightness(5);
}

void loop() {
  int distanceCm = getDistanceCm();     // our function
  Serial.println(distanceCm);
  display.showNumberDec(distanceCm);      // show on display
  delay(200);
}

int getDistanceCm() {
  digitalWrite(trigPin, LOW);  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH); delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);
  return duration * 0.0343 / 2;
}

11שלב 3 — נורית אזהרה חכמהLevel 3 — a smart warning LED

כאן נכנס ה-if / else וגם map(): הופכים "מרחק" ל"קצב הבהוב". Here the if / else and map() come in: turn "distance" into "blink speed".

const int START_CM = 30;

if (distanceCm > START_CM) {
  digitalWrite(ledPin, LOW);   // far: off
  delay(200);
} else {
  int d = map(distanceCm, 0, START_CM, 40, 500);
  digitalWrite(ledPin, HIGH); delay(d);
  digitalWrite(ledPin, LOW);  delay(d);
}

map: מרחק 0 → 40ms (מהיר) · מרחק 30 → 500ms (איטי) map: distance 0 → 40ms (fast) · distance 30 → 500ms (slow)

20 cm → קצבrate — ms

★בונוס — מכונית שעוצרת לפני מכשולBonus — a car that stops for obstacles

מרכיבים את החיישן על חזית המכונית. היא מחכה 2 שניות, מתחילה לנסוע קדימה, ועוצרת כשמשהו נמצא ממש לפניה (בערך 5 ס״מ). The sensor sits on the front of the car. It waits 2 seconds, drives forward, and stops when something is right in front of it (about 5 cm).

אותו רעיון — פלט חדשSame idea — a new output

זה בדיוק ה-if / else עם הסונאר מהשיעור, אבל במקום נורית — 4 מנועים. אם קרוב מ-5 ס״מ → עצור, אחרת → סע. It's exactly the if / else with the sonar from the lesson, but instead of an LED — 4 motors. If closer than 5 cm → stop, else → drive.

למה גשר H (H-bridge)? פין של הארדואינו חלש מדי כדי להניע מנוע, ולא יכול להפוך כיוון. ה-L298N לוקח כוח מסוללה, והארדואינו רק אומר לו "סע / עצור / כיוון". Why an H-bridge? An Arduino pin is too weak to run a motor and can't reverse it. The L298N takes power from a battery, and the Arduino just tells it "go / stop / direction".
  1. מעלים את bonus_car_obstacle.inoUpload bonus_car_obstacle.ino
  2. מניחים על הרצפה ומדליקים את סוללת המנועיםPut it on the floor, turn on the motor battery
  3. אחרי 2 שניות היא נוסעת — ידיים מוכנות לתפוס!After 2 seconds it drives — hands ready to catch it!

חשוב: ה-GND של ה-L298N והארדואינו חייבים להיות מחוברים יחד. Important: the L298N's GND and the Arduino's GND must be connected together.

🎬 מדריך וידאו — מכונית עם מניעת התנגשות🎬 Video tutorial — collision-avoidance car

▶ youtube.com/watch?v=LO-tLG4t5Dg  ·  אין אינטרנט בכיתה? הקישור נפתח בכל מחשבno internet in class? the link opens anywhere

13חיווט ה-L298NWiring the L298N

L298N motor driver board

הכרטיס — מה כל חלק (לזיהוי)The board — what each part is (for identification)

חיבור לארדואינוConnect to the Arduino

L298NArduino
ENA→D5  PWM · remove jumper
IN1→D2
IN2→D3
IN3→D4
IN4→D7
ENB→D6  PWM · remove jumper
Vs (5–35V)→battery +
GND→battery − & Arduino GND
Motor A / B→left / right motors
מסירים את כובעי הג׳מפר של ENA ו-ENB — רק אז analogWrite שולט במהירות. אם משאירים אותם, המנועים רצים במלוא הכוח. Remove the ENA & ENB jumper caps — only then does analogWrite control speed. Leave them on and the motors run flat-out.
GND משותף! ה-GND של הכרטיס, הסוללה והארדואינו — כולם יחד. זו התקלה הכי נפוצה. Shared ground! the board's, battery's and Arduino's GND all tie together. The most common failure.

ג׳מפר 12V: משאירים לסוללה עד 12V.12V jumper: keep it on for a battery up to 12V.

14סיכום ואתגרSummary & challenge

מה למדנוWhat we learned

  • סונאר מודד זמן והופך אותו למרחק (חלקי 2!)Sonar measures time and turns it into distance (divide by 2!)
  • Trig = פולס התחלה · Echo = משך ההדTrig = start pulse · Echo = echo duration
  • חוט שעון (CLK) מסנכרן תקשורת טוריתA clock wire (CLK) syncs serial communication
  • if / else + map() = התנהגות חכמהif / else + map() = smart behavior

אתגר 🏁Challenge 🏁

  • הוסיפו זמזם (buzzer) שמצפצף יחד עם הנוריתAdd a buzzer that beeps along with the LED
  • הציגו על התצוגה "Stop" כשמתקרבים מאודShow "Stop" on the display when very close
  • מתקדמים: החליפו את ה-delay ב-millis() כדי שהכול ירוץ חלקAdvanced: replace delay with millis() so everything runs smoothly

תודה — נתראה בשיעור הבא! 👋Thanks — see you next lesson! 👋