---
# System prepended metadata

title: 機器人專題製作

---

# 課程內容
**開燈**
```c=
void setup() {
  pinMode(11,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(13,OUTPUT);

}

void loop() {
  digitalWrite(13,HIGH);
  digitalWrite(12,HIGH);
  delay(200);
  digitalWrite(13,LOW);
  digitalWrite(12,LOW);
  delay(200);
  digitalWrite(12,HIGH);
  digitalWrite(11,HIGH);
  delay(200);
  digitalWrite(12,LOW);
  digitalWrite(11,LOW);
  delay(200);
  digitalWrite(11,HIGH);
  digitalWrite(13,HIGH);
  delay(200);
  digitalWrite(11,LOW);
  digitalWrite(13,LOW);
  delay(200);

}
```
**超音波**
```c=
int trigPin = 10;                  //Trig Pin
int echoPin = 9;                  //Echo Pin
long duration, cm, inches;
 
void setup() {
  Serial.begin (9600);             // Serial Port begin
  pinMode(trigPin, OUTPUT);        // 定義輸入及輸出 
  pinMode(echoPin, INPUT);
}
 
void loop()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);     // 給 Trig 高電位，持續 10微秒
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);             // 讀取 echo 的電位
  duration = pulseIn(echoPin, HIGH);   // 收到高電位時的時間
 
  cm = (duration/2) / 29.1;         // 將時間換算成距離 cm 或 inch  
  inches = (duration/2) / 74; 

  Serial.print("Distance : ");  
  Serial.print(inches);
  Serial.print("in,   ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  
  delay(250);
}
```
**超音波感測燈**
```c=
int trigPin = 10;    // 超音波感接 Arduino pin 11
int echoPin = 9;    //超音波感測器 Echo 腳接 Arduino pin 12
int speakerpin = 7;  //蜂鳴器 + 腳接 Arduino pin 7
long duration, cm ;  //宣告計算距離時，需要用到的兩個實數
 
void setup() {
  Serial.begin (9600);           //設定序列埠監控視窗 (Serial Monitor) 和 Arduino資料傳輸速率為 9600 bps (Bits Per Second)
  pinMode(trigPin, OUTPUT);      //Arduino 對外啟動距離感測器Trig腳，射出超音波 
  pinMode(echoPin, INPUT);       //超音波被障礙物反射後，Arduino讀取感測器Echo腳的時間差
  pinMode(speakerpin, OUTPUT); //Arduino對蜂鳴器送出電壓，使其鳴叫
  pinMode(11,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(13,OUTPUT);
}
 
void loop()
{                                  //程式計算出距離值 cm
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  cm = (duration/2) / 29.1;  

  Serial.print(cm);     //印出距離值 cm 在序列埠監控顯示器 單位公分
  Serial.println(" cm");

   if (cm <= 10) {                       //距離小於5公分，蜂鳴器一直叫 
    digitalWrite(13, HIGH);
    delay (cm*25);
    digitalWrite(13, LOW);
    delay (cm*25);
      }
  if (cm > 20 && cm <= 50) {
    //距離介於5到15公分，蜂鳴器斷斷續續叫，每次0.1秒 
    digitalWrite(12, HIGH);
    delay (cm*50);
    digitalWrite(12, LOW);
    delay (cm*50);
   }
  if (cm > 50){                        // 距離大於15公分，蜂鳴器斷斷續續叫，每次0.5秒 
     digitalWrite(11, HIGH);
    delay (cm*100);
    digitalWrite(11, LOW);
    delay (cm*100);
      }
  delay(10); 
  }
```
# 專題製作
**避障自走車**
```c=


#include <Arduino.h>
#include <Wire.h>
#include <SoftwareSerial.h>

float turn = 0;
float Distance = 0;
float Distance_left = 0;
float Distance_right = 0;

float getDistance(int trig,int echo){
    pinMode(trig,OUTPUT);
    digitalWrite(trig,LOW);
    delayMicroseconds(2);
    digitalWrite(trig,HIGH);
    delayMicroseconds(10);
    digitalWrite(trig,LOW);
    pinMode(echo, INPUT);
    return pulseIn(echo,HIGH,30000)/58.0;
}
void go(){
  analogWrite(5,0);
  analogWrite(6,200);
  analogWrite(9,200);
  analogWrite(10,0);

}
void left(){
  analogWrite(5,0);
  analogWrite(6,200);
  analogWrite(9,0);
  analogWrite(10,200);

}
void right(){
  analogWrite(5,200);
  analogWrite(6,0);
  analogWrite(9,200);
  analogWrite(10,0);

}
void a(){
  analogWrite(5,0);
  analogWrite(6,0);
  analogWrite(9,0);
  analogWrite(10,0);

}

void _delay(float seconds) {
  long endTime = millis() + seconds * 1000;
  while(millis() < endTime) _loop();
}

void setup() {
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  while(1) {
      Distance = getDistance(3,2);
      Distance_left = getDistance(13,12);
      Distance_right = getDistance(11,8);
      if(Distance > 15){
        go();

      }else{
        if(Distance_left > 15){
          left();

        }else{
          if(Distance_right > 15){
            right();

          }else{
            a();
          }

        }

      }

      _loop();
  }

}

void _loop() {
}

void loop() {
  _loop();
}

```
```=
#include <Arduino.h>
#include <Wire.h>
#include <SoftwareSerial.h>

float turn = 0;
float Distance = 0;
float Distance_left = 0;
float Distance_right = 0;

float getDistance(int trig,int echo){
    pinMode(trig,OUTPUT);
    digitalWrite(trig,LOW);
    delayMicroseconds(2);
    digitalWrite(trig,HIGH);
    delayMicroseconds(10);
    digitalWrite(trig,LOW);
    pinMode(echo, INPUT);
    return pulseIn(echo,HIGH,30000)/58.0;
}
void go(){
  analogWrite(5,200);
  analogWrite(6,0);
  analogWrite(9,0);
  analogWrite(10,200);

}
void left(int a){
  analogWrite(5,0);
  analogWrite(6,a);
  analogWrite(9,0);
  analogWrite(10,a);

}
void right(int a){
  analogWrite(5,a);
  analogWrite(6,0);
  analogWrite(9,a);
  analogWrite(10,0);

}
void a(){
  analogWrite(5,0);
  analogWrite(6,100);
  analogWrite(9,100);
  analogWrite(10,0);

}

void _delay(float seconds) {
  long endTime = millis() + seconds * 1000;
  while(millis() < endTime) _loop();
}

void setup() {
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  while(1) {
      Distance = getDistance(3,2);
      Distance_left = getDistance(13,12);
      Distance_right = getDistance(11,8);
      if(Distance > 15){
        go();
        if(Distance_left>Distance_right){
           left(25);
        }else{right(25);
          }
      }else{
        if(Distance_left > 15){
          left(200);

        }else{
          if(Distance_right > 15){
            right(200);

          }else{
            a();
          }

        }

      }

      _loop();
  }

}

void _loop() {
}

void loop() {
  _loop();
}

```
```c=
 #include <AFMotor.h>
#include <MsTimer2.h>

AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);

// PID参数 (PID Parameters)
double Setpoint = 0.0; // 目标距离（根据传感器单位调整） (Target distance - adjust based on sensor unit)
double Kp = 1.5;        // 比例增益 (Proportional gain)
double Ki = 0.0;        // 积分增益 (Integral gain)
double Kd = 5;       // 微分增益 (Derivative gain)
double Input, Output, previousError, integral;

//Ultrasonic sensor pins
const int frontTrigPin = A4;
const int frontEchoPin = A5;
const int leftTrigPin = A0;
const int leftEchoPin = A1;
const int rightTrigPin = A2;
const int rightEchoPin = A3;

//Other variables
double leftDistance, rightDistance, frontDistance;

double getDistance(int trigPin, int echoPin) {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  double distance = pulseIn(echoPin, HIGH) / 58.0; // Convert to centimeters

  //Limit the distance to a maximum of 100 centimeters
  /*if (distance > 100.0) {
    distance = 100.0;
  
  }*/
  return distance;
}

double forward(){
    //Calculate PID control input using distances from left and right ultrasonic sensors
  Input = leftDistance - rightDistance;

  //Manual PID control calculation
  double error = Setpoint - Input;  //Error
  integral += error;  //Accumulated error
  double derivative = error - previousError;  //Rate of change of error
  Output = Kp * error + Ki * integral + Kd * derivative;
  previousError = error;  //Save current error for the next iteration
  if (Output > 255.0) {
    Output = 255.0;
  }
  //Adjust motor speed based on PID output
  int leftMotorSpeed = 255 - Output;
  int rightMotorSpeed = 255 + Output;
  
  //Control motors using the AFMotor library
  motor2.setSpeed(leftMotorSpeed);
  motor2.run(FORWARD);
  motor1.setSpeed(rightMotorSpeed);
  motor1.run(FORWARD);
  motor3.setSpeed(leftMotorSpeed);
  motor3.run(FORWARD);
  motor4.setSpeed(rightMotorSpeed);
  motor4.run(FORWARD);
}

void setup() {
  //Initialize ultrasonic sensor pins
  pinMode(frontTrigPin, OUTPUT);
  pinMode(frontEchoPin, INPUT);
  pinMode(leftTrigPin, OUTPUT);
  pinMode(leftEchoPin, INPUT);
  pinMode(rightTrigPin, OUTPUT);
  pinMode(rightEchoPin, INPUT);

  //Initialize serial communication
  Serial.begin(9600);
}
 int k=6;
void loop() {
  //Read left and right ultrasonic sensor distances
  leftDistance = getDistance(leftTrigPin, leftEchoPin);
  rightDistance = getDistance(rightTrigPin, rightEchoPin);
  frontDistance = getDistance(frontTrigPin, frontEchoPin);
 
  if(k<=3){k++;if(rightDistance>leftDistance){
      motor1.run(BACKWARD);
      motor1.setSpeed(255);
      motor4.run(BACKWARD);
      motor4.setSpeed(255);
      motor2.run(FORWARD);
      motor2.setSpeed(255);
      motor3.run(FORWARD);
      motor3.setSpeed(255);
      }
    else{
      motor2.run(BACKWARD);
      motor2.setSpeed(255);
      motor3.run(BACKWARD);
      motor3.setSpeed(255);
      motor1.run(FORWARD);
      motor1.setSpeed(255);
      motor4.run(FORWARD);
      motor4.setSpeed(255);
    }}else{
  if(frontDistance>20){
    forward();  
  }
  else if(frontDistance<30){k=0;
    if(rightDistance>leftDistance){
      motor1.run(BACKWARD);
      motor1.setSpeed(255);
      motor4.run(BACKWARD);
      motor4.setSpeed(255);
      motor2.run(FORWARD);
      motor2.setSpeed(255);
      motor3.run(FORWARD);
      motor3.setSpeed(255);    }
    else{
      motor2.run(BACKWARD);
      motor2.setSpeed(255);
      motor3.run(BACKWARD);
      motor3.setSpeed(255);
      motor1.run(FORWARD);
      motor1.setSpeed(255);
      motor4.run(FORWARD);
      motor4.setSpeed(255);
    }
  }

  //Output debug information
  Serial.print("前方距离：");  // Left Distance
  Serial.print(frontDistance);
  Serial.print("左方距离：");  // Left Distance
  Serial.print(leftDistance);
  Serial.print("右方距离：");  // Right Distance
  Serial.print(rightDistance);
  Serial.print(" Intput：");  // Input
  Serial.print(Input);
  Serial.print(" Output：");  // Output
  Serial.println(Output);
}}
```
```c=
#include <Arduino.h>
#include <Wire.h>
#include <SoftwareSerial.h>

float turn = 0;
float Distance = 0;
float Distance_left = 0;
float Distance_right = 0;

float getDistance(int trig,int echo){
    pinMode(trig,OUTPUT);
    digitalWrite(trig,LOW);
    delayMicroseconds(2);
    digitalWrite(trig,HIGH);
    delayMicroseconds(10);
    digitalWrite(trig,LOW);
    pinMode(echo, INPUT);
    return pulseIn(echo,HIGH,30000)/58.0;
}
void go(){
  analogWrite(5,200);
  analogWrite(6,0);
  analogWrite(9,0);
  analogWrite(10,200);

}
void left(int a){
  analogWrite(5,0);
  analogWrite(6,a);
  analogWrite(9,0);
  analogWrite(10,a);

}
void right(int a){
  analogWrite(5,a);
  analogWrite(6,0);
  analogWrite(9,a);
  analogWrite(10,0);

}
void a(){
  analogWrite(5,0);
  analogWrite(6,200);
  analogWrite(9,200);
  analogWrite(10,0);

}
void right1(int k){
  while(k>=0){
    right(200);k--;
  }
}
void left1(int k){
  while(k>=0){
    left(200);k--;
  }
}
void _delay(float seconds) {
  long endTime = millis() + seconds * 1000;
  while(millis() < endTime) _loop();
}

void setup() {
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  while(1) {
      Distance = getDistance(3,2);
      Distance_left = getDistance(13,12);
      Distance_right = getDistance(11,8);
      
      if(Distance > 15){
       int k=(Distance_left- Distance_right)*10;
        if(Distance_left>Distance_right){
            analogWrite(5,210);
            analogWrite(6,k);
            analogWrite(9,0);
            analogWrite(10,210+k);
        }else{analogWrite(5,210-k);
              analogWrite(6,0);
              analogWrite(9,-k);
              analogWrite(10,210);
          }
      }else{
        if(Distance_left <15 && Distance_right <15){
           a();
        }else{
          if(Distance_right > Distance_left){
            right1(5);

          }else{
           left1(7);
          }

        }

      }

      _loop();
  }

}

void _loop() {
}

void loop() {
  _loop();
}

```
**循跡自走車**

# 遇到問題與解決方法
1. 腳位不能接1和0，因為接收外部訊息用
# 參考內容