CIRCUIT
CODE
// The Wave Switch
const int trigPin = 2;
const int echoPin = 4;
int redPin = 6;
void setup()
{
Serial.begin(9600);
}
void loop()
{
long duration, inches, cm;
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
pinMode(redPin, OUTPUT);
duration = pulseIn(echoPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
if (cm > 40 && cm < 80){
digitalWrite(redPin, HIGH);}
if (cm < 40){
digitalWrite(redPin, LOW);}
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds){
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds){
return microseconds / 29 / 2;
}
No comments:
Post a Comment