שלט רחוק: IR, RF ו-Bluetooth — ומודול מנועים משותף · כל קובץ בעמוד משלו, עם הקוד המלא וכפתור הורדה.Remote control: IR, RF & Bluetooth — and a shared motors module · one file per page, with the full code and a download button.
⬇ להוריד הכל (zip)Download all (zip)
כל שלט IR שונה. מריצים, פותחים Serial (9600), ורושמים את הקוד של כל כפתור. ספרייה: IRremote.Every IR remote differs. Run it, open Serial (9600), and note each button's code. Library: IRremote.
/* Robotika - Course 44, Lesson 4 IR helper: learn YOUR remote's button codes Every IR remote is a little different, so first we read the codes once and write them down. Upload this, open Serial Monitor (9600), point the small remote at the receiver and press UP / DOWN / LEFT / RIGHT / OK. Copy the HEX code each button prints into IrCar.ino. Library: "IRremote" (Library Manager -> search "IRremote"). Wiring: IR receiver OUT -> D9 VCC -> 5V GND -> GND*/#include <IRremote.h>const int IR_PIN = 9;void setup() { Serial.begin(9600); IrReceiver.begin(IR_PIN); Serial.println("Point the remote and press buttons...");}void loop() { if (IrReceiver.decode()) { Serial.print("command (HEX): 0x"); Serial.println(IrReceiver.decodedIRData.command, HEX); // the part that changes per button IrReceiver.resume(); // ready for the next button }}
ממלאים את 5 הקודים, והשלט נוהג במכונית. התנועות מגיעות מ-Motors.h — רק הקלט השתנה.Fill in the 5 codes and the remote drives the car. The moves come from Motors.h — only the input changed.
/* Robotika - Course 44, Lesson 4 The IR car -- drive with a TV-style infrared remote IR = infrared light, exactly like a TV remote. It needs a clear line of sight to the receiver and goes one way only (remote -> car). The car's MOVES come from Motors.h -- we only choose WHICH move each button makes. Same car, same motor module as the RF and Bluetooth versions. 1) Run IrReadCodes.ino first and fill in your 5 codes below. 2) Upload this, point the remote at the car, and drive. Library: "IRremote" Wiring: IR receiver OUT -> D9 (car wiring: see the shared wiring map)*/#include <IRremote.h>#include "Motors.h"const int IR_PIN = 9;const int SPEED = 160; // how fast the car drives (0..255)const int HOLD_MS = 200; // keep moving this long after a press, then stop// >>> FILL THESE IN from IrReadCodes.ino (your remote's codes) <<<const uint8_t BTN_UP = 0x18;const uint8_t BTN_DOWN = 0x52;const uint8_t BTN_LEFT = 0x08;const uint8_t BTN_RIGHT = 0x5A;const uint8_t BTN_OK = 0x1C;unsigned long lastCmd = 0;void setup() { Serial.begin(9600); IrReceiver.begin(IR_PIN); beginMotors();}void loop() { if (IrReceiver.decode()) { uint8_t c = IrReceiver.decodedIRData.command; if (c == BTN_UP) drive( SPEED, SPEED); // both forward else if (c == BTN_DOWN) drive(-SPEED, -SPEED); // both reverse else if (c == BTN_LEFT) drive(-SPEED, SPEED); // spin left else if (c == BTN_RIGHT) drive( SPEED, -SPEED); // spin right else if (c == BTN_OK) stopCar(); lastCmd = millis(); IrReceiver.resume(); // ready for the next button } // no button for a moment -> stop, so the car never runs away if (millis() - lastCmd > HOLD_MS) stopCar();}
ארדואינו שני עם 4 כפתורים ששולח קוד רדיו לכל כיוון. ספרייה: rc-switch. הקודים מ-RadioProtocol.h.A second Arduino with 4 buttons that sends a radio code per direction. Library: rc-switch. Codes from RadioProtocol.h.
/* Robotika - Course 44, Lesson 4 The RF remote (runs on a SECOND Arduino Uno -- the one with the buttons) With IR the remote came ready-made. With RF we BUILD the remote too: a second Arduino with 4 buttons that sends a radio code per direction. When nothing is pressed we send CODE_STOP, so the car stops the moment you let go. RF433 = radio at 433 MHz. Unlike IR it does NOT need line of sight, it goes through walls, and it reaches much farther. Still one-way: remote -> car. The codes are NOT written here -- they live in RadioProtocol.h, the one file the remote and the car share. We just #include it. Library: "rc-switch" Wiring (this REMOTE board -- no motors here): RF transmitter (FS1000A): DATA -> D10 VCC -> 5V GND -> GND Buttons to GND (internal pull-ups): UP -> D2 DOWN -> D3 LEFT -> D4 RIGHT -> D5*/#include <RCSwitch.h> // < > = a library we installed#include "RadioProtocol.h" // " " = our own file, next to this sketchRCSwitch radio = RCSwitch();const int TX_PIN = 10;const int BTN_UP = 2, BTN_DOWN = 3, BTN_LEFT = 4, BTN_RIGHT = 5;void setup() { radio.enableTransmit(TX_PIN); pinMode(BTN_UP, INPUT_PULLUP); pinMode(BTN_DOWN, INPUT_PULLUP); pinMode(BTN_LEFT, INPUT_PULLUP); pinMode(BTN_RIGHT, INPUT_PULLUP);}void loop() { long code = CODE_STOP; // nothing pressed -> ask the car to stop if (digitalRead(BTN_UP) == LOW) code = CODE_UP; else if (digitalRead(BTN_DOWN) == LOW) code = CODE_DOWN; else if (digitalRead(BTN_LEFT) == LOW) code = CODE_LEFT; else if (digitalRead(BTN_RIGHT) == LOW) code = CODE_RIGHT; radio.send(code, 24); // send the code over the air (24 bits) delay(100); // about 10 times a second}
מקשיבה לקודי הרדיו ונוהגת. מרכיבה RadioProtocol.h ו-Motors.h. עצירת ביטחון כשהשלט נעלם.Listens for the radio codes and drives. Combines RadioProtocol.h and Motors.h. A failsafe stop if the remote drops out.
/* Robotika - Course 44, Lesson 4 The RF car (the receiver -- listens to the RF remote) The car listens for radio codes from RfRemote.ino and drives. It is built from several files the Arduino IDE compiles together: RfCar.ino <- this file: setup + loop, the "story" RadioProtocol.h <- the shared codes (the same file the remote uses) Motors.h/.cpp <- the reusable motor module (shared with IR & Bluetooth) Notice how short loop() is: the motor detail hides in Motors.cpp, and the codes are named words from RadioProtocol.h. loop() reads like a sentence. SAFETY: if no code arrives for a short while (remote off / out of range) we stopCar() -- so the car can never run away on an old command. Wheels up first. Library: "rc-switch" Wiring: RF receiver (XY-MK-5V) DATA -> D2 VCC -> 5V GND -> GND*/#include <RCSwitch.h>#include "RadioProtocol.h"#include "Motors.h"RCSwitch radio = RCSwitch();const int SPEED = 160; // how fast the car drives (0..255)const int HOLD_MS = 300; // no new code for this long -> stopunsigned long lastCode = 0;void setup() { Serial.begin(9600); beginMotors(); radio.enableReceive(0); // interrupt 0 = pin D2 = the RF receiver's DATA}void loop() { if (radio.available()) { long code = radio.getReceivedValue(); if (code == CODE_UP) drive( SPEED, SPEED); else if (code == CODE_DOWN) drive(-SPEED, -SPEED); else if (code == CODE_LEFT) drive(-SPEED, SPEED); else if (code == CODE_RIGHT) drive( SPEED, -SPEED); else if (code == CODE_STOP) stopCar(); lastCode = millis(); radio.resetAvailable(); } // failsafe: lost the remote? stop. if (millis() - lastCode > HOLD_MS) stopCar();}
מודול HC-05 + אפליקציית Dabble. הג'ויסטיק במסך נוהג. ספרייה: Dabble. אותו Motors.h שוב.An HC-05 module + the Dabble app. The on-screen GamePad drives. Library: Dabble. The same Motors.h again.
/* Robotika - Course 44, Lesson 4 The Bluetooth car -- your PHONE is the remote No separate remote board at all: an HC-05 Bluetooth module on the car talks to the free "Dabble" app, whose on-screen GamePad sends the direction. Hold an arrow to drive; let go and the car stops. Same Motors.h module again -- only the input changed, one last time. Setup: 1) Install "Dabble" on the phone (Android). 2) Library: "Dabble" (Library Manager -> search "Dabble"). 3) In the app: connect to the HC-05, then open the GamePad module. !! On the Uno, Dabble talks to the module through SoftwareSerial, NOT D0/D1. Its default pins D2/D3 are our motor pins, so we move it to D11/D12 with Dabble.begin(9600, 11, 12). D0/D1 stay free, so USB upload still works. (Android + HC-05. iPhone Dabble needs a BLE module like HM-10.) Wiring: HC-05 TXD -> D11 RXD <- D12 (via a 1k/2k divider) VCC -> 5V GND -> GND*/#define CUSTOM_SETTINGS#define INCLUDE_GAMEPAD_MODULE#include <Dabble.h>#include "Motors.h"const int SPEED = 160; // how fast the car drives (0..255)void setup() { Dabble.begin(9600, 11, 12); // HC-05 on RX = D11, TX = D12 beginMotors();}void loop() { Dabble.processInput(); // read what the phone sent 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 -> stop}
בונוס: Bluetooth דו-כיווני. על אותו קו, המכונית קוראת פקודות ומדווחת D=מרחק,M=תנועה,S=מהירות 5 פעמים בשנייה. הזרע של מרכז השליטה בשיעור הבא.Bonus: Bluetooth is two-way. On the same link the car reads commands AND reports D=distance,M=move,S=speed 5x a second. The seed of next lesson's command center.
/* Robotika - Course 44, Lesson 4 · BONUS (and the seed of Lesson 5) Bluetooth telemetry -- the car talks BACK 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 now reads your letters AND reports what it sees, five times a second, as one line of text: D=23,M=F,S=160 | | '-- S = speed (0..255) | '------- M = current move (F / B / L / R / S) '------------ D = distance in cm (999 = nothing in front) key=value pairs, comma-separated -- simple for any program (even a web page) to read. Next lesson we turn this stream into a live "command center". Drive it from any Bluetooth serial-terminal app (Android): send F B L R S to move, and 1..9 to set the speed. Watch the D=,M=,S= lines stream back. Reuses Motors.h once more. SoftwareSerial is built in -- no extra library. Wiring: HC-05 on D11/D12 (as the Dabble car), HC-SR04 Trig -> D9, Echo -> D10. New idea: millis() -- a clock that does NOT freeze the program. A delay(200) here would make the car deaf to commands for 200 ms every report.*/#include <SoftwareSerial.h>#include "Motors.h"SoftwareSerial BT(11, 12); // RX = D11 (<- HC-05 TXD), TX = D12 (-> HC-05 RXD)const int TRIG = 9, ECHO = 10;const int STOP_CM = 15; // refuse to drive forward closer than thisconst unsigned long REPORT_MS = 200; // one telemetry line every 200 ms = 5 / secint carSpeed = 160; // not const any more -- '1'..'9' change itchar moveCmd = 'S'; // the move we are currently doing (latched)int distanceCm = 999;unsigned long lastReport = 0;void setup() { BT.begin(9600); beginMotors(); pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT);}void loop() { // 1) IN: a command from the phone, over Bluetooth if (BT.available()) { char c = toupper(BT.read()); if (c == 'F' || c == 'B' || c == 'L' || c == 'R' || c == 'S') moveCmd = c; else if (c >= '1' && c <= '9') carSpeed = map(c - '0', 1, 9, 80, 255); // anything else (newlines, typos) is ignored } // 2) SENSE + SAFETY distanceCm = readDistanceCm(); if (moveCmd == 'F' && distanceCm <= STOP_CM) moveCmd = 'S'; // 3) OUT (motors): the same Motors.h module as every other car if (moveCmd == 'F') drive( carSpeed, carSpeed); else if (moveCmd == 'B') drive(-carSpeed, -carSpeed); else if (moveCmd == 'L') drive(-carSpeed, carSpeed); else if (moveCmd == 'R') drive( carSpeed, -carSpeed); else stopCar(); // 4) OUT (telemetry): report back WITHOUT freezing the program if (millis() - lastReport >= REPORT_MS) { lastReport = millis(); BT.print("D="); BT.print(distanceCm); BT.print(",M="); BT.print(moveCmd); BT.print(",S="); BT.println(carSpeed); }}int readDistanceCm() { digitalWrite(TRIG, LOW); delayMicroseconds(2); digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW); long duration = pulseIn(ECHO, HIGH, 25000); if (duration == 0) return 999; // no echo -> treat as "clear / far" return duration * 0.0343 / 2;}
השפה שהשלט והמכונית מסכימים עליה. שני סקיצות ה-RF עושות #include לקובץ הזה — מקור אמת אחד.The shared language the RF remote and car agree on. Both RF sketches #include this one file — a single source of truth.
#pragma once/* RadioProtocol.h -- the "language" the RF remote and the RF car agree on. The remote SENDS one of these numbers; the car LISTENS for the same ones. Both RF sketches do #include "RadioProtocol.h" -- so there is ONE place the codes live. Change a number here, and BOTH boards change together. Before this file we copied the numbers into both sketches by hand. If they ever drifted apart, the car would quietly ignore the remote. One shared file makes that mistake impossible.*/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;
מה אפשר לבקש מהמנועים — שלוש פקודות. שלוש המכוניות (IR/RF/BT) מרכיבות את אותו קובץ.What you can ask the motors to do — three commands. All three cars (IR/RF/BT) include this same file.
#pragma once/* Motors.h -- the MENU of the car's motors. This file says only WHAT you can ask the motors to do -- the names of the three commands. It does NOT say how they work; that lives in Motors.cpp. The IR car, the RF car and the Bluetooth car ALL #include this same file. We write the car's moves ONCE, and every remote reuses them unchanged -- only the way the command ARRIVES is different.*/void beginMotors(); // call once, in setup()void drive(int left, int right); // speed per side, -255..255 (0 = stop)void stopCar(); // cut power to both sides
ה-איך של המנועים, נכתב פעם אחת. חיווט אחיד לשלושתן: IN1 על D8 כדי לפנות את D2 למקלט ה-RF.The HOW of the motors, written once. One wiring for all three: IN1 on D8 to free D2 for the RF receiver.
/* Motors.cpp -- the KITCHEN. HOW the three commands from Motors.h work. ONE wiring, shared by all three cars (IR / RF / Bluetooth), so this module is written once and every remote's sketch includes it unchanged. It is the same L298N driver and the same moves as Lesson 3, with ONE change: IN1 sits on D8 instead of D2. Why? The RF car must receive the radio on the interrupt pin D2 -- so we keep D2 free on EVERY car and put IN1 on D8. That way the one Motors.cpp fits all three remotes. L298N ch. A (LEFT motors): ENA -> D5 IN1 -> D8 IN2 -> D3 L298N ch. B (RIGHT motors): ENB -> D6 IN3 -> D4 IN4 -> D7*/#include <Arduino.h>#include "Motors.h"const byte ENA = 5, IN1 = 8, IN2 = 3; // left side (IN1 on D8, not D2)const byte ENB = 6, IN3 = 4, IN4 = 7; // right side// Drive one side. Positive = forward, negative = reverse, 0 = stop.static void oneSide(byte en, byte a, byte b, int speed) { digitalWrite(a, speed > 0 ? HIGH : LOW); digitalWrite(b, speed < 0 ? HIGH : LOW); analogWrite(en, abs(speed));}void beginMotors() { pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT); pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT); stopCar();}void drive(int left, int right) { oneSide(ENA, IN1, IN2, left); oneSide(ENB, IN3, IN4, right);}void stopCar() { drive(0, 0);}