Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Sensor{
- public:
- int trigPin = 9;
- int echoPin = 8;
- float getDistance(){
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- double duration = pulseIn(echoPin, HIGH);
- double distance = 0.0343*duration/2;
- return(distance);
- }
- };
- class Speaker{
- public:
- int soundPin = 12;
- };
- class Button{
- public:
- int buttonPin = 2;
- bool shouldPlay = 0;
- long long lastToggle;
- bool isPressed(){
- if (bool buttonState = digitalRead(buttonPin)){
- if (millis() - lastToggle > 250){
- lastToggle = millis();
- return(true);
- }
- }
- return(false);
- }
- };
- Sensor sensor;
- Speaker speaker;
- Button button;
- long long start;
- bool active;
- void setup(){
- Serial.begin(115200);
- pinMode(sensor.echoPin, INPUT);
- pinMode(sensor.trigPin, OUTPUT);
- pinMode(speaker.soundPin, OUTPUT);
- pinMode(button.buttonPin, INPUT);
- pinMode(13, OUTPUT);
- button.lastToggle = millis();
- active = false;
- }
- void loop(){
- if (sensor.getDistance() < 25 && active == false){
- tone(speaker.soundPin, 400);
- start = millis();
- active = true;
- }
- if (millis() - start < 5000){
- if (button.isPressed()){
- noTone(speaker.soundPin);
- active = false;
- delay(3000);
- }
- }
- if (millis() - start > 5000){
- noTone(speaker.soundPin);
- digitalWrite(13, HIGH);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment