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

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

זרוע רובוטית: סרוו ובקרה · כל קובץ בעמוד משלו, עם הקוד המלא וכפתור הורדה.Robotic arm: servos & control · 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 · סרוו אחד — SweepLevel 1 · One servo — Sweep

attach + write. 0→180 וחזרה. בודקים חיווט וכוח לפני שבונים.attach + write. 0→180 and back. Check wiring and power before building.

level1_servo_sweep.ino ⬇ הורדהDownload 30 שורותlines
/*  Lesson 6 - Level 1: one servo, the classic "Sweep".  The servo slowly turns 0 -> 180 degrees and back, forever.  Run this first: it proves your wiring and power are good  BEFORE you build anything mechanical.  Wiring (only the SIGNAL wire goes to the Arduino):    Signal (orange/yellow) -> D9    V+     (red)           -> external 5-6V servo rail  (NOT the Uno's 5V)    GND    (brown/black)   -> common ground (shared with the Arduino)*/#include <Servo.h>Servo joint;                   // a Servo object controls one servoconst int SERVO_PIN = 9;void setup() {  joint.attach(SERVO_PIN);     // tell the library which pin the signal is on}void loop() {  for (int a = 0; a <= 180; a++) {   // 0 -> 180 degrees    joint.write(a);                  // go to angle a    delay(15);                       // let it move a little before the next step  }  for (int a = 180; a >= 0; a--) {   // 180 -> 0 degrees    joint.write(a);    delay(15);  }}

2עזר בנייה · איפוס כל הסרוו ל-90°Build helper · Center all servos to 90°

מריצים לפני ההרכבה כדי שכל מפרק יתחיל ב"אמצע" ויקבל טווח מלא.Run before assembly so every joint starts in the "middle" and gets full range.

level1_center_all.ino ⬇ הורדהDownload 24 שורותlines
/*  Lesson 6 - Build helper: center every servo at 90 degrees.  Run this BEFORE you attach the horns and brackets. With each servo  parked at its middle, every joint gets the full range once assembled.  Power the servos from the external 5-6V rail, never from USB.  Joints / pins:  0=base D3   1=shoulder D5   2=elbow D6   3=gripper D9*/#include <Servo.h>const int PINS[] = {3, 5, 6, 9};const int N = 4;Servo servos[N];void setup() {  for (int i = 0; i < N; i++) {    servos[i].attach(PINS[i]);    servos[i].write(90);       // middle of a 0-180 servo  }}void loop() {  // nothing - just hold every joint at 90}

3שלב 2 · מקלידים זווית ב-SerialLevel 2 · Type an angle in Serial

Serial Monitor (9600): מקלידים 0–180, הסרוו הולך לשם. constrain שומר על הטווח.Serial Monitor (9600): type 0–180 and the servo goes there. constrain keeps it in range.

level2_servo_serial.ino ⬇ הורדהDownload 26 שורותlines
/*  Lesson 6 - Level 2: type an angle, the servo goes there.  Open the Serial Monitor (9600 baud), type a number 0-180, press Enter.  This is the bridge from "it moves on its own" to "I am in control".*/#include <Servo.h>Servo joint;const int SERVO_PIN = 9;void setup() {  joint.attach(SERVO_PIN);  joint.write(90);  Serial.begin(9600);  Serial.println("Type an angle 0-180 and press Enter:");}void loop() {  if (Serial.available()) {    int angle = Serial.parseInt();      // read the number you typed    angle = constrain(angle, 0, 180);   // keep it inside the legal range    joint.write(angle);    Serial.print("-> ");    Serial.println(angle);  }}

4שלב 3 · שליטה בכל מפרקLevel 3 · Control each joint

4 סרוו. פקודה "<מפרק> <זווית>", למשל 1 120. שליטה ידנית מלאה בזרוע.4 servos. Command "<joint> <angle>", e.g. 1 120. Full manual control of the arm.

level3_arm_manual.ino ⬇ הורדהDownload 42 שורותlines
/*  Lesson 6 - Level 3: control each joint of the arm by hand.  Four servos, one Serial command per move:  "<joint> <angle>"  Examples:   0 90    -> base to 90              2 40    -> elbow to 40  Joints:     0 = base   1 = shoulder   2 = elbow   3 = gripper  Open the Serial Monitor (9600 baud).  Power the servos from the external 5-6V rail. Share a common ground  with the Arduino. Signal pins only go to the Arduino.*/#include <Servo.h>const int N = 4;const int PINS[N]  = {3, 5, 6, 9};       // base, shoulder, elbow, gripperconst int START[N] = {90, 90, 90, 90};   // a safe middle poseServo servos[N];int pos[N];void setup() {  for (int i = 0; i < N; i++) {    servos[i].attach(PINS[i]);    pos[i] = START[i];    servos[i].write(pos[i]);  }  Serial.begin(9600);  Serial.println("Command:  <joint 0-3> <angle 0-180>   e.g.  1 120");}void loop() {  if (Serial.available()) {    int joint = Serial.parseInt();    int angle = Serial.parseInt();    if (joint >= 0 && joint < N) {      angle = constrain(angle, 0, 180);      pos[joint] = angle;      servos[joint].write(angle);      Serial.print("joint "); Serial.print(joint);      Serial.print(" -> ");   Serial.println(angle);    }  }}

5שלב 4 · תנועה חלקהLevel 4 · Smooth motion

moveTo שמתקדם מעלה-מעלה עם delay קטן — מגן על הגלגלים ונראה חלק.moveTo that steps a degree at a time with a small delay — protects the gears and looks smooth.

level4_smooth_move.ino ⬇ הורדהDownload 35 שורותlines
/*  Lesson 6 - Level 4: smooth motion.  write(angle) tells the servo to go there as fast as it can - that jump  is hard on the gears and looks jerky. Instead we step the angle a little  at a time, with a short delay between steps. This "glides".  This sketch moves one joint smoothly between two angles, back and forth.*/#include <Servo.h>Servo joint;const int SERVO_PIN = 9;int current = 90;// move to a target one degree at a time (smaller stepDelay = faster)void moveTo(int target, int stepDelay) {  target = constrain(target, 0, 180);  while (current != target) {    current += (target > current) ? 1 : -1;    joint.write(current);    delay(stepDelay);  }}void setup() {  joint.attach(SERVO_PIN);  joint.write(current);}void loop() {  moveTo(150, 12);   // glide up  delay(500);  moveTo(30, 12);    // glide down  delay(500);}

6שלב 5 · הקלטה והשמעה (הרם-והנח)Level 5 · Record & replay (pick & place)

מערך תנוחות {base,shoulder,elbow,gripper}. הזרוע עוברת ביניהן בחלקות בלולאה.An array of poses {base,shoulder,elbow,gripper}. The arm glides through them in a loop.

level5_record_play.ino ⬇ הורדהDownload 61 שורותlines
/*  Lesson 6 - Level 5: record poses, then replay them (pick & place).  A "pose" is the angle of all 4 joints at one moment: {base, shoulder, elbow, gripper}.  We store a list of poses and the arm plays through them in a loop,  moving smoothly between each one - that is a pick-and-place routine.  Find the angles by hand first (Level 3 or the pot pendant), write them  down, and fill them into POSES below.  Joints: 0=base  1=shoulder  2=elbow  3=gripper*/#include <Servo.h>const int N = 4;const int PINS[N] = {3, 5, 6, 9};Servo servos[N];int current[N];// each row is one pose: {base, shoulder, elbow, gripper}const int POSES[][N] = {  { 90, 90, 90,  20},   // home, gripper open  { 90, 60, 40,  20},   // reach down to the object  { 90, 60, 40,  80},   // close the gripper (grab)  { 90, 90, 90,  80},   // lift straight up  {160, 90, 90,  80},   // rotate over to the drop spot  {160, 60, 40,  80},   // lower  {160, 60, 40,  20},   // open (release)  {160, 90, 90,  20},   // lift away};const int NUM_POSES = sizeof(POSES) / sizeof(POSES[0]);// move ALL joints smoothly toward a target pose, one degree per stepvoid goToPose(const int target[N], int stepDelay) {  bool moving = true;  while (moving) {    moving = false;    for (int i = 0; i < N; i++) {      if (current[i] != target[i]) {        current[i] += (target[i] > current[i]) ? 1 : -1;        servos[i].write(current[i]);        moving = true;      }    }    delay(stepDelay);  }}void setup() {  for (int i = 0; i < N; i++) {    servos[i].attach(PINS[i]);    current[i] = POSES[0][i];    servos[i].write(current[i]);  }  delay(800);}void loop() {  for (int p = 0; p < NUM_POSES; p++) {    goToPose(POSES[p], 12);    delay(400);          // pause at each pose  }}

7בונוס · שלט לימוד (4 פוטנציומטרים)Bonus · Teach pendant (4 pots)

פוטנציומטר לכל מפרק (A0–A3), map ל-0–180. מניחים תנוחה ביד ורושמים זוויות.A pot per joint (A0–A3), map to 0–180. Hand-pose the arm and note the angles.

bonus_pot_pendant.ino ⬇ הורדהDownload 31 שורותlines
/*  Lesson 6 - Bonus: a "teach pendant" - 4 potentiometers pose the arm live.  Turn each knob and its joint follows. This is the easy way to FEEL out  good poses; read the printed numbers and copy them into Level 5's POSES.  Pots on A0-A3 -> joints  base, shoulder, elbow, gripper.  Servos on D3, D5, D6, D9. External 5-6V on the servo rail, common ground.*/#include <Servo.h>const int N = 4;const int SERVO_PINS[N] = {3, 5, 6, 9};const int POT_PINS[N]   = {A0, A1, A2, A3};Servo servos[N];void setup() {  for (int i = 0; i < N; i++) servos[i].attach(SERVO_PINS[i]);  Serial.begin(9600);  Serial.println("base\tshoulder\telbow\tgripper");}void loop() {  for (int i = 0; i < N; i++) {    int raw = analogRead(POT_PINS[i]);      // 0..1023    int angle = map(raw, 0, 1023, 0, 180);  // -> 0..180 degrees    servos[i].write(angle);    Serial.print(angle);    Serial.print(i < N - 1 ? '\t' : '\n');  }  delay(20);     // a little smoothing}

8בונוס · שליטה ב-BluetoothBonus · Control over Bluetooth

אותה פקודת "<מפרק> <זווית>" דרך HC-05 — מהטלפון או ממרכז השליטה של שיעור 5.The same "<joint> <angle>" over an HC-05 — from the phone or the Lesson 5 command center.

bonus_bt_arm.ino ⬇ הורדהDownload 37 שורותlines
/*  Lesson 6 - Bonus: drive the arm over Bluetooth.  Same big idea as the car in Lessons 3-5: the motion code stays the same,  only WHERE the command comes from changes. The HC-05 receives the very  same "<joint> <angle>" text we used over USB - so you can send poses  from a phone Bluetooth terminal, or from the Lesson 5 command center.  HC-05:  TXD -> D10 ,  RXD <- D11 (through a 1k/2k voltage divider)          VCC -> 5V  ,  GND -> common ground  Joints: 0=base 1=shoulder 2=elbow 3=gripper*/#include <Servo.h>#include <SoftwareSerial.h>SoftwareSerial bt(10, 11);          // RX, TXconst int N = 4;const int PINS[N] = {3, 5, 6, 9};Servo servos[N];void setup() {  for (int i = 0; i < N; i++) {    servos[i].attach(PINS[i]);    servos[i].write(90);  }  bt.begin(9600);}void loop() {  if (bt.available()) {    int joint = bt.parseInt();    int angle = bt.parseInt();    if (joint >= 0 && joint < N) {      angle = constrain(angle, 0, 180);      servos[joint].write(angle);    }  }}