Advertisement
learnelectronics

Arduino Clapper

Apr 21st, 2023
851
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 2.36 KB | Software | 0 0
  1. /*****************************************
  2.  *             Arduino Clapper           *
  3.  *           by Learnelectronics         *
  4.  *      inspired by Sketch by andprof    *
  5.  *         4/20/23 Use this however      *
  6.  *         you wish. Open Source.        *
  7.  *****************************************/        
  8.  
  9.  
  10. int Sensor = A0;                                     //microphone sensor attached to A0
  11. int clap = 0;                                         //claps detected starts at 0
  12. long detection_range_start = 0;                      //detection ranbge starts at 0
  13. long detection_range = 0;                            //see above
  14. boolean status_lights = false;                       //clapper inital state is off
  15.  
  16.  
  17. void setup() {                                         //setup loop runs once time
  18. pinMode(Sensor, INPUT);                                //sensor pin (A0) is set as input
  19. pinMode(2,OUTPUT);                                    //LED pin set as output
  20. Serial.begin(115200);                                 //serial comms for debugging
  21. }
  22.  
  23.  
  24. void loop() {                                        //main loops runs forever
  25. int status_sensor = digitalRead(Sensor);              //read the sensor and store value in status_sensor
  26.  
  27. if (status_sensor == 0)                               //if it is 0
  28. {
  29. if (clap == 0)                                        //and a clap is detected
  30. {
  31. detection_range_start = detection_range = millis();   //start range is detection range is millis all the same
  32. clap++;                                               //increment clap count
  33. }
  34. else if (clap > 0 && millis()-detection_range >= 50)  //if time has pssed before another detected clap
  35. {
  36. detection_range = millis();                           //reset detection range
  37. clap++;                                               //increment clap count
  38. Serial.println(clap);                                 //for debugging
  39. }
  40. }
  41. if (millis()-detection_range_start >= 400)            //if there are 2 claps in under 400 milliseconds do the thing
  42. {
  43. if (clap == 2)
  44. {
  45. if (!status_lights)
  46. {
  47. status_lights = true;
  48. digitalWrite(2, HIGH);                                //do the thing
  49. }
  50. else if (status_lights)
  51. {
  52. status_lights = false;
  53. digitalWrite(2, LOW);                                 //undo the thing
  54. }
  55. }
  56. clap = 0;                                             //reset clap count
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement