Small code explanation

i followed a tutorial how to make a blind stick, and it's working but i feel stupid without understanding the code, can someone please explain to me the code from a to z i would really appreciate it.

#define trigPin 13

#define echoPin 12

#define motor 7

#define buzzer 6

void setup()
{
pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

pinMode(motor, OUTPUT);

pinMode(buzzer,OUTPUT);

}

void loop()

{

long duration, distance;

digitalWrite(trigPin, LOW); 

delayMicroseconds(2); 

digitalWrite(trigPin, HIGH);

delayMicroseconds(10); 

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance = (duration/2) / 29.1;

if (distance < 70)// This is where checking the distanceyou can change the value

{ 

digitalWrite(motor,HIGH); // When the the distance below 100cm

digitalWrite(buzzer,HIGH);

} else

{

digitalWrite(motor,LOW);// when greater than 100cm

digitalWrite(buzzer,LOW); 

} delay(500);

}

Link for the project http://www.instructables.com/id/Smart-Blind-Stick/

Start by looking at simpler examples first then. Because if this simple sketch with comments is still abracadabra for you it's time to learn it from the start instead of just jumping in :wink:

The problem is, i decided to make a presentation on this project introduction to Arduino, and i already made the stick i thought it was easy.

The defines at the top are so that the rest of the code can use meaningful names instead of magic numbers. Also, it makes things easier to reconfigure later.

The setup() function does the initialisation: configures some i/o pins for their purpose.

The loop function gets repeated over and over:

It puts the trigPin high for 10 microseconds then low again. (Putting it low first does nothing as it was already low from the previous loop.)

The pulseIn() function measures how long it takes for an input pin to go high and then back low, or vice versa.

Then there is some math to convert time into distance. (The 29.1 in there is the speed of sound in microseconds per centimeter.)

Depending on the distance some other pins get put high or low.

Finally, there is a 500ms delay, so it gets repeated twice a second. A bit less, because of the microsecond delays and the time pulseIn() takes.

You can read about all those function in the Language Reference.

If distance is less than 70cm, run motor (vibrator?) and buzzer.

Note: If no echo is received the result is a distance of 0 which will trigger the motor and buzzer.

You could make the device more useful by mapping distance to a PWM value (0-255) and use analogWrite() to control the speed of the motor. The motor would have to be connected to one of the PWM pins. That will give the user more information about obstacles. Removing the 500 mS delay at the bottom of the loop will provide fro more continuous feedback, also good.