HELLO everyone , i hope that someone can help me out concerning programming using mega and ultrasound sensor please that i have not got any of both but i need to prepare the code
i am very new to ardruino but i need to know how can i make a led go on permanently if a cetain distance is reached but not to atop until another far distance is reached to make things clearer i need that the led will go on when distance is lower than 10 cm and stay on until distance is 30 cm then goes off until the lower 10 cm is reached again, then it will go on again and so on,
please help me out ,
Adnan
Here's a good tutorial on a typical ultrasonic sensor. For your convenience I've attached sample code for your particular application, an edited version of the code from the link above:
// Define pins numbers
const int trigPin = 9;
const int echoPin = 10;
const int LED = 13; // Default LED on Arduino Uno
// Define variables
long duration;
int distance;
bool distanceFlag = false;
void setup() {
Serial.begin(9600); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW); // Initialize LED to be off
}
void loop() {
// Clear trig pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set trig pin to HIGH for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate and print distance to serial monitor
distance= duration*0.034/2; // Distance in cm
Serial.print("Distance: ");
Serial.println(distance);
if (distance > 30) {
digitalWrite(LED, LOW);
distanceFlag = false; // Reset flag
}
else if (distance < 10) {
digitalWrite(LED, HIGH);
distanceFlag = true; // This flag indicates the distance was lower than 10cm
}
else if (distanceFlag && distance >= 10 && distance <= 30) {
digitalWrite(LED, HIGH); // Keep LED on in between 10 and 30 cm but only if the flag was set before
}
}
thank you very much my friend,
I will try this code one i get my mega board and ultrasonic sensor,
BR,
AdnanSamra