This is the code for an ultrasonic sensor with buzzer. Someone wanted to get code of two ultrasonic sensors, but unfortunately my other ultrasonic sensor broke so I could experiment with it.
The sketch
int greenled = 3; int redled = 4; int trigPin = 5; int echoPin = 6; void setup() { Serial.begin (9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(greenled, OUTPUT); pinMode(redled, OUTPUT); } void firstsensor(){ // This function is for first sensor. int duration, distance; digitalWrite (trigPin, HIGH); delayMicroseconds (10); digitalWrite (trigPin, LOW); duration = pulseIn (echoPin, HIGH); distance = (duration/2) / 29.1; Serial.print("1st Sensor: "); Serial.print(distance); Serial.print("cm "); if (distance > 10) { // Change the number for long or short distances. digitalWrite (greenled, HIGH); digitalWrite (redled, LOW); } else { digitalWrite (greenled, LOW); digitalWrite (redled, HIGH); } } void loop() { Serial.println("\n"); firstsensor(); delay(100); } |
No comments:
Post a Comment