Robotika ● שיעור 4Lesson 4
→ חזרה← Back
קורס ארדואינו · מפגש 4Arduino course · Session 4

שלט רחוק
שלוש דרכים לנהוג במכונית
Remote control
three ways to drive the car

בשיעור 3 המכונית נהגה לבדה. היום אתם נוהגים בה — בשלוש דרכים: שלט אינפרא-אדום (IR), שלט רדיו (RF) שנבנה בעצמנו, וBluetooth מהטלפון. ובדרך נלמד לסדר קוד גדול עם קבצי כותרת (.h/.cpp): כותבים את המכונית פעם אחת, ומחליפים רק את השלט. In Lesson 3 the car drove itself. Today you drive it — in three ways: an infrared (IR) remote, a radio (RF) remote we build, and Bluetooth from your phone. Along the way we tame bigger code with header files (.h/.cpp): write the car once, just swap the remote.

📺 IR — אור אינפרא-אדום (כמו שלט טלוויזיה)IR — infrared light (like a TV remote)
📡 RF — רדיו 433MHz (עובר קירות)RF — 433MHz radio (through walls)
📱 Bluetooth — הטלפון הוא השלטBluetooth — the phone is the remote

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

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

שלוש דרכים — אותה מכוניתThree ways — the same car

  • IR: שלט טלוויזיה מוכן. לומדים לקרוא את הקודים שלו ונוהגים.IR: a ready-made TV remote. We learn to read its codes and drive.
  • RF: בונים שלט רדיו משלנו על ארדואינו שני.RF: we build our own radio remote on a second Arduino.
  • Bluetooth: הטלפון נוהג, דרך אפליקציית Dabble.Bluetooth: the phone drives, via the Dabble app.

הרעיון שמחבר: קוד לשימוש חוזרThe connecting idea: reusable code

לשלוש הדרכים אותן תנועות בדיוק (קדימה/אחורה/פנייה/עצירה). לכן נכתוב אותן פעם אחת בתוך מודול, וכל שלט ישתמש בו. זה בדיוק מה שקבצי כותרת נותנים:All three share the exact same moves (forward/back/turn/stop). So we write them once in a module, and every remote uses it. That's exactly what header files give us:

  • Motors.h / Motors.cpp — מודול המנועים, משותף לשלושתןthe motors module, shared by all three
  • RadioProtocol.h — קובץ הקודים המשותף לשלט ה-RF ולמכוניתthe codes file shared by the RF remote and car

3אותה מכונית, שלטים מתחלפיםSame car, swappable remotes

בשיעור 3 כתבנו את תנועות המכונית: drive(), stopCar(). היום הן לא משתנות בכלל. מה שמשתנה הוא רק מאיפה מגיעה הפקודה: מאור IR, מגל רדיו, או מהטלפון. In Lesson 3 we wrote the car's moves: drive(), stopCar(). Today they don't change at all. The only thing that changes is where the command comes from: IR light, a radio wave, or the phone.

זה הלב של השיעור: הפלט זהה, רק הקלט מתחלף. בדיוק בגלל זה כדאי לארוז את הפלט (המנועים) בקובץ נפרד לשימוש חוזר. That's the heart of the lesson: the output is identical, only the input swaps. Which is exactly why it pays to package the output (the motors) in a separate, reusable file.

❓ אם שלושת השלטים קוראים לאותן פונקציות תנועה — כמה פעמים כדאי לכתוב אותן?If all three remotes call the same movement functions — how many times should we write them?

בחרו שלט, לחצו חץ — אותה מכונית זזה:Pick a remote, press an arrow — the same car moves:

4IR — הודעה על גבי אור אינפרא-אדוםIR — a message carried by infrared light

הדרך הראשונה היא בדיוק כמו השלט של הטלוויזיה: נורית אינפרא-אדום (אור שהעין לא רואה) מהבהבת מהר מאוד בתבנית, ומקלט על המכונית מפענח אותה. The first way is exactly like your TV remote: an infrared LED (light the eye can't see) flickers very fast in a pattern, and a receiver on the car decodes it.

  • צריך קו ראייה — אור לא עובר דרך קיר (כמו טלוויזיה)Needs line of sight — light doesn't pass through a wall (like a TV)
  • חד-כיווני, וטווח קצר יחסיתOne-way, and fairly short range
  • הספרייה IRremote מפענחת כל לחיצה למספרThe IRremote library decodes each press into a number
חיווט המקלט: OUT → D9, VCC → 5V, GND → GND.Receiver wiring: OUT → D9, VCC → 5V, GND → GND.

אור אינפרא-אדום נע בקו ישר מהשלט אל המקלט — בדיוק כמו טלוויזיה.Infrared light travels straight from remote to receiver — just like a TV.

5IR — קוראים את הקודים של השלטIR — read the remote's codes

כל שלט IR מדבר קצת אחרת, אז קודם לומדים אותו: מריצים סקיצת עזר, פותחים Serial Monitor (9600), ולוחצים על כל כפתור. כל כפתור מדפיס מספר (HEX) — רושמים אותם. Every IR remote speaks a bit differently, so first we learn it: run a helper sketch, open the Serial Monitor (9600), and press each button. Each prints a number (HEX) — write them down.

void loop() {
  if (IrReceiver.decode()) {
    Serial.print("command (HEX): 0x");
    Serial.println(
      IrReceiver.decodedIRData.command, HEX);
    IrReceiver.resume(); // next button
  }
}

📄 code/IrReadCodes.ino📄 code/IrReadCodes.ino

זה מה שתראוWhat you'll see

כפתורButtonקוד (דוגמה)Code (example)
▲ UP0x18
▼ DOWN0x52
◀ LEFT0x08
▶ RIGHT0x5A
OK0x1C
הקודים שלכם כנראה שונים! אלו רק דוגמה. העתיקו את שלכם לסקיצת הנהיגה.Your codes are probably different! These are just an example. Copy yours into the driving sketch.

6IR — נוהגיםIR — drive

ממלאים את 5 הקודים, והשלט נוהג. שימו לב: התנועות מגיעות מ-Motors.h (drive, stopCar) — בדיוק מה שנשתמש בו גם ב-RF וב-Bluetooth. רק הקלט כאן הוא IR. Fill in the 5 codes and the remote drives. Note: the moves come from Motors.h (drive, stopCar) — the very thing RF and Bluetooth will use too. Only the input here is IR.

#include <IRremote.h>
#include "Motors.h"   // the shared moves

void loop() {
  if (IrReceiver.decode()) {
    uint8_t c = IrReceiver.decodedIRData.command;
    if      (c == BTN_UP)   drive( SPEED,  SPEED);
    else if (c == BTN_DOWN) drive(-SPEED, -SPEED);
    // ... LEFT / RIGHT / OK
    lastCmd = millis(); IrReceiver.resume();
  }
  if (millis()-lastCmd > 200) stopCar(); // failsafe
}

📄 code/IrCar.ino📄 code/IrCar.ino

אותו דפוס בכל שלטThe same pattern every time

  • קלט — קוראים מה הגיע (כאן: קוד IR)Input — read what arrived (here: an IR code)
  • החלטה — if/else: איזה קוד = איזו תנועהDecide — if/else: which code = which move
  • פלט — drive() / stopCar() מ-Motors.hOutput — drive() / stopCar() from Motors.h
זכרו את הדפוס הזה — RF ו-Bluetooth יחליפו רק את שורת הקלט.Remember this pattern — RF and Bluetooth will swap only the input line.

7RF — רדיו 433MHz, ובונים שלט משלנוRF — 433MHz radio, and we build our own remote

הדרך השנייה: גלי רדיו ב-433MHz. בניגוד ל-IR, רדיו לא צריך קו ראייה, עובר דרך קירות, ומגיע רחוק. וכאן גם בונים את השלט: ארדואינו שני עם 4 כפתורים ומשדר רדיו. הספרייה: rc-switch. The second way: radio waves at 433MHz. Unlike IR, radio needs no line of sight, passes through walls, and reaches far. And here we also build the remote: a second Arduino with 4 buttons and a radio transmitter. Library: rc-switch.

❓ מתי IR עדיף, ומתי RF? (חשבו על קיר, על טווח, ועל "מי עוד שומע")When is IR better, and when RF? (think walls, range, and "who else is listening")
📺 IR📡 RF 433
מתווךCarrierאורlightגלי רדיוradio
קו ראייה?Line of sight?צריךneededלא צריךnot needed
דרך קירותThrough walls✗✓
טווחRangeקצרshortארוךlong
השלטThe remoteמוכןready-madeבוניםwe build it
חיווט המקלט במכונית: DATA → D2 (פין פסיקה). לכן IN1 של המנוע עבר ל-D8 — פרטים בהמשך.Car receiver wiring: DATA → D2 (an interrupt pin). So motor IN1 moved to D8 — details later.

8RF — שני לוחות חייבים להסכיםRF — two boards must agree

השלט שולח מספר לכל כיוון (למשל "11" = קדימה), והמכונית מחכה לאותו מספר. אבל עכשיו יש שני לוחות עם שתי תוכניות — וצריך שיסכימו על הקודים. אם נכתוב את הקודים בשתי התוכניות בנפרד, מתישהו הם יתפצלו, והמכונית פשוט תתעלם. The remote sends a number per direction (e.g. "11" = forward), and the car waits for the same number. But now there are two boards with two programs — and they must agree on the codes. If we write the codes in both programs separately, one day they'll drift apart, and the car will simply ignore you.

❓ מה הבאג הכי קשה למצוא — כזה שקורס, או כזה ש"פשוט לא עובד" בלי הודעת שגיאה?Which bug is hardest to find — one that crashes, or one that "just doesn't work" with no error?

שנו את הקוד של "קדימה" בשלט — וראו אם המכונית עדיין מבינה:Change the "forward" code on the remote — see if the car still understands:

🎮 השלט שולחremote sends
CODE_UP = 11
🚗 המכונית מחכה לcar waits for
CODE_UP = 11

9RF — הפתרון: RadioProtocol.hRF — the fix: RadioProtocol.h

קובץ כותרת הוא קובץ ש"מדביקים" לקוד עם #include. נכתוב את הקודים פעם אחת ב-RadioProtocol.h, ושני הצדדים יעשו לו #include. מקור אמת אחד — אי אפשר "לשכוח לעדכן את השני". A header file is a file you "paste" into code with #include. We write the codes once in RadioProtocol.h, and both sides #include it. One source of truth — you can't "forget to update the other one".

RadioProtocol.h
#pragma once
const long CODE_STOP  = 10;
const long CODE_UP    = 11;
const long CODE_DOWN  = 12;
const long CODE_LEFT  = 13;
const long CODE_RIGHT = 14;

שתי צורות של #includeTwo shapes of #include

#include <RCSwitch.h>ספרייה שהתקנוan installed library
#include "RadioProtocol.h"קובץ שלנו, ליד הסקיצהour file, next to the sketch

לחצו — #include "מדביק" את הקובץ פנימה:Press — #include "pastes" the file in:

RfCar.ino
#include "RadioProtocol.h"
// <-- the codes appear here
✓ אותו קובץ נמצא גם בשלט וגם במכונית — לכן הם לא יכולים "להתפצל".✓ The same file sits in both the remote and the car — so they can't "drift".

10Bluetooth — הטלפון מדבר עם המכוניתBluetooth — the phone talks to the car

הדרך השלישית: אין שלט נפרד בכלל — הטלפון הוא השלט. מודול Bluetooth (HC-05) על המכונית מדבר עם אפליקציה חינמית בשם Dabble, שבה יש ג'ויסטיק על המסך. The third way: no separate remote at all — the phone is the remote. A Bluetooth (HC-05) module on the car talks to a free app called Dabble, which has an on-screen GamePad.

הכנהSetup

  • מתקינים את Dabble בטלפון (אנדרואיד)Install Dabble on the phone (Android)
  • מתקינים את ספריית Dabble ב-Arduino IDEInstall the Dabble library in the Arduino IDE
  • באפליקציה: מתחברים ל-HC-05, פותחים את מודול ה-GamePadIn the app: connect to the HC-05, open the GamePad module
⚠️ ב-Uno מודול ה-Bluetooth לא על D0/D1, אלא על D11/D12 (SoftwareSerial) — כך הקוד מתעדכן ב-USB בלי לנתק כלום. אנדרואיד בלבד.⚠️ On the Uno the Bluetooth module is not on D0/D1 but on D11/D12 (SoftwareSerial) — so USB upload works without unplugging. Android only.

הג'ויסטיק באפליקציה שולח את הכיוון, בדיוק כמו כפתור.The app's GamePad sends the direction, just like a button.

11Bluetooth — נוהגים עם Dabble GamePadBluetooth — drive with the Dabble GamePad

מחזיקים חץ באפליקציה — נוסעים; עוזבים — עוצרים. אותו דפוס בדיוק מ-IR, רק שורת הקלט השתנתה: במקום לקרוא קוד, שואלים את ה-GamePad איזה כפתור לחוץ. Hold an arrow in the app — you drive; let go — you stop. The exact same pattern as IR; only the input line changed: instead of reading a code, we ask the GamePad which button is pressed.

#include <Dabble.h>
#include "Motors.h"   // the same shared moves

void loop() {
  Dabble.processInput();            // read the phone
  if      (GamePad.isUpPressed())    drive( SPEED, SPEED);
  else if (GamePad.isDownPressed())  drive(-SPEED,-SPEED);
  else if (GamePad.isLeftPressed())  drive(-SPEED, SPEED);
  else if (GamePad.isRightPressed()) drive( SPEED,-SPEED);
  else                             stopCar(); // finger off
}

📄 code/BtCar.ino📄 code/BtCar.ino

שלושתם זה אותו קוד כמעטAll three are nearly the same code

שלטRemoteשורת הקלטThe input line
📺 IRdecodedIRData.command
📡 RFgetReceivedValue()
📱 BTisUpPressed()…
הפלט — drive() / stopCar() — זהה בשלושתם. בדיוק למה שווה לארוז אותו פעם אחת.The output — drive() / stopCar() — is identical in all three. Exactly why it's worth packaging once.

12Bluetooth דו-כיווני — המכונית מדברת בחזרהBluetooth is two-way — the car talks back

שמתם לב? IR ו-RF היו חד-כיווניים: השלט מדבר, המכונית רק מקשיבה. Bluetooth הוא חוט שהולך לשני הכיוונים — על אותו קו HC-05, המכונית קוראת את הפקודות שלכם וגם מדווחת מה היא רואה, 5 פעמים בשנייה. Notice? IR and RF were one-way: the remote talks, the car only listens. Bluetooth is a wire that runs both ways — over the same HC-05 link the car reads your commands and reports what it sees, five times a second.

the car → the phone
D=23,M=F,S=160
 |    |    +-- S = speed 0..255
 |    +------- M = move F/B/L/R/S
 +------------ D = distance cm (999=clear)

★ בונוס / פתיח לשיעור הבאbonus / next-lesson teaser · 📄 code/BtTelemetry.ino

if (BT.available())              // IN: a command
  moveCmd = toupper(BT.read());

if (millis()-lastReport >= 200) { // OUT: telemetry
  BT.print("D=");  BT.print(distanceCm);
  BT.print(",M="); BT.print(moveCmd);
  BT.print(",S="); BT.println(carSpeed);
}

שלחו פקודה — וראו אותה חוזרת ב-M=:Send a command — watch it come back in M=:

בשיעור הבא נחבר את הזרם הזה למרכז שליטה בדפדפן — מדדים וכפתורים חיים.Next lesson we wire this stream into a browser command center — live gauges and buttons.

13ההחזר על ההשקעה: מודול מנועיםThe payoff: the motors module

כל שלושת קובצי המכונית עושים #include "Motors.h" ומשתמשים ב-drive() ו-stopCar(). כתבנו את המנועים פעם אחת, ולא מעתיקים אותם לכל סקיצה מחדש. זה בדיוק מה שקובצי כותרת נותנים — קוד לשימוש חוזר. All three car files #include "Motors.h" and use drive() and stopCar(). We wrote the motors once, and don't re-copy them into each sketch. That's exactly what header files give — reusable code.

למה דווקא שני קבצים?Why two files?

.h = התפריט= menu

מה אפשר להזמין — שמות הפקודות.What you can order — the names.

.cpp = המטבח= kitchen

איך מכינים — פינים וחוטים.How it's made — pins and wires.

מי שנוהג במכונית קורא רק את התפריט (Motors.h). את המטבח (Motors.cpp) פותחים רק כדי לשנות איך המנועים עובדים.Whoever drives reads only the menu (Motors.h). You open the kitchen (Motors.cpp) only to change how the motors work.

14מודול המנועים, קובץ-קובץThe motors module, file by file

Motors.h — התפריטthe menu
#pragma once
void beginMotors();
void drive(int left, int right);
void stopCar();

📄 Motors.h📄 Motors.h

Motors.cpp — המטבח (קטע)the kitchen (excerpt)
#include "Motors.h"
const byte ENA=5, IN1=8, IN2=3; // IN1->D8

void drive(int left, int right) {
  oneSide(ENA, IN1, IN2, left);
  oneSide(ENB, IN3, IN4, right);
}
void stopCar() { drive(0, 0); }

📄 Motors.cpp📄 Motors.cpp

IN1 על D8 בכל המכוניות — כדי לפנות את D2 למקלט ה-RF. חיווט אחד שמתאים לשלושתן.IN1 on D8 in every car — to free D2 for the RF receiver. One wiring that fits all three.

15איך .ino, .h ו-.cpp הופכים לתוכנית אחתHow .ino, .h and .cpp become one program

כשפותחים סקיצה ב-Arduino IDE, כל הקבצים בתיקייה מתקמפלים יחד לתוכנית אחת. למשל תיקיית ה-RF car: When you open a sketch in the Arduino IDE, all the files in its folder compile together into one program. For example the RF car folder:

RfCar/
RfCar.ino        // setup + loop (the story)
RadioProtocol.h  // the shared codes
Motors.h         // the menu
Motors.cpp       // the kitchen
לכן ה-ZIP שמורידים בנוי מתיקיות — כל מכונית עם העותקים שהיא צריכה. פותחים את ה-.ino, וה-IDE מרכיב את השאר.That's why the ZIP is built from folders — each car with the copies it needs. Open the .ino, and the IDE assembles the rest.

עצירה כשהפקודות נפסקותStopping when commands go quiet

בכל שלושת השלטים יש עצירת ביטחון: אם לא הגיעה פקודה חדשה זמן קצר — stopCar(). בלי זה, אם השלט כבה / יצא מהטווח / נגמרה הסוללה — המכונית תמשיך בפקודה האחרונה ותברח. All three remotes have a failsafe: if no new command arrives for a short moment — stopCar(). Without it, if the remote dies / goes out of range / loses battery — the car keeps its last command and runs away.

❓ IR, RF ו-Bluetooth — לכל אחד יש דרך "להיעלם". איך העצירה מגינה על כולן באותה צורה?IR, RF and Bluetooth each has a way to "vanish". How does the stop protect all three the same way?
🛞 בדיקה ראשונה תמיד עם הגלגלים מורמים מהשולחן.🛞 First test always with the wheels raised off the table.

16מפת חיבורים ובדיקת ספסלWiring map & bench test

חיווט אחד למכונית — לכל השלטיםOne car wiring — for every remote

רכיבPartאלTo
L298N · ENA / IN1 / IN2
D5 / D8 / D3
L298N · ENB / IN3 / IN4
D6 / D4 / D7
📺 מקלט IRIR receiver
D9
📡 מקלט RF — DATARF receiver — DATA
D2
📱 HC-05 — TXD / RXD
D11 / D12
המנועים תמיד אותו דבר (IN1 על D8). כל שלט מוסיף רק את המקלט שלו לפין פנוי משלו.The motors are always the same (IN1 on D8). Each remote adds only its own receiver on its own free pin.

סדר עבודהOrder of work

  • גלגלים מורמים, ומעלים את הסקיצה של השלט שבחרתםWheels raised, upload the sketch for the remote you chose
  • לוחצים כיוון — בודקים שכל צד נוסע נכוןPress a direction — check each side drives correctly
  • צד הפוך? מחליפים IN3↔IN4 (או IN1↔IN2) של אותו צדA side reversed? Swap that side's IN3↔IN4 (or IN1↔IN2)
  • רק כשהכול נכון — מורידים לרצפהOnly when it's all correct — to the floor

17סיכום — מה לקחנו הביתהSummary — what we take home

הרעיון האחד להיוםThe one idea for today

נהגנו באותה מכונית בשלוש דרכים — IR, RF ו-Bluetooth — וראינו שהפלט זהה והקלט מתחלף. לכן ארזנו את המנועים במודול לשימוש חוזר (Motors.h/.cpp), ואת קודי הרדיו בקובץ משותף (RadioProtocol.h). זה הכוח של קבצי כותרת: אותו מידע — מקום אחד. We drove the same car in three ways — IR, RF and Bluetooth — and saw the output stays, the input swaps. So we packaged the motors in a reusable module (Motors.h/.cpp) and the radio codes in a shared file (RadioProtocol.h). That's the power of header files: one fact — one place.

המילים החדשותThe new words

IR / IRremote · RF433 / rc-switch · Dabble · קובץ כותרתheader file · .h / .cpp · #include "…" · #pragma once · failsafe

בשיעור הבאNext lesson

כל השלטים שלנו חד-כיווניים — המכונית שותקת. בשיעור הבא נוסיף ערוץ חזרה: המכונית תדווח מה היא רואה (מרחק, מהירות) למרכז שליטה במחשב. הלוך ושוב. All our remotes are one-way — the car is silent. Next lesson we add a return channel: the car reports what it sees (distance, speed) to a command center on the computer. There and back.

💻 כל קבצי הקוד של השיעור — הורדהAll of this lesson's code — download

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