基Arduino简易智能垃圾桶
- 材料清单:Arduino开发板 超声波传感器 舵机 杜邦线
- 原理:当我们人靠近垃圾桶,超声波传感器测出两者之间的距离,距离小于设定的阈值,舵机转动,垃圾桶盖打开。
- 功能:实现人到自动打开垃圾袋。
- 线路连接:
元件名称 | I/O引脚 | ||||
arduino | 正极 | 负极 | 引脚2 | 引脚3 | 引脚9 |
舵机 | 正极 | 负极 | 信号接收口 | ||
超声波传感器 | 正极 | 负极 | TrigPin | EchoPin |
5.注意事项:舵机红色线:正极接5v 棕色(有的黑色)线:负极 黄色(橘色):arduino9号引脚
- 代码:
1 #include <Servo.h> 2 Servo myservo; // 创建舵机对象来控制舵机 3 int pos = 0; 4 const int TrigPin = 2; 5 const int EchoPin = 3; 6 float distance; 7 void setup() 8 { 9 // 初始化串口通信及连接SR04的引脚 10 Serial.begin(9600); 11 pinMode(TrigPin, OUTPUT); 12 // 要检测引脚上输入的脉冲宽度,需要先设置为输入状态 13 pinMode(EchoPin, INPUT); 14 Serial.println("Ultrasonic sensor:"); 15 myservo.attach(9); 16 // 把连接在引脚9上的舵机赋予舵机对其控制 17 } 18 void loop() 19 { 20 // 产生一个10us的高脉冲去触发TrigPin 21 digitalWrite(TrigPin, LOW); 22 delayMicroseconds(2); 23 digitalWrite(TrigPin, HIGH); 24 delayMicroseconds(10); 25 digitalWrite(TrigPin, LOW); 26 // 检测脉冲宽度,并计算出距离 27 distance = pulseIn(EchoPin, HIGH) / 58.00; 28 Serial.println(distance); 29 delay(300); 30 if (distance<=50) 31 { 32 for(pos = 0; pos <= 120; pos += 120) // 从0度到120度 步长为120度,角度自己可调整 33 { 34 myservo.write(5); // 告诉舵机到达位置 35 delay(150); // 舵机命令之间等待15ms 36 } 37 } 38 if (distance>=50) 39 { 40 for(pos = 180; pos>=0; pos-=180) // 从120度到0度 41 { 42 myservo.write(120); // 在相反的方向上移动舵 43 delay(150); // 舵机命令之间等待15ms 44 } 45 } 46 }
6.选择对应串口上传,每个人的电脑有可能不一样,查看舵机转动,方向不合适可自己调整。
总结:1,制作模型过程要多加小心,我的手指就是在制作过程中操作不当,流血不止 嘻嘻 还好没有什么大碍。2、在连接电路过程中有必要的时候可以把线路接稳了,能固 定就可以固定了,现在接的电路比较简单,以后可能要接触多电路时就很难排错。