Created
May 11, 2018 20:34
-
-
Save ulitiy/6907ecc4cd5533a65d7015211d730070 to your computer and use it in GitHub Desktop.
Ultrasonic light switch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <NewPing.h> | |
#define TRIGGER_PIN 5 // Arduino pin tied to trigger pin on the ultrasonic sensor. | |
#define ECHO_PIN 4 // Arduino pin tied to echo pin on the ultrasonic sensor. | |
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. | |
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. | |
int usual_dist; | |
float acc_dist; | |
unsigned long last_hit=0; | |
void setup() { | |
pinMode(A3, OUTPUT); | |
// digitalWrite(A3, HIGH); | |
digitalWrite(A3, LOW); | |
Serial.begin(9600); // Open serial monitor at 115200 baud to see ping results. | |
pinMode(6, OUTPUT); // VCC pin | |
pinMode(3, OUTPUT); // GND ping | |
digitalWrite(6, HIGH); // VCC +5V mode | |
digitalWrite(3, LOW); // GND mode | |
int sum_dist = 0; | |
delay(2000); | |
// for(int i=0;i<100;i++){ | |
// delay(50); | |
// sum_dist += sonar.ping_cm(); | |
// } | |
// usual_dist = sum_dist / 100; | |
usual_dist = 164; // 167 | |
acc_dist = usual_dist; | |
} | |
void loop() { | |
int dist = sonar.ping_cm(); | |
if(dist == 0){ | |
Serial.println("ZERO---------------------------------"); | |
delay(50); | |
return; | |
} | |
Serial.print(dist); | |
Serial.print('-'); | |
Serial.print(acc_dist); | |
if(acc_dist < usual_dist){ | |
last_hit = millis(); | |
// Serial.print(acc_dist); | |
// Serial.print('-'); | |
// Serial.print(usual_dist); | |
Serial.print('S'); | |
} | |
Serial.println(); | |
acc_dist = (acc_dist * 10 + dist)/11; | |
if(millis() - last_hit < 6000){ | |
digitalWrite(A3, LOW); | |
} else { | |
digitalWrite(A3, HIGH); | |
} | |
delay(50); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment