Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. #include <Servo.h>
  2. Servo servo9;
  3. const int piezo = A0;
  4. const int switchPin = 2;
  5. const int yellowLed = 3;
  6. const int greenLed = 4;
  7. const int redLed = 5;
  8. int knockVal;
  9. int switchVal;
  10. const int quietKnock = 10;
  11. const int loudKnock = 100;
  12. boolean locked = false;
  13. int numberOfKnocks = 0;
  14. void setup() {
  15. servo9.attach(9);
  16. pinMode(yellowLed, OUTPUT);
  17. pinMode(greenLed, OUTPUT);
  18. pinMode(redLed, OUTPUT);
  19. pinMode(switchPin, INPUT);
  20. Serial.begin(9600);
  21. digitalWrite(greenLed, HIGH);
  22.  
  23. servo9.write(0);
  24. Serial.println("The box is unlocked!");
  25. }
  26. void loop() {
  27. if (locked == false) {
  28. switchVal = digitalRead(switchPin);
  29. if (switchVal == HIGH) {
  30. locked = true;
  31. digitalWrite(greenLed, LOW);
  32. digitalWrite(redLed, HIGH);
  33. servo9.write(90);
  34. Serial.println("The box is locked!");
  35. delay(1000);
  36. }
  37. }
  38. if (locked == true) {
  39. knockVal = analogRead(piezo);
  40. if (numberOfKnocks < 3 && knockVal > 0) {
  41. if (checkForKnock(knockVal) == true) { // Check for correct
  42. // number of knocks
  43. numberOfKnocks++;
  44. }
  45. Serial.print(3 - numberOfKnocks);
  46. Serial.println(" more knocks to go");
  47. }
  48. if (numberOfKnocks >= 3) { // If 3 valid knocks are detected,
  49. // the servo moves
  50. locked = false;
  51. servo9.write(0);
  52. delay(20);
  53. digitalWrite(greenLed, HIGH);
  54. digitalWrite(redLed, LOW);
  55. Serial.println("The box is unlocked!");
  56. }
  57. }
  58. }
  59. boolean checkForKnock(int value) { // Checks knock value
  60. if (value > quietKnock && value < loudKnock) { // Value needs to be
  61. // between these
  62. digitalWrite(yellowLed, HIGH);
  63. delay(50);
  64. digitalWrite(yellowLed, LOW);
  65. Serial.print("Valid knock of value ");
  66. Serial.println(value);
  67. return true;
  68. }
  69. else {
  70. Serial.print("Bad knock value ");
  71. Serial.println(value);
  72. return false;
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement