BASIC4MCU | 질문게시판 | 서보모터 질문
페이지 정보
작성자 죠르디 작성일2022-06-07 16:03 조회8,822회 댓글2건본문
안녕하세요. 질문이 있어서 글 남깁니다. 사운드센서의 일정값이 넘으면 멜로디가 나오면서 서보모터 두개가 돌아가는 코드인데 사운드가 넘으면 한 멜로디에 서보모터가 반 바퀴만 천천히 돌아가는데 그 속도를 빠르게 하거나 반바퀴로 두번 회전하게끔 할 수는 없나요? 도와주시면 정말 감사하겠습니다 ㅜㅜ
#include <MsTimer2.h>
#include <Servo.h>
Servo myservo1;// create servo object to control a servo
Servo myservo2;// twelve servo objects can be created on most boards
int Sensor = A1;
int speakerPin=8;
char notes[] = "ccggaag ffeeddc ggffeed ggffeed ccggaag ffeeddc ";
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
int tempo = 300;
volatile int pos=0,length=15,len=0,run=0;
void playTone(int tone, int duration) { //자장가 출력1
for (long len = 0; len < duration * 1000L; len += tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}
void playNote(char note, int duration) { //자장가 출력2
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int tones[] = { 2015, 1800, 1619, 1532, 1375, 1236, 1114, 1056 };
for (int len = 0; len < 8; len++) {
if (names[len] == note) {
playTone(tones[len], duration);
}
}
}
void flash() { //서보모터 작동
if(run){
if(len<9){ if(pos<180)pos++; }
else{ if(pos>0)pos--; }
myservo1.write(pos);
myservo2.write(pos);
}
else{
pos=0; myservo1.write(0); myservo2.write(0);
}
}
void setup() {
myservo1.attach(6);
myservo2.attach(5);// attaches the servo on pin 5,6 to the servo object
Serial.begin(9600);
pinMode(Sensor,INPUT);
pinMode(speakerPin, OUTPUT);
MsTimer2::set(16,flash); // flash함수를 16ms마다 호출한다
MsTimer2::start();
}
void loop() {
int Sound = analogRead(Sensor);
Serial.println(Sound);
if (Sound > 100) { //소리가 100이상이면
run=1;
for (len=0;len<length;len++){
if (notes[len]==' ') { delay(beats[len] * tempo); }
else { playNote(notes[len], beats[len] * tempo); }
delay(tempo / 2);
}
run=0;
}
}
댓글 2
조회수 8,822master님의 댓글
master 작성일
MsTimer2::set(16,flash); // flash함수를 16ms마다 호출한다
16ms마다 서보모터 각도가 회전합니다.
16을 8로 고치면 두배 빠르게 회전합니다
죠르디님의 댓글
죠르디
도움 주셔서 감사합니다. 항상 행복한 일만 가득하시길 바랄게요!