Jump to content

Title: Arduino Ultrasonic + servo realizes smart trash can

In this article, I will briefly talk about using Arduino and ultrasonic module to implement intelligent garbage can experiments. When a person approaches the trash can, the trash can is automatically opened.垃圾桶

Preparation of materials

Arduino ultrasonic sensor servo

Line connection

线路连接

实物连线

Code

#include Servo.h

const int trigPin=9; //trigger pin of ultrasonic sensor

const int echoPin=10; //Echo pin of ultrasonic sensor

Servo servoMotor; //Create servo object

void setup() {

Serial.begin(9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

servoMotor.attach(6); //Connect the servo to digital pin 6

}

void loop() {

long duration, distance;

//Send ultrasonic pulses

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

//Read the time of ultrasonic return

duration=pulseIn(echoPin, HIGH);

//Convert time to distance (cm)

distance=(duration/2)/29.1;

Serial.print('Distance:');

Serial.print(distance);

Serial.println(' cm');

//Control the servo to rotate according to distance

if (distance=10) {

//If the distance is less than or equal to 10 cm, the servo will rotate to a 90-degree position

servoMotor.write(90);

} else {

//Otherwise, the servo will return to the 0-degree position

servoMotor.write(0);

}

delay(500); //Delay to stabilize output

}

Effect

Precautions

Correct wiring to prevent the sensor from burning out. The pin position and the angle of the servo can be modified in the code.

0 Comments

Recommended Comments

There are no comments to display.

Guest
Add a comment...