網頁

2023年6月4日

Arduino 電子標靶

 程式碼

#include <Ultrasonic.h>

Ultrasonic ultrasonic(2, 3);

int distance;



#include <Servo.h>

Servo myservo;


#include "pitches.h"

int melody[] = {

  NOTE_C4, NOTE_G4

};

int noteDurations[] = {

  4, 2

};


int score;


void setup() {

  Serial.begin(9600);


  myservo.attach(13);  // 設定要將伺服馬達接到哪一個PIN腳

  myservo.write(20);  //旋轉到130度

  

  pinMode(8, OUTPUT);

  pinMode(9, OUTPUT);

  pinMode(10, OUTPUT);


  digitalWrite(8, LOW);

  digitalWrite(9, LOW);

  digitalWrite(10, LOW);


  distance=100;

  score = 0;

}


void loop() {

  if (score == 1) {

    digitalWrite(8, HIGH);

    digitalWrite(9, LOW);

    digitalWrite(10, LOW);

  } else if (score == 2) {

    digitalWrite(8, LOW);

    digitalWrite(9, HIGH);

    digitalWrite(10, LOW);

  } else if (score == 3) {

    digitalWrite(8, HIGH);

    digitalWrite(9, HIGH);

    digitalWrite(10, LOW);

  } else if (score == 4) {

    digitalWrite(8, LOW);

    digitalWrite(9, LOW);

    digitalWrite(10, HIGH);

  } else if (score == 5) {

    digitalWrite(8, HIGH);

    digitalWrite(9, LOW);

    digitalWrite(10, HIGH);

  } else if (score == 6) {

    digitalWrite(8, LOW);

    digitalWrite(9, HIGH);

    digitalWrite(10, HIGH);

  } else if (score == 7) {

    digitalWrite(8, HIGH);

    digitalWrite(9, HIGH);

    digitalWrite(10, HIGH);

  } else if (score == 8) {

    digitalWrite(8, LOW);

    digitalWrite(9, LOW);

    digitalWrite(10, LOW);

    score=0;

  }


  if (distance < 20) {

    for (int thisNote = 0; thisNote < 2; thisNote++) {

    int noteDuration = 1000 / noteDurations[thisNote];

    tone(12, melody[thisNote], noteDuration);

    int pauseBetweenNotes = noteDuration * 1.30;

    delay(pauseBetweenNotes);    

    noTone(12); 

  }


    score = score + 1;


    myservo.write(130);  //旋轉到130度

    delay(500);

    myservo.write(20); //旋轉到20度


  }


  distance = ultrasonic.read(); 

  

  Serial.print(score);

  Serial.println(distance);

  delay(500); //每次間格0.5秒

}

沒有留言:

張貼留言