RobinBrusbo

Bra för fan

Dec 22nd, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. class Sensor{
  2.  
  3.     public:
  4.  
  5.         int trigPin = 9;
  6.         int echoPin = 8;
  7.  
  8.         float getDistance(){
  9.             digitalWrite(trigPin, LOW);
  10.             delayMicroseconds(2);
  11.             digitalWrite(trigPin, HIGH);
  12.             delayMicroseconds(10);
  13.             digitalWrite(trigPin, LOW);
  14.  
  15.             double duration = pulseIn(echoPin, HIGH);
  16.  
  17.             double distance = 0.0343*duration/2;
  18.  
  19.             return(distance);
  20.         }
  21.  
  22. };
  23.  
  24. class Speaker{
  25.  
  26.     public:
  27.         int soundPin = 12;
  28.  
  29. };
  30.  
  31. class Button{
  32.  
  33.     public:
  34.         int buttonPin = 2;
  35.         bool shouldPlay = 0;
  36.         long long lastToggle;
  37.        
  38.         bool isPressed(){
  39.             if (bool buttonState = digitalRead(buttonPin)){
  40.                 if (millis() - lastToggle > 250){
  41.                     lastToggle = millis();
  42.                     return(true);
  43.                 }
  44.             }
  45.             return(false);
  46.         }
  47.  
  48. };
  49.  
  50. Sensor sensor;
  51. Speaker speaker;
  52. Button button;
  53.  
  54. long long start;
  55. bool active;
  56.  
  57. void setup(){
  58.     Serial.begin(115200);
  59.     pinMode(sensor.echoPin, INPUT);
  60.     pinMode(sensor.trigPin, OUTPUT);
  61.     pinMode(speaker.soundPin, OUTPUT);
  62.     pinMode(button.buttonPin, INPUT);
  63.     pinMode(13, OUTPUT);
  64.     button.lastToggle = millis();
  65.     active = false;
  66. }
  67.  
  68. void loop(){
  69.    
  70.     if (sensor.getDistance() < 25 && active == false){
  71.         tone(speaker.soundPin, 400);
  72.         start = millis();
  73.         active = true;
  74.     }
  75.    
  76.     if (millis() - start < 5000){
  77.         if (button.isPressed()){
  78.             noTone(speaker.soundPin);
  79.             active = false;
  80.             delay(3000);
  81.         }
  82.     }
  83.    
  84.     if (millis() - start > 5000){
  85.         noTone(speaker.soundPin);
  86.         digitalWrite(13, HIGH);
  87.     }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment