Work1: Array & Loop example
Work2: Using ultrasonic Sensor to control the brightness
code:
const int trigPin = 9; const int echoPin = 10; int ledPin = 6; int buttonPin = 4; bool Status = true; int counter = 0;
long duration; int distance;
void setup() { pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input Serial.begin(9600); // Starts the serial communication pinMode(ledPin, OUTPUT); pinMode(buttonPin,INPUT); }
void loop() {
if(digitalRead(buttonPin) == HIGH){ delay(300); counter++; }
((counter % 2) == 1)? Status = true : Status = false; if(Status) {
// Clears the trigPin digitalWrite(trigPin, LOW); delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin, HIGH);
// Calculating the distance distance= duration*0.034/2;
// Prints the distance on the Serial Monitor Serial.print("Distance: "); Serial.println(distance);
if (distance <= 15){ analogWrite(ledPin, (255-distance*16)); } else { analogWrite(ledPin, 0); }
}
else { Serial.println("OFF"); analogWrite(ledPin,0); }
}
Reflections:
I tried to add a button as a prime controller to the whole system, but it showed that there was some unknown signal disturbing between the button and the ultrasonic sensor (or maybe from my other devices). I think I'll try it again in other spaces and try to find what is disturbing the signal.
Now it seems more interesting to work with Arduino because of so many powerful sensors available. I think the next step is to use it as a tool which helps to realize and refine my design concepts.
References:
https://www.youtube.com/watch?v=WslzsHDYuF0
http://mertarduinotutorial.blogspot.com/2016/11/hc-sr04.html
http://mechstuff.com/connection-interfacing-programming-of-ultrasonic-sensor-hc-sr04/