Robotika ● שיעור 2 — קבצי הקודLesson 2 — Code files
→ חזרה← Back ↩ למצגת השיעור↩ Lesson deck
קורס ארדואינו · קבצי קודArduino course · Code files

שיעור 2 — קבצי הקודLesson 2 — Code files

חיישנים, החלטות ותצוגה · כל קובץ בעמוד משלו, עם הקוד המלא וכפתור הורדה.Sensors, decisions & a display · one file per page, with the full code and a download button.

⬇ להוריד הכל (zip)Download all (zip)

💡 ב-Arduino IDE: פותחים את קובץ ה-.ino, וה-IDE יציע ליצור לו תיקייה באותו שם — מאשרים.💡 In the Arduino IDE: open the .ino file; the IDE offers to create a folder with the same name — accept.

1שלב 1 · קוראים חיישן אורLevel 1 · Read a light sensor

analogRead מחזיר 0..1023. מדפיסים ל-Serial Monitor (9600) ומכסים את החיישן ביד.analogRead gives 0..1023. Print it to the Serial Monitor (9600) and cover the sensor with your hand.

level1_light_read.ino ⬇ הורדהDownload 32 שורותlines
/*  Robotika – Course 44, Lesson 2  Level 1: Your first SENSE — read a light sensor into the Serial Monitor  Last lesson our loop could THINK and ACT (blink on a timer).  Today we add the piece that was missing: SENSE. We give the Arduino an eye.  The light-sensor module has 4 legs. We use three of them:    VCC -> 5V    GND -> GND    AO  -> A0        // AO = "Analog Out": a voltage that follows the light    (DO stays unconnected for now)  analogRead(A0) gives a number from 0 (dark) up to 1023 (bright).  Open: Tools > Serial Monitor, and set the baud rate to 9600.*/const int LIGHT_PIN = A0;      // the sensor's AO leg is plugged in herevoid setup() {  Serial.begin(9600);          // open a "window" from the Arduino to the computer}void loop() {  int light = analogRead(LIGHT_PIN);   // read the eye: a number 0..1023  Serial.print("Light: ");  Serial.println(light);               // print it so WE can see what the Arduino sees  delay(200);                          // 5 readings a second is plenty for our eyes}

2שלב 2 · מנורת לילה (if/else)Level 2 · Nightlight (if/else)

ההחלטה הראשונה: אם חשוך — הדלק נורה (פין 13), אחרת כבה. הסף DARK_LEVEL הוא קבוע עם שם.The first decision: if it's dark, turn the LED on (pin 13), else off. The DARK_LEVEL threshold is a named constant.

level2_nightlight.ino ⬇ הורדהDownload 39 שורותlines
/*  Robotika – Course 44, Lesson 2  Level 2: A nightlight — our first DECISION (if / else)  Same wiring as Level 1 (just the light sensor). No new parts:  we use the LED that is ALREADY on the board, pin 13.  Now the loop from last lesson is finally complete:    SENSE  -> read the light    THINK  -> IF it is dark, turn the light on; ELSE turn it off    ACT    -> drive the LED  DARK_LEVEL is a NAMED number at the top. If your room's light is  different, you change it in ONE place. Never bury a bare "magic number"  deep inside the code where no one can find it.*/const int LIGHT_PIN = A0;const int LED_PIN   = 13;      // the built-in LED on the boardconst int DARK_LEVEL = 400;    // below this = "it's dark". Tune it to your room.void setup() {  Serial.begin(9600);  pinMode(LED_PIN, OUTPUT);}void loop() {  int light = analogRead(LIGHT_PIN);  Serial.println(light);               // watch this to choose a good DARK_LEVEL  if (light < DARK_LEVEL) {    digitalWrite(LED_PIN, HIGH);       // dark  -> light ON  } else {    digitalWrite(LED_PIN, LOW);        // bright -> light OFF  }  delay(100);}

3שלב 3 · מרחק על מסך 4 ספרותLevel 3 · Distance on a 4-digit display

HC-SR04 מודד מרחק; getDistanceCm() מסתיר את הטכניקה; המסך (TM1637) מציג. ספרייה: TM1637Display.HC-SR04 measures distance; getDistanceCm() hides the technique; the TM1637 display shows it. Library: TM1637Display.

level3_sonar_display.ino ⬇ הורדהDownload 67 שורותlines
/*  Robotika – Course 44, Lesson 2  Level 3: A new sense (distance), shown on a 4-digit display  Two new parts:    1) HC-SR04 ultrasonic sensor — measures DISTANCE by timing an echo,       exactly like a bat. It does not read a voltage; it measures TIME.    2) TM1637 4-digit display — a number you can read across the room.  Library needed (Library Manager -> search "TM1637Display" by Avishay Orpaz).  CODE HYGIENE idea of the day:    Measuring the distance takes several fiddly steps. We hide them inside    their own well-named function: getDistanceCm(). Then loop() reads like    a sentence — "get the distance, show it". A short loop is an easy loop.  Wiring:    HC-SR04:  VCC -> 5V   GND -> GND   Trig -> D9   Echo -> D10    TM1637:   VCC -> 5V   GND -> GND   CLK  -> D4   DIO  -> D5*/#include <TM1637Display.h>const int TRIG_PIN = 9;const int ECHO_PIN = 10;const int CLK_PIN  = 4;const int DIO_PIN  = 5;TM1637Display display(CLK_PIN, DIO_PIN);void setup() {  Serial.begin(9600);  pinMode(TRIG_PIN, OUTPUT);  pinMode(ECHO_PIN, INPUT);  display.setBrightness(5);          // 0 = dim ... 7 = bright}void loop() {  int distance = getDistanceCm();    // one clean line; the details live below  Serial.print("Distance: ");  Serial.print(distance);  Serial.println(" cm");  display.showNumberDec(distance);   // show the number on the 4 digits  delay(200);}// Measure one distance in centimeters and hand it back.// (A function that RETURNS a value: we "call" it, and it gives us an answer.)int getDistanceCm() {  // 1) send a short 10-microsecond "ping" out of Trig  digitalWrite(TRIG_PIN, LOW);  delayMicroseconds(2);  digitalWrite(TRIG_PIN, HIGH);  delayMicroseconds(10);  digitalWrite(TRIG_PIN, LOW);  // 2) listen on Echo for how long the ping took to come back  long duration = pulseIn(ECHO_PIN, HIGH, 25000);  // give up after 25 ms (nothing near)  if (duration == 0) return 999;                   // no echo -> treat it as "far / clear"  // 3) turn that time into centimeters. Sound travels ~0.0343 cm per microsecond,  //    and the ping goes there AND back, so we divide by 2.  return duration * 0.0343 / 2;}

4שלב 4 · חיישן חניהLevel 4 · Parking sensor

הכול יחד: if/else + map() לנורת אזהרה שמהבהבת מהר יותר ככל שמתקרבים. נורה על D6.All together: if/else + map() for a warning LED that blinks faster as you approach. LED on D6.

level4_parking_sensor.ino ⬇ הורדהDownload 66 שורותlines
/*  Robotika – Course 44, Lesson 2  Level 4: A car parking sensor — everything from today, together    SENSE  -> the distance (the function from Level 3)    THINK  -> IF we are far: all clear, LED off.              ELSE we are in the warning zone: blink FASTER the closer we get.    ACT    -> the display shows the number; a warning LED blinks.  New helper: map() rescales one range onto another. Here it turns a  distance of 0..WARN_CM into a blink delay of 40..500 ms — closer = faster.  Wiring (add a warning LED to the Level 3 setup):    LED long leg (+)  -> 220 ohm resistor -> D6    LED short leg (-) -> GND*/#include <TM1637Display.h>const int TRIG_PIN = 9;const int ECHO_PIN = 10;const int CLK_PIN  = 4;const int DIO_PIN  = 5;const int LED_PIN  = 6;const int WARN_CM = 30;        // the warning zone begins at this distance (cm)TM1637Display display(CLK_PIN, DIO_PIN);void setup() {  Serial.begin(9600);  pinMode(TRIG_PIN, OUTPUT);  pinMode(ECHO_PIN, INPUT);  pinMode(LED_PIN, OUTPUT);  display.setBrightness(5);}void loop() {  int distance = getDistanceCm();  display.showNumberDec(distance);  // ---- the decision ----  if (distance > WARN_CM) {    digitalWrite(LED_PIN, LOW);                      // far away -> all clear    delay(100);  } else {    // inside the zone: blink, and the closer we are the faster it blinks    int blinkDelay = map(distance, 0, WARN_CM, 40, 500);    digitalWrite(LED_PIN, HIGH);    delay(blinkDelay);    digitalWrite(LED_PIN, LOW);    delay(blinkDelay);  }}int getDistanceCm() {  digitalWrite(TRIG_PIN, LOW);  delayMicroseconds(2);  digitalWrite(TRIG_PIN, HIGH);  delayMicroseconds(10);  digitalWrite(TRIG_PIN, LOW);  long duration = pulseIn(ECHO_PIN, HIGH, 25000);  if (duration == 0) return 999;  return duration * 0.0343 / 2;}

5בונוס · בהירות אוטומטיתBonus · Auto-brightness

חיישן האור קובע את בהירות המסך (map ל-0..7). שני חיישנים עובדים יחד.The light sensor sets the display brightness (map to 0..7). Two sensors working together.

bonus_auto_brightness.ino ⬇ הורדהDownload 50 שורותlines
/*  Robotika – Course 44, Lesson 2 · BONUS  Auto-brightness: the display dims itself in a dark room.  Two senses working together — the light sensor decides how bright the  distance display should be. map() again, this time: light -> brightness.  Wiring: the Level 3 wiring (HC-SR04 + TM1637) PLUS the light sensor:    Light module:  VCC -> 5V   GND -> GND   AO -> A0*/#include <TM1637Display.h>const int LIGHT_PIN = A0;const int TRIG_PIN  = 9;const int ECHO_PIN  = 10;const int CLK_PIN   = 4;const int DIO_PIN   = 5;TM1637Display display(CLK_PIN, DIO_PIN);void setup() {  Serial.begin(9600);  pinMode(TRIG_PIN, OUTPUT);  pinMode(ECHO_PIN, INPUT);}void loop() {  int light = analogRead(LIGHT_PIN);           // 0..1023  // turn the light reading into a display brightness level 0..7  int brightness = map(light, 0, 1023, 0, 7);  display.setBrightness(brightness);  int distance = getDistanceCm();  display.showNumberDec(distance);             // re-draw so the new brightness shows  delay(150);}int getDistanceCm() {  digitalWrite(TRIG_PIN, LOW);  delayMicroseconds(2);  digitalWrite(TRIG_PIN, HIGH);  delayMicroseconds(10);  digitalWrite(TRIG_PIN, LOW);  long duration = pulseIn(ECHO_PIN, HIGH, 25000);  if (duration == 0) return 999;  return duration * 0.0343 / 2;}

6בונוס · שלושה אזורי אור (else if)Bonus · Three light zones (else if)

if … else if … else: בהיר / עמום / חשוך. שרשרת החלטות — הראשון שמתאים מנצח.if … else if … else: bright / dim / dark. A chain of decisions — the first match wins.

bonus_light_zones.ino ⬇ הורדהDownload 37 שורותlines
/*  Robotika – Course 44, Lesson 2 · BONUS  Three zones with if / else if / else — giving names to light levels.  One sensor, three possible outcomes. When you have more than two cases,  you chain them: if ... else if ... else. The FIRST match wins, so order  the tests from the brightest level down.  Wiring: just the light sensor (AO -> A0), like Level 1.  Cover the sensor with your hand and watch the word change in the monitor.*/const int LIGHT_PIN = A0;const int BRIGHT_LEVEL = 700;   // above this  = bright daylightconst int DIM_LEVEL    = 300;   // between DIM and BRIGHT = a dim roomvoid setup() {  Serial.begin(9600);}void loop() {  int light = analogRead(LIGHT_PIN);  Serial.print(light);  Serial.print("  ->  ");  if (light > BRIGHT_LEVEL) {    Serial.println("BRIGHT");  } else if (light > DIM_LEVEL) {    Serial.println("DIM");  } else {    Serial.println("DARK");  }  delay(300);}