Skip to content

Instantly share code, notes, and snippets.

@myy
Created October 14, 2012 11:47
Show Gist options
  • Save myy/3888327 to your computer and use it in GitHub Desktop.
Save myy/3888327 to your computer and use it in GitHub Desktop.
コンデンサマイクから拾った音量が一定以上のときに,サーボモータを動かす
// コンデンサマイクから拾った音の大きさが一定以上であれば,サーボを動かす
// 2012/08/21 できた!でも,一定以上の音が鳴っている間はサーボの角度を維持するようにしたいなあ
#include <Servo.h>
Servo myservo; // Servo型の変数
int ecmPin = 0; // ECMは0ピンへ接続
//int state = 0; // サーボの状態.1のときは130度まで回転した状態.0のときは30度まで回転した状態
void setup()
{
myservo.attach(9); // サーボは9ピン
myservo.write(150); // サーボの最初の角度は90度
Serial.begin(9600);
}
void loop()
{
// static int lasEcmLevel = 0; // 前の音量レベル
int input = analogRead(ecmPin); // ECMからの値をint型で読み込む
Serial.print(input);
Serial.print(", ");
input = abs(input - 512); // 入力値の絶対値を求める
Serial.print(input);
int ecmLevel = map(input, 50, 380, 0, 8); // 50から380の絶対値を0から8の段階にマッピングする
Serial.print(", ");
Serial.println(ecmLevel);
if(myservo.read() < 90 && ecmLevel >= 1) {
myservo.write(150); // しきい値より大きい音であれば150度回転
} else if(myservo.read() > 90 && ecmLevel < 1) {
myservo.write(30); // しきい値より小さい音であれば30度回転
}
delay(500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment