3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

自動で開くゴミ箱を電子工作しました

Last updated at Posted at 2019-11-23

目的

自動で開くゴミ箱を電子工作した際の備忘録です

準備

100均の卓上ゴミ箱
Arduino Nano
サーボモータ(SG-90)
距離センサ(HC-SR04)
モバイルバッテリー
グルーガン、養生テープ等

ブロック図

スクリーンショット 2019-11-09 20.09.24.png

距離センサ(HC-SR04)とArduino nanoの接続

VCC - 5V
ECHO - D9
TRIG - D8
GND - GND

サーボモータ(SG-90)とArduino nanoの接続

VCC - 5V
制御信号 D7
GND - GND

コード

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

#define echoPin 9 // Echo Pin
#define trigPin 8 // Trigger Pin
double Duration = 0; //受信した間隔
double Distance = 0; //距離

int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin( 115200 );
  myservo.attach(7);  // attaches the servo on pin 9 to the servo object
  pinMode( echoPin, INPUT );
  pinMode( trigPin, OUTPUT );
}

void loop() {

  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2); 
  digitalWrite( trigPin, HIGH ); //超音波を出力
  delayMicroseconds( 10 ); //
  digitalWrite( trigPin, LOW );
  Duration = pulseIn( echoPin, HIGH ); //センサからの入力
  if (Duration > 0) {
    Duration = Duration/2; //往復距離を半分にする
    Distance = Duration*340*100/1000000; // 音速を340m/sに設定
    Serial.print("Distance:");
    Serial.print(Distance);
    Serial.println(" cm");
  }
  delay(500);

  if( Distance < 30.0 && Distance > 3.0) { 
    for (pos = 0; pos <= 85; pos += 1) { // goes from 0 degrees to 180 degrees
         // in steps of 1 degree
         myservo.write(pos);              // tell servo to go to position in variable 'pos'
         delay(7);                       // waits 15ms for the servo to reach the position
    }
    delay(2000);
    for (pos = 85; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          delay(7);                       // waits 15ms for the servo to reach the position
    }
  }
}

テスト

距離センサから30cm以内の距離にモノを近づけるとゴミ箱が開きます。

CodingError対策

特になし

参考

arduino nano の外部電源
【Arduino】超音波距離センサ(HC-SR04)の使い方
ArduinoにServoモータを繋いで動かす

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?