Home > database >  Arduino ultrasonic ranging by leds
Arduino ultrasonic ranging by leds

Time:05-24

The code is as follows:

//set the Arduino SR04 connection pin
Const int TrigPin=11;
Const int EchoPin=12;
Unsigned long short;
Int led1=2, led2=3;//led1 is red light, led2 is green
# define Buzzer 3


Void setup ()
{//initializes a serial port communication and connection SR04 pin
Serial.begin(9600);
PinMode (TrigPin, the OUTPUT);
//to detect the pulse width of input pin, need to be set to the input state
PinMode (EchoPin, INPUT);
Serial. Println (" Ultrasonic sensor: ");
PinMode (led1, the OUTPUT);
PinMode (led2, the OUTPUT);//led1 red and led2 green
PinMode (Buzzer, the OUTPUT);
DigitalWrite (Buzzer, LOW);//buzzer
}


Void loop ()
{
//create a 10 us high pulse to trigger TrigPin
DigitalWrite (TrigPin, LOW);
DelayMicroseconds (2);
DigitalWrite (TrigPin, HIGH);
DelayMicroseconds (10);
DigitalWrite (TrigPin, LOW);
//testing pulse width, and calculate the distance
//delayMicroseconds (2);
Short=pulseIn (EchoPin, HIGH)/58.00;
Serial. Print (short);
Serial. Print (" cm ");
Serial.println();
Delay (200);
If (distance<=50) {
DigitalWrite (led1, HIGH);
DigitalWrite (Buzzer, HIGH);
} else {
DigitalWrite (led1, LOW);
DigitalWrite (Buzzer, LOW);
}
If (51 & lt;=distance<{
=200)DigitalWrite (led2, HIGH);
} the else digitalWrite (led2, LOW);
Delay (20);
}



Problem: white light has been on, did not achieve the desired effect
  • Related