---
# System prepended metadata

title: LAB07 利用光敏電阻與伺服馬達控制 Google 恐龍跳跳跳
tags: [嵌入式系統]

---

# LAB07 利用光敏電阻與伺服馬達控制 Google 恐龍跳跳跳

## DEMO
<iframe width="560" height="315" src="https://www.youtube.com/embed/nKdtxg0qZ64?si=sWeFDAaO55uMGpuh" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

## 電路圖
![image](https://hackmd.io/_uploads/ryiK0Zz7ke.png)


## 程式碼說明
- 先讀取感光元件讀取的值
    ```cpp=
    int sensorValue1 = analogRead(4);  //下面的感光元件
    int sensorValue2 = analogRead(27); //上面的感光元件
    ```
- 接著我們在數值上分成兩種情況: 蹲下與跳躍
    - CASE1 蹲下: 上面暗下面亮
        ```cpp=
        if (sensorValue1 >= 1300 && sensorValue2 < 1300){
            digitalWrite(2,HIGH);   
            down.write(60);
            delay(200);
            down.write(0);
        }
        ```
    - CASE2 跳躍: 上面暗下面暗 or 上面亮下面暗
        ```cpp=
        else if(sensorValue1 < 1300 || sensorValue2 < 1300){   
            digitalWrite(2,HIGH);     
            jump.write(60);
            delay(75);
            jump.write(0);
        }
        ```
## 程式碼
```cpp=
#include <ESP32_Servo.h> 
#define SERVO_JUMP_PIN 16 
#define SERVO_DOWN_PIN 17    
Servo jump; 
Servo down; 

void setup() {
  Serial.begin(9600);
  pinMode(2,OUTPUT);
  //JUMP servo setting
  jump.attach(SERVO_JUMP_PIN, 500, 2400);              
  jump.write(0);

  //DOWN servo setting
  down.attach(SERVO_DOWN_PIN, 500, 2400);              
  down.write(0);
}

void loop() {
  // reading the value of lightness
  int sensorValue1 = analogRead(4);
  int sensorValue2 = analogRead(27);
  Serial.printf("%d, %d\n",sensorValue1, sensorValue2); 
  
  //case 1: DOWN    
  if (sensorValue1 >= 1300 && sensorValue2 < 1300){
    digitalWrite(2,HIGH);   
    down.write(60);
    delay(200);
    down.write(0);
  }
  //case2: jump
  else if(sensorValue1 < 1300 || sensorValue2 < 1300){   
    digitalWrite(2,HIGH);     
    jump.write(60);
    delay(75);
    jump.write(0);
  }
   digitalWrite(2,LOW);   
}
```