Arduino示例代码讲解: Project 12 - Knock Lock 锁
Arduino示例代码讲解: Project 12 - Knock Lock 锁
- Project 12 - Knock Lock 锁
- 程序功能概述
- 功能:
- 硬件要求:
- 输出:
- 代码结构
- 全局变量
- `setup()` 函数
- `loop()` 函数
- 未锁定状态:
- 锁定状态:
- `checkForKnock()` 函数
- 运行过程
- 注意事项
Project 12 - Knock Lock 锁
这段代码是一个Arduino程序,用于实现一个“敲击锁”项目,通过敲击传感器(压电传感器)和按钮控制一个伺服电机,模拟一个锁的开合。
/*Arduino Starter Kit exampleProject 12 - Knock LockThis sketch is written to accompany Project 12 in theArduino Starter KitParts required:1 Megohm resistor10 kilohm resistorthree 220 ohm resistorspiezoservo motorpush buttonone red LEDone yellow LEDone green LED100 uF capacitorCreated 18 September 2012by Scott FitzgeraldThanks to Federico Vanzati for improvementshttp://arduino.cc/starterKitThis example code is part of the public domain*/// import the library
#include <Servo.h>
// create an instance of the servo library
Servo myServo;const int piezo = A0; // pin the piezo is attached to
const int switchPin = 2; // pin the switch is attached to
const int yellowLed = 3; // pin the yellow LED is attached to
const int greenLed = 4; // pin the green LED is attached to
const int redLed = 5; // pin the red LED is attached to// variable for the piezo value
int knockVal;
// variable for the switch value
int switchVal;// variables for the high and low limits of the knock value
const int quietKnock = 10;
const int loudKnock = 100;// variable to indicate if locked or not
boolean locked = false;
// how many valid knocks you've received
int numberOfKnocks = 0;void setup() {// attach the servo to pin 9myServo.attach(9);// make the LED pins outputspinMode(yellowLed, OUTPUT);pinMode(redLed, OUTPUT);pinMode(greenLed, OUTPUT);// set the switch pin as an inputpinMode(switchPin, INPUT);// start serial communication for debuggingSerial.begin(9600);// turn the green LED ondigitalWrite(greenLed, HIGH);// move the servo to the unlocked positionmyServo.write(0);// print status to the serial monitorSerial.println("the box is unlocked!");
}void loop() {// if the box is unlockedif (locked == false) {// read the value of the switch pinswitchVal