קורס רובוטיקה ובינה מלאכותית : A106-06 רובוטיקה
חלק א : TOPS
מה זה TOPS ואיך מודדים ביצועי מעבדי AI?
TOPS – Tera Operations Per Second הוא מדד לכמות הפעולות החישוביות שמעבד מסוגל לבצע בשנייה.
כלומר, 1 TOPS = טריליון פעולות בשנייה.
1. יחידות המדידה
| מדד | משמעות | פעולות בשנייה |
|---|---|---|
| KOPS | Kilo Operations | 1,000 |
| MOPS | Mega Operations | מיליון |
| GOPS | Giga Operations | מיליארד |
| TOPS | Tera Operations | טריליון |
| POPS | Peta Operations | אלף טריליון |
2. מה נחשב לפעולה?
במעבדי AI הפעולות הנפוצות הן:
-
ADD – חיבור מספרים.
-
MUL – כפל מספרים.
-
MAC – Multiply-Accumulate, כפל וצבירה.
לדוגמה:
בדרך כלל סופרים פעולת MAC אחת כשתי פעולות: כפל וחיבור.
מעבד שמבצע 3 טריליון פעולות MAC בשנייה יכול להיות מדורג כ־6 TOPS.
3. ההבדל בין TOPS ל־FLOPS
| מדד | מה מודדים | שימוש עיקרי |
|---|---|---|
| TOPS | פעולות לשנייה | AI Inference |
| FLOPS | פעולות Floating Point לשנייה | מדע, GPU, AI Training |
| FPS | תמונות או פריימים בשנייה | עיבוד וידאו ו־YOLO |
| Latency | זמן לביצוע פעולה | מהירות תגובה |
| Memory Bandwidth | העברת נתונים בשנייה | הזנת המעבד בנתונים |
4. מדוע חשוב לציין INT8, FP16 או FP32?
אותו מעבד יכול לספק ביצועים שונים בהתאם לדיוק המספרי.
| פורמט | גודל נתון | משמעות |
|---|---|---|
| INT8 | 8 ביט | חישוב במספרים שלמים, נפוץ ב־Inference |
| INT16 | 16 ביט | מספרים שלמים בטווח רחב יותר |
| FP16 | 16 ביט | Floating Point בדיוק מופחת |
| FP32 | 32 ביט | Floating Point בדיוק גבוה יותר |
לדוגמה, מעבד עשוי לספק:
-
INT8: 12 TOPS
-
FP16: 6 TFLOPS
-
FP32: 3 TFLOPS
המספרים להמחשה בלבד.
5. דוגמה מעשית – מצלמה עם YOLO
נניח שמודל YOLO דורש 10 מיליארד פעולות לעיבוד תמונה אחת.
מעבד עם 6 TOPS:
FPS = (6000 GOPS) / (10 GOP/frame) = 600 FPS
כלומר, תקרה תאורטית של 600 תמונות בשנייה.
בפועל הביצועים יהיו נמוכים יותר בשל העברת נתונים, זיכרון, פעולות שאינן מואצות וניצולת המעבד.
המסקנה: TOPS מודד יכולת חישוב מרבית, אך כדי לבחור מעבד AI לרובוט או לרחפן חשוב לבדוק גם FPS בפועל, צריכת חשמל (W), זיכרון ו־Latency.
כאשר רושמים פורמט עבור YOLO עבור בדיקת Performance Benchmark נוסיף פרמטרים הבאים (הסבר לכל פרמטרים בהמשך ההרצאה )
BENCHMARK_RUNS = 20
, YOLO model, Model storage format, Requested precision, Actual weight precision, Actual network input precision, Quantization, Original image pixel format, CPU, CPU logical cores, GPU, Execution device, GPU compute capability, System RAM total, System RAM used by process, GPU VRAM total, GPU PyTorch peak allocation, Input image, Original image resolution, YOLO input resolution, Model parameters, Estimated GFLOPs / image, Preprocessing, Inference, Postprocessing, Pipeline latency, Python API latency, Pipeline FPS estimate, Python API FPS estimate, Effective TOPS equivalent, Benchmark runs, Detected objects
תרגיל לדוגמא :
TOPS – YOLOv8 – Google Colab AI Performance Benchmark
- נתונה התמונה

אם נבדוק את פלט של ההרצה (לאחר ההרצה ב COLAB)
בכל הרצה נמדדים:
-
Inference Time – זמן חישוב המודל.
-
Preprocessing – זמן הכנת התמונה.
-
Postprocessing – זמן עיבוד התוצאות.
-
FPS – מחושב לפי זמני העיבוד.
-
Effective TOPS – מחושב לפי GFLOPs וזמן ה־Inference.
WARMUP_RUNS = 3 – שלוש ההרצות חימום אינן נכללות בחישוב הממוצע.
| Parameter | Measured value | Description / purpose |
|---|---|---|
| Website | ROBOTRONIX.CO.IL | Program author / educational project |
| YOLO model | yolov8n.pt | Pretrained YOLOv8 model used for object detection |
| Model storage format | PyTorch checkpoint (.pt) | Format of the saved model file |
| Requested precision | FP32 | Precision requested by the user |
| Actual weight precision | FP32 | Observed floating/integer format of model weights |
| Actual network input precision | FP32 | Observed tensor format entering the neural network |
| Quantization | No INT8 / INT16 weight quantization | Whether integer-quantized weights were observed |
| Original image pixel format | uint8 | Raw decoded image pixel type; not network precision |
| CPU | Intel(R) Xeon(R) CPU @ 2.20GHz | Host CPU model provided by Google Colab |
| CPU logical cores | 2 | Logical CPU execution cores available |
| GPU | Not available | GPU model used for neural-network computation |
| Execution device | CPU | Processor selected for inference |
| GPU compute capability | N/A | NVIDIA GPU architecture capability, if available |
| System RAM total | 12.67 GiB | Total virtual-machine system memory |
| System RAM used by process | 910.3 MiB | Current resident memory used by Python |
| GPU VRAM total | N/A | Total physical GPU memory |
| GPU PyTorch peak allocation | N/A | Peak live GPU allocations tracked by PyTorch |
| Input image | ChatGPT-Image-Feb-18-2026-07_44_50-PM-400×600 (1).png | Image uploaded from the local computer |
| Original image resolution | 400 x 600 | Uploaded image width and height in pixels |
| YOLO input resolution | 640 x 640 | Fixed network input resolution used for profiling |
| Model parameters | 3,157,200 | Number of learned neural-network parameters |
| Estimated GFLOPs / image | 8.855 | Estimated floating-point operations for one image in billions |
| Preprocessing | 3.207 ms | Image resizing, formatting, and conversion time |
| Inference | 191.011 ms | Neural-network computation time per image |
| Postprocessing | 1.497 ms | Detection filtering and output processing time |
| Pipeline latency | 195.715 ms | Sum of measured YOLO processing stages |
| Python API latency | 196.275 ms | Full measured model.predict() call duration |
| Pipeline FPS estimate | 5.11 | Images/s estimated from pipeline latency |
| Python API FPS estimate | 5.09 | Serial predictions/s estimated from total call time |
| Effective TOPS equivalent | 0.0464 | FLOPs-based compute-rate estimate; NOT peak GPU TOPS |
| Benchmark runs | 20 | Timed predictions used to calculate mean measurements |
| Detected objects | 29 | Number of objects detected in the uploaded image |
הרצת התרגיל
קוד קישור (שנה למודל l ומה ההבדלים )
https://colab.research.google.com/drive/1PdTWR5x7S10Z1ul9IeoEeYTZS_plidP0?usp=sharing
הרצת התרגיל
|
1 |
%pip -q install -U ultralytics ultralytics-thop psutil |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 |
""" ROBOTRONIX.CO.IL YOLOv8 Image Detection and AI Performance Benchmark Purpose: Upload one image from a local PC to Google Colab, detect objects with YOLOv8, identify the CPU/GPU and the model's observed numeric precision, and measure inference latency, preprocessing, postprocessing, memory, FPS, and the model's estimated FLOPs-based compute rate. Notes: This benchmark uses the same uploaded image repeatedly for timing. Effective TOPS-equivalent is NOT the advertised peak TOPS of the GPU. Standard PyTorch YOLOv8 .pt inference uses FP32 or FP16 here, not INT16. """ import os import time from collections import Counter import cv2 import matplotlib.pyplot as plt import numpy as np import pandas as pd import psutil import torch from google.colab import files from ultralytics import YOLO from ultralytics.cfg import DEFAULT_CFG_DICT from ultralytics.utils.torch_utils import get_flops # ====================== USER CONFIGURATION ====================== # YOLOv8 checkpoint name: n=nano, s=small, m=medium, l=large, x=extra-large. MODEL_NAME = "yolov8n.pt" # Neural-network input size in pixels: 640 means a fixed 640 x 640 tensor. IMAGE_SIZE = 640 # Requested precision: False=FP32; True=FP16 when an NVIDIA CUDA GPU is available. USE_FP16 = False # Minimum detection confidence accepted by YOLO, between 0.0 and 1.0. CONFIDENCE = 0.25 # Number of preliminary runs excluded from performance measurements. WARMUP_RUNS = 3 # Number of timed predictions used to calculate average performance. BENCHMARK_RUNS = 20 # ====================== DETECT HARDWARE ========================= # Detect whether PyTorch can execute the model on a CUDA GPU. HAS_GPU = torch.cuda.is_available() # Select the first CUDA GPU when available; otherwise use the CPU. DEVICE = "0" if HAS_GPU else "cpu" # Use FP16 only when requested and CUDA is available; CPU runs FP32. ACTUAL_FP16_REQUEST = USE_FP16 and HAS_GPU # Read the CPU model name from the Colab Linux virtual machine. cpu_name = "Unknown CPU" try: with open("/proc/cpuinfo", encoding="utf-8") as cpu_file: cpu_name = next( line.split(":", 1)[1].strip() for line in cpu_file if line.startswith("model name") ) except (OSError, StopIteration): pass # Read the total system memory and the number of logical CPU cores. ram_total_gib = psutil.virtual_memory().total / 2**30 cpu_cores = psutil.cpu_count(logical=True) # Read the GPU name, VRAM capacity, and CUDA compute capability if available. gpu_name = torch.cuda.get_device_name(0) if HAS_GPU else "Not available" gpu_total_gib = ( torch.cuda.get_device_properties(0).total_memory / 2**30 if HAS_GPU else None ) gpu_capability = ( ".".join(map(str, torch.cuda.get_device_capability(0))) if HAS_GPU else "N/A" ) print("=" * 72) print("ROBOTRONIX.CO.IL | YOLOv8 IMAGE DETECTION & AI PERFORMANCE BENCHMARK") print("=" * 72) print(f"CPU: {cpu_name} | Logical cores: {cpu_cores}") print(f"System RAM: {ram_total_gib:.2f} GiB") print(f"GPU: {gpu_name} | VRAM: {gpu_total_gib:.2f} GiB" if HAS_GPU else "GPU: None; running on CPU") # ====================== UPLOAD AN IMAGE ========================= # Open the Google Colab file selector and upload one image from the local PC. print("\nSelect one image from your PC:") uploaded_files = files.upload() if not uploaded_files: raise ValueError("No image was uploaded.") # Select the first uploaded filename, then decode it with OpenCV. image_filename = next(iter(uploaded_files)) image_bgr = cv2.imread(image_filename) if image_bgr is None: raise ValueError("The selected file is not a readable image.") # Record original image dimensions; OpenCV images normally contain uint8 pixels. original_height, original_width = image_bgr.shape[:2] # ====================== LOAD AND PROFILE YOLOv8 ================ # Load pretrained YOLOv8 weights, downloading them automatically if necessary. model = YOLO(MODEL_NAME) # Count all learned parameters in the original PyTorch neural network. model_parameters = sum(parameter.numel() for parameter in model.model.parameters()) # Estimate computational cost at IMAGE_SIZE; two floating-point ops per MAC. # This is a model-profile estimate, NOT a hardware TOPS measurement. gflops_per_image = get_flops(model.model, imgsz=IMAGE_SIZE) # Use the precision argument supported by the installed Ultralytics version. # New versions use 'quantize=16/32'; older ones use 'half=True/False'. precision_argument = ( {"quantize": 16 if ACTUAL_FP16_REQUEST else 32} if "quantize" in DEFAULT_CFG_DICT else {"half": ACTUAL_FP16_REQUEST} ) # Configure consistent input dimensions, device, confidence, and precision. prediction_arguments = dict( source=image_bgr, imgsz=IMAGE_SIZE, rect=False, device=DEVICE, conf=CONFIDENCE, verbose=False, save=False, **precision_argument, ) # Run once to initialize the Ultralytics inference backend and its buffers. result = model.predict(**prediction_arguments)[0] # Obtain the actual backend module executing the neural-network forward pass. backend = model.predictor.model backend_module = getattr(backend, "model", model.model) # Collect the real dtype of input tensors entering the neural network. observed_input_dtypes = set() def observe_input_precision(module, inputs): """Capture the data type of the input tensor passed to the YOLO network.""" if inputs and isinstance(inputs[0], torch.Tensor): observed_input_dtypes.add(inputs[0].dtype) # Install a temporary hook that observes input precision during inference. input_precision_hook = backend_module.register_forward_pre_hook(observe_input_precision) # ====================== WARM-UP ================================ # Perform warm-up runs so initial setup overhead does not distort the averages. for _ in range(WARMUP_RUNS): result = model.predict(**prediction_arguments)[0] # Synchronize CUDA operations before resetting peak PyTorch VRAM measurements. if HAS_GPU: torch.cuda.synchronize() torch.cuda.reset_peak_memory_stats() # ====================== MEASURE PERFORMANCE ===================== # Store stage timings reported by YOLO and end-to-end Python call durations. stage_speeds = [] wall_time_ms_samples = [] # Repeatedly process the same image and measure latency in milliseconds. for _ in range(BENCHMARK_RUNS): if HAS_GPU: torch.cuda.synchronize() start_time = time.perf_counter() result = model.predict(**prediction_arguments)[0] if HAS_GPU: torch.cuda.synchronize() wall_time_ms_samples.append((time.perf_counter() - start_time) * 1000) stage_speeds.append(result.speed.copy()) # Remove the instrumentation hook after collecting the input tensor dtype. input_precision_hook.remove() # Compute mean image preprocessing latency in milliseconds. preprocess_ms = float(np.mean([speed["preprocess"] for speed in stage_speeds])) # Compute mean neural-network inference latency in milliseconds. inference_ms = float(np.mean([speed["inference"] for speed in stage_speeds])) # Compute mean postprocessing latency in milliseconds, including detection filtering. postprocess_ms = float(np.mean([speed["postprocess"] for speed in stage_speeds])) # Sum Ultralytics stage durations to estimate overall pipeline latency. pipeline_ms = preprocess_ms + inference_ms + postprocess_ms # Average the full Python API call duration, including additional Python overhead. python_call_ms = float(np.mean(wall_time_ms_samples)) # Estimate throughput from the measured average per-image pipeline latency. pipeline_fps = 1000.0 / pipeline_ms if pipeline_ms > 0 else float("nan") # Estimate serial Python prediction calls per second for this repeated image. python_fps = 1000.0 / python_call_ms if python_call_ms > 0 else float("nan") # Estimate FLOPs executed per second; GFLOPs/ms is numerically TFLOPS (TOPS-equivalent). # This does not reveal the GPU's peak hardware TOPS or actual instruction count. effective_tops_equivalent = ( gflops_per_image / inference_ms if gflops_per_image > 0 and inference_ms > 0 else float("nan") ) # ====================== VERIFY NUMERIC PRECISION ================ # Read actual weight dtype in the backend used for execution, not just a setting. try: weight_dtype = next(backend_module.parameters()).dtype except (AttributeError, StopIteration): weight_dtype = next(model.model.parameters()).dtype # Convert technical PyTorch data types into familiar precision labels. dtype_names = { torch.float32: "FP32", torch.float16: "FP16", torch.bfloat16: "BF16", torch.int8: "INT8", torch.int16: "INT16", } # Format the actual weight precision and observed network-input precision. weight_precision = dtype_names.get(weight_dtype, str(weight_dtype)) network_input_precision = ( ", ".join(sorted(dtype_names.get(dtype, str(dtype)) for dtype in observed_input_dtypes)) if observed_input_dtypes else "Not observed" ) # Identify the model storage format separately from its execution precision. model_storage_format = ( "PyTorch checkpoint (.pt)" if os.path.splitext(MODEL_NAME)[1].lower() == ".pt" else os.path.splitext(MODEL_NAME)[1].lower() ) # Describe whether the backend weights use 8-bit or 16-bit integer quantization. quantization_status = ( "INT8" if weight_dtype == torch.int8 else "INT16" if weight_dtype == torch.int16 else "No INT8 / INT16 weight quantization" ) # ====================== MEASURE MEMORY ========================== # Read the resident memory currently used by this Python process. process_ram_mib = psutil.Process().memory_info().rss / 2**20 # Read peak GPU memory allocated by PyTorch during timed inference runs. peak_gpu_mib = torch.cuda.max_memory_allocated() / 2**20 if HAS_GPU else None # ====================== BUILD EXPLAINED REPORT =================== # Store each metric as: English parameter name, measured value, and its role. report_rows = [ ("Website", "ROBOTRONIX.CO.IL", "Program author / educational project"), ("YOLO model", MODEL_NAME, "Pretrained YOLOv8 model used for object detection"), ("Model storage format", model_storage_format, "Format of the saved model file"), ("Requested precision", "FP16" if USE_FP16 else "FP32", "Precision requested by the user"), ("Actual weight precision", weight_precision, "Observed floating/integer format of model weights"), ("Actual network input precision", network_input_precision, "Observed tensor format entering the neural network"), ("Quantization", quantization_status, "Whether integer-quantized weights were observed"), ("Original image pixel format", str(image_bgr.dtype), "Raw decoded image pixel type; not network precision"), ("CPU", cpu_name, "Host CPU model provided by Google Colab"), ("CPU logical cores", str(cpu_cores), "Logical CPU execution cores available"), ("GPU", gpu_name, "GPU model used for neural-network computation"), ("Execution device", "CUDA GPU" if HAS_GPU else "CPU", "Processor selected for inference"), ("GPU compute capability", gpu_capability, "NVIDIA GPU architecture capability, if available"), ("System RAM total", f"{ram_total_gib:.2f} GiB", "Total virtual-machine system memory"), ("System RAM used by process", f"{process_ram_mib:.1f} MiB", "Current resident memory used by Python"), ("GPU VRAM total", f"{gpu_total_gib:.2f} GiB" if HAS_GPU else "N/A", "Total physical GPU memory"), ("GPU PyTorch peak allocation", f"{peak_gpu_mib:.1f} MiB" if HAS_GPU else "N/A", "Peak live GPU allocations tracked by PyTorch"), ("Input image", image_filename, "Image uploaded from the local computer"), ("Original image resolution", f"{original_width} x {original_height}", "Uploaded image width and height in pixels"), ("YOLO input resolution", f"{IMAGE_SIZE} x {IMAGE_SIZE}", "Fixed network input resolution used for profiling"), ("Model parameters", f"{model_parameters:,}", "Number of learned neural-network parameters"), ("Estimated GFLOPs / image", f"{gflops_per_image:.3f}" if gflops_per_image > 0 else "Unavailable", "Estimated floating-point operations for one image in billions"), ("Preprocessing", f"{preprocess_ms:.3f} ms", "Image resizing, formatting, and conversion time"), ("Inference", f"{inference_ms:.3f} ms", "Neural-network computation time per image"), ("Postprocessing", f"{postprocess_ms:.3f} ms", "Detection filtering and output processing time"), ("Pipeline latency", f"{pipeline_ms:.3f} ms", "Sum of measured YOLO processing stages"), ("Python API latency", f"{python_call_ms:.3f} ms", "Full measured model.predict() call duration"), ("Pipeline FPS estimate", f"{pipeline_fps:.2f}", "Images/s estimated from pipeline latency"), ("Python API FPS estimate", f"{python_fps:.2f}", "Serial predictions/s estimated from total call time"), ("Effective TOPS equivalent", f"{effective_tops_equivalent:.4f}" if np.isfinite(effective_tops_equivalent) else "Unavailable", "FLOPs-based compute-rate estimate; NOT peak GPU TOPS"), ("Benchmark runs", str(BENCHMARK_RUNS), "Timed predictions used to calculate mean measurements"), ("Detected objects", str(len(result.boxes)), "Number of objects detected in the uploaded image"), ] # Convert the report to a table with an English explanation for each parameter. report = pd.DataFrame(report_rows, columns=["Parameter", "Measured value", "Description / purpose"]) # Print the complete benchmark report in the Colab output window. print("\nROBOTRONIX.CO.IL | YOLOv8 BENCHMARK REPORT") print(report.to_string(index=False)) # Save report results to a CSV file for future analysis or comparison. report.to_csv("ROBOTRONIX_YOLOv8_Benchmark_Report.csv", index=False) # Count objects by predicted class name. class_counts = Counter(result.names[int(class_id)] for class_id in result.boxes.cls.tolist()) print("\nDETECTED CLASSES:", dict(class_counts)) # ====================== DISPLAY RESULT IMAGE ==================== # Render bounding boxes and class labels on top of the uploaded image. annotated_image_rgb = cv2.cvtColor(result.plot(), cv2.COLOR_BGR2RGB) # Display the result image with inference precision and timing in the title. plt.figure(figsize=(12, 8)) plt.imshow(annotated_image_rgb) plt.title( f"ROBOTRONIX.CO.IL | YOLOv8 | {weight_precision} | " f"Inference {inference_ms:.2f} ms | {len(result.boxes)} objects" ) plt.axis("off") plt.show() # ====================== INTERPRETATION NOTES ===================== # Explain why raw uint8 images must not be confused with INT8 network inference. print("\nIMPORTANT MEASUREMENT NOTES") print("1. Original image uint8 pixels DO NOT imply INT8 neural-network inference.") print("2. Observed weight/input dtypes do not prove the precision of every GPU kernel (e.g., TF32).") print("3. GFLOPs/image is an estimated model operation count (typically 2 FLOPs/MAC).") print("4. Effective TOPS equivalent = GFLOPs/image / inference time (ms).") print("5. This FLOPs-based rate is NOT advertised GPU peak TOPS, especially not INT8 TOPS.") print("6. FPS is estimated from repeated predictions of one image, not from streaming video.") print("7. Report saved as ROBOTRONIX_YOLOv8_Benchmark_Report.csv") |
חלק ב : לימוד UART
-
פתח את הפרויקט ב־Wokwi.
-
לחץ על Library Manager.
-
לחץ על + וחפש
Servo. -
בחר בספריית Servo והוסף אותה לפרויקט.
-
הפעל שוב את הסימולציה.
https://wokwi.com/projects/481031961164571649

חלק ג : תרגול יצירת קוד בעזרת CHATGPT
תרגיל 1 – תרגיל כיתה – בקרת שער חשמלי באמצעות Arduino UNO

-
פתח את הפרויקט ב־Wokwi.
-
לחץ על Library Manager.
-
לחץ על + וחפש
Servo. -
בחר בספריית Servo והוסף אותה לפרויקט.
-
הפעל שוב את הסימולציה.
https://wokwi.com/projects/481029488355898369

תרגיל כיתה – בקרת שער חשמלי באמצעות Arduino UNO
פיתוח מערכת לבקרת שער חשמלי באמצעות שני לחצנים, מנוע Servo ונורית LED בסביבת Wokwi.
-
כפתור ירוק (D3): לחיצה תפעיל הבהוב LED למשך 2 שניות, ולאחר מכן השער ייפתח בהדרגה מ־0° ל־90°.
-
בזמן פתיחת השער: ה־LED ימשיך להבהב עד לפתיחה מלאה.
-
כפתור אדום (D2): לחיצה תפעיל הבהוב LED למשך 23 שניות לפני תחילת סגירת השער.
-
בזמן סגירת השער: ה־LED ימשיך להבהב עד לסגירה מלאה מ־90° ל־0°.
-
מצב שער סגור: LED דולק קבוע.
-
מצב שער פתוח: LED כבוי.
-
Serial Monitor: הצגת מצבי השער:
OPENING,OPEN,CLOSING,CLOSED.
תרגיל 2 – בקרת שער חשמלי עם מסך OLED באמצעות Arduino UNO
פיתוח מערכת לבקרת שער חשמלי באמצעות Arduino UNO, שני לחצנים, מנוע Servo, נורית LED ומסך OLED להצגת מצב השער בזמן אמת בסביבת Wokwi.
שלב 1 – רכיבי המערכת
יש להוסיף למעגל ב־Wokwi את הרכיבים הבאים:
-
Arduino UNO – בקר ראשי.
-
Push Button אדום – סגירת שער.
-
Push Button ירוק – פתיחת שער.
-
Servo Motor – הנעת השער.
-
LED אדום – נורית אזהרה.
-
נגד 220Ω – להגבלת הזרם ל־LED.
-
OLED SSD1306 128×64 I2C – מסך להצגת מצב השער.

שלב 2 – חיבור הרכיבים
| רכיב | פין Arduino UNO |
|---|---|
| לחצן אדום | D2 ו־GND |
| לחצן ירוק | D3 ו־GND |
| LED אדום | D8 דרך נגד 220Ω |
| Servo Signal | D9 |
| Servo VCC | 5V |
| Servo GND | GND |
| OLED VCC | 5V |
| OLED GND | GND |
| OLED SDA | A4 |
| OLED SCL | A5 |
יש להגדיר את שני הלחצנים כ־INPUT_PULLUP. רגל ה־Cathode של ה־LED מתחברת ל־GND.
שלב 3 – התקנת ספריות (Libraries)
בסביבת Wokwi יש לפתוח את Library Manager, לחפש ולהוסיף את הספריות:
| ספרייה | תפקיד |
|---|---|
| Adafruit SSD1306 | דרייבר למסך OLED |
| Adafruit GFX Library | הצגת טקסט וגרפיקה |
| Wire | תקשורת I2C, מובנית בסביבת Arduino |
| Servo | שליטה במנוע Servo, מובנית בסביבת Arduino |
יש להגדיר את המסך ברזולוציה 128×64 ובכתובת I2C מסוג 0x3C.
אין צורך להתקין דרייבר USB למסך בסביבת Wokwi. הספריות הן אלה שמאפשרות לתוכנה לשלוט בו.
שלב 4 – דרישות התוכנה
-
מצב התחלתי: השער סגור בזווית 0°, וה־LED דולק.
-
כפתור ירוק: לחיצה תפעיל הבהוב LED למשך 2 שניות לפני פתיחת השער.
-
פתיחת השער: מנוע Servo ינוע בהדרגה מ־0° ל־90°, וה־LED ימשיך להבהב.
-
שער פתוח: מנוע Servo בזווית 90°, וה־LED כבוי.
-
כפתור אדום: לחיצה תפעיל הבהוב LED למשך 23 שניות לפני סגירת השער.
-
סגירת השער: מנוע Servo ינוע בהדרגה מ־90° ל־0°, וה־LED ימשיך להבהב.
-
שער סגור: ה־LED יידלק באופן קבוע.
- יש להציג את מצב השער גם ב־Serial Monitor.
9. הוסף פיקוד לסגירה פתיחה של השער ב UART
שלב 5 – הצגת מידע במסך OLED
יש לתכנת את המסך להציג את מצב השער באנגלית.
| מצב המערכת | הודעה במסך |
|---|---|
| שער סגור | GATE CLOSED |
| המתנה לפתיחה | OPEN IN 2 SEC |
| שער נפתח | GATE OPENING |
| שער פתוח | GATE OPEN |
| המתנה לסגירה | CLOSE IN 23 SEC |
| שער נסגר | GATE CLOSING |
שלב 6 – משימת אתגר
הוסיפו למסך OLED את האפשרויות הבאות:
-
הצגת זווית מנוע Servo בזמן אמת, בין 0° ל־90°.
-
הצגת ספירה לאחור לפני פתיחת השער ולפני סגירתו.
-
הצגת אחוז פתיחת השער, בין 0% ל־100%.
-
אפשרות לעצירת השער באמצע התנועה ולשינוי כיוון באמצעות הלחצנים.
תוצאה נדרשת: מערכת שער חשמלי מלאה בסביבת Wokwi, הכוללת חיווי LED, שליטה במנוע Servo והצגת מצב השער במסך OLED בזמן אמת
חלק ג: התקנה של ARDUINO