Arduino – Blinking LED

Arduino – Blinking LED ”; Previous Next LEDs are small, powerful lights that are used in many different applications. To start, we will work on blinking an LED, the Hello World of microcontrollers. It is as simple as turning a light on and off. Establishing this important baseline will give you a solid foundation as we work towards experiments that are more complex. Components Required You will need the following components − 1 × Breadboard 1 × Arduino Uno R3 1 × LED 1 × 330Ω Resistor 2 × Jumper Procedure Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below. Note − To find out the polarity of an LED, look at it closely. The shorter of the two legs, towards the flat edge of the bulb indicates the negative terminal. Components like resistors need to have their terminals bent into 90° angles in order to fit the breadboard sockets properly. You can also cut the terminals shorter. Sketch Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the new sketch File by clicking New. Arduino Code /* Blink Turns on an LED on for one second, then off for one second, repeatedly. */ // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin 13 as an output. pinMode(2, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(2, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } Code to Note pinMode(2, OUTPUT) − Before you can use one of Arduino’s pins, you need to tell Arduino Uno R3 whether it is an INPUT or OUTPUT. We use a built-in “function” called pinMode() to do this. digitalWrite(2, HIGH) − When you are using a pin as an OUTPUT, you can command it to be HIGH (output 5 volts), or LOW (output 0 volts). Result You should see your LED turn on and off. If the required output is not seen, make sure you have assembled the circuit correctly, and verified and uploaded the code to your board. Print Page Previous Next Advertisements ”;

Arduino – Reading Analog Voltage

Arduino – Reading Analog Voltage ”; Previous Next This example will show you how to read an analog input on analog pin 0. The input is converted from analogRead() into voltage, and printed out to the serial monitor of the Arduino Software (IDE). Components Required You will need the following components − 1 × Breadboard 1 × Arduino Uno R3 1 × 5K variable resistor (potentiometer) 2 × Jumper Procedure Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below. Potentiometer A potentiometer (or pot) is a simple electro-mechanical transducer. It converts rotary or linear motion from the input operator into a change of resistance. This change is (or can be) used to control anything from the volume of a hi-fi system to the direction of a huge container ship. The pot as we know it was originally known as a rheostat (essentially a variable wirewound resistor). The variety of available pots is now quite astonishing, and it can be very difficult for the beginner (in particular) to work out which type is suitable for a given task. A few different pot types, which can all be used for the same task makes the job harder. The image on the left shows the standard schematic symbol of a pot. The image on the right is the potentiometer. Sketch Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. Arduino Code /* ReadAnalogVoltage Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor. Graphical representation is available using serial plotter (Tools > Serial Plotter menu) Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. */ // the setup routine runs once when you press reset: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); // Convert the analog reading (which goes from 0 – 1023) to a voltage (0 – 5V): float voltage = sensorValue * (5.0 / 1023.0); // print out the value you read: Serial.println(voltage); } Code to Note In the program or sketch given below, the first thing that you do in the setup function is begin serial communications, at 9600 bits per second, between your board and your computer with the line − Serial.begin(9600); In the main loop of your code, you need to establish a variable to store the resistance value (which will be between 0 and 1023, perfect for an int datatype) coming from your potentiometer − int sensorValue = analogRead(A0); To change the values from 0-1023 to a range that corresponds to the voltage, the pin is reading, you need to create another variable, a float, and do a little calculation. To scale the numbers between 0.0 and 5.0, divide 5.0 by 1023.0 and multiply that by sensorValue − float voltage= sensorValue * (5.0 / 1023.0); Finally, you need to print this information to your serial window. You can do this with the command Serial.println() in your last line of code − Serial.println(voltage) Now, open Serial Monitor in the Arduino IDE by clicking the icon on the right side of the top green bar or pressing Ctrl+Shift+M. Result You will see a steady stream of numbers ranging from 0.0 – 5.0. As you turn the pot, the values will change, corresponding to the voltage at pin A0. Print Page Previous Next Advertisements ”;

Arduino – Operators

Arduino – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators − Arithmetic Operators Comparison Operators Boolean Operators Bitwise Operators Compound Operators Arithmetic Operators Assume variable A holds 10 and variable B holds 20 then − Show Example Operator name Operator simple Description Example assignment operator = Stores the value to the right of the equal sign in the variable to the left of the equal sign. A = B addition &plus; Adds two operands A &plus; B will give 30 subtraction – Subtracts second operand from the first A – B will give -10 multiplication * Multiply both operands A * B will give 200 division / Divide numerator by denominator B / A will give 2 modulo % Modulus Operator and remainder of after an integer division B % A will give 0 Comparison Operators Assume variable A holds 10 and variable B holds 20 then − Show Example Operator name Operator simple Description Example equal to == Checks if the value of two operands is equal or not, if yes then condition becomes true. (A == B) is not true not equal to != Checks if the value of two operands is equal or not, if values are not equal then condition becomes true. (A != B) is true less than < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true greater than > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true less than or equal to <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true greater than or equal to >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true Boolean Operators Assume variable A holds 10 and variable B holds 20 then − Show Example Operator name Operator simple Description Example and && Called Logical AND operator. If both the operands are non-zero then then condition becomes true. (A && B) is true or || Called Logical OR Operator. If any of the two operands is non-zero then then condition becomes true. (A || B) is true not ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false Bitwise Operators Assume variable A holds 60 and variable B holds 13 then − Show Example Operator name Operator simple Description Example and & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100 or | Binary OR Operator copies a bit if it exists in either operand (A | B) will give 61 which is 0011 1101 xor ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001 not ~ Binary Ones Complement Operator is unary and has the effect of ”flipping” bits. (~A ) will give -60 which is 1100 0011 shift left << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000 shift right >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 0000 1111 Compound Operators Assume variable A holds 10 and variable B holds 20 then − Show Example Operator name Operator simple Description Example increment &plus;&plus; Increment operator, increases integer value by one A&plus;&plus; will give 11 decrement — Decrement operator, decreases integer value by one A– will give 9 compound addition &plus;= Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand B &plus;= A is equivalent to B = B&plus; A compound subtraction -= Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand B -= A is equivalent to B = B – A compound multiplication *= Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand B*= A is equivalent to B = B* A compound division /= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand B /= A is equivalent to B = B / A compound modulo %= Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand B %= A is equivalent to B = B % A compound bitwise or |= bitwise inclusive OR and assignment operator A |= 2 is same as A = A | 2 compound bitwise and &= Bitwise AND assignment operator A &= 2 is same as A = A & 2 Print Page Previous Next Advertisements ”;

Arduino – Functions

Arduino – Functions ”; Previous Next Functions allow structuring the programs in segments of code to perform individual tasks. The typical case for creating a function is when one needs to perform the same action multiple times in a program. Standardizing code fragments into functions has several advantages − Functions help the programmer stay organized. Often this helps to conceptualize the program. Functions codify one action in one place so that the function only has to be thought about and debugged once. This also reduces chances for errors in modification, if the code needs to be changed. Functions make the whole sketch smaller and more compact because sections of code are reused many times. They make it easier to reuse code in other programs by making it modular, and using functions often makes the code more readable. There are two required functions in an Arduino sketch or a program i.e. setup () and loop(). Other functions must be created outside the brackets of these two functions. The most common syntax to define a function is − Function Declaration A function is declared outside any other functions, above or below the loop function. We can declare the function in two different ways − The first way is just writing the part of the function called a function prototype above the loop function, which consists of − Function return type Function name Function argument type, no need to write the argument name Function prototype must be followed by a semicolon ( ; ). The following example shows the demonstration of the function declaration using the first method. Example int sum_func (int x, int y) // function declaration { int z = 0; z = x+y ; return z; // return the value } void setup () { Statements // group of statements } Void loop () { int result = 0 ; result = Sum_func (5,6) ; // function call } The second part, which is called the function definition or declaration, must be declared below the loop function, which consists of − Function return type Function name Function argument type, here you must add the argument name The function body (statements inside the function executing when the function is called) The following example demonstrates the declaration of function using the second method. Example int sum_func (int , int ) ; // function prototype void setup () { Statements // group of statements } Void loop () { int result = 0 ; result = Sum_func (5,6) ; // function call } int sum_func (int x, int y) // function declaration { int z = 0; z = x+y ; return z; // return the value } The second method just declares the function above the loop function. Print Page Previous Next Advertisements ”;

Arduino – Arrays

Arduino – Arrays ”; Previous Next An array is a consecutive group of memory locations that are of the same type. To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array. The illustration given below shows an integer array called C that contains 11 elements. You refer to any one of these elements by giving the array name followed by the particular element’s position number in square brackets ([]). The position number is more formally called a subscript or index (this number specifies the number of elements from the beginning of the array). The first element has subscript 0 (zero) and is sometimes called the zeros element. Thus, the elements of array C are C[0] (pronounced “C sub zero”), C[1], C[2] and so on. The highest subscript in array C is 10, which is 1 less than the number of elements in the array (11). Array names follow the same conventions as other variable names. A subscript must be an integer or integer expression (using any integral type). If a program uses an expression as a subscript, then the program evaluates the expression to determine the subscript. For example, if we assume that variable a is equal to 5 and that variable b is equal to 6, then the statement adds 2 to array element C[11]. A subscripted array name is an lvalue, it can be used on the left side of an assignment, just as non-array variable names can. Let us examine array C in the given figure, more closely. The name of the entire array is C. Its 11 elements are referred to as C[0] to C[10]. The value of C[0] is -45, the value of C[1] is 6, the value of C[2] is 0, the value of C[7] is 62, and the value of C[10] is 78. To print the sum of the values contained in the first three elements of array C, we would write − Serial.print (C[ 0 ] + C[ 1 ] + C[ 2 ] ); To divide the value of C[6] by 2 and assign the result to the variable x, we would write − x = C[ 6 ] / 2; Declaring Arrays Arrays occupy space in memory. To specify the type of the elements and the number of elements required by an array, use a declaration of the form − type arrayName [ arraySize ] ; The compiler reserves the appropriate amount of memory. (Recall that a declaration, which reserves memory is more properly known as a definition). The arraySize must be an integer constant greater than zero. For example, to tell the compiler to reserve 11 elements for integer array C, use the declaration − int C[ 12 ]; // C is an array of 12 integers Arrays can be declared to contain values of any non-reference data type. For example, an array of type string can be used to store character strings. Examples Using Arrays This section gives many examples that demonstrate how to declare, initialize and manipulate arrays. Example 1: Declaring an Array and using a Loop to Initialize the Array’s Elements The program declares a 10-element integer array n. Lines a–b use a For statement to initialize the array elements to zeros. Like other automatic variables, automatic arrays are not implicitly initialized to zero. The first output statement (line c) displays the column headings for the columns printed in the subsequent for statement (lines d–e), which prints the array in tabular format. Example int n[ 10 ] ; // n is an array of 10 integers void setup () { } void loop () { for ( int i = 0; i < 10; ++i ) // initialize elements of array n to 0 { n[ i ] = 0; // set element at location i to 0 Serial.print (i) ; Serial.print (‘r’) ; } for ( int j = 0; j < 10; ++j ) // output each array element”s value { Serial.print (n[j]) ; Serial.print (‘r’) ; } } Result − It will produce the following result − Element Value 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 Example 2: Initializing an Array in a Declaration with an Initializer List The elements of an array can also be initialized in the array declaration by following the array name with an equal-to sign and a brace-delimited comma-separated list of initializers. The program uses an initializer list to initialize an integer array with 10 values (line a) and prints the array in tabular format (lines b–c). Example // n is an array of 10 integers int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 } ; void setup () { } void loop () { for ( int i = 0; i < 10; ++i ) { Serial.print (i) ; Serial.print (‘r’) ; } for ( int j = 0; j < 10; ++j ) // output each array element”s value { Serial.print (n[j]) ; Serial.print (‘r’) ; } } Result − It will produce the following result − Element Value 0 1 2 3 4 5 6 7 8 9 32 27 64 18 95 14 90 70 60 37 Example 3: Summing the Elements of an Array Often, the elements of an array represent a series of values to be used in a calculation. For example, if the elements of an array represent exam grades, a professor may wish to total the elements of the array and use that sum to calculate the class average for the exam. The program sums the values contained in the 10-element integer array a. Example const int arraySize = 10; // constant variable indicating size of array int a[ arraySize ] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total

Arduino – Trigonometric Functions

Arduino – Trigonometric Functions ”; Previous Next You need to use Trigonometry practically like calculating the distance for moving object or angular speed. Arduino provides traditional trigonometric functions (sin, cos, tan, asin, acos, atan) that can be summarized by writing their prototypes. Math.h contains the trigonometry function”s prototype. Trigonometric Exact Syntax double sin(double x); //returns sine of x radians double cos(double y); //returns cosine of y radians double tan(double x); //returns the tangent of x radians double acos(double x); //returns A, the angle corresponding to cos (A) = x double asin(double x); //returns A, the angle corresponding to sin (A) = x double atan(double x); //returns A, the angle corresponding to tan (A) = x Example double sine = sin(2); // approximately 0.90929737091 double cosine = cos(2); // approximately -0.41614685058 double tangent = tan(2); // approximately -2.18503975868 Print Page Previous Next Advertisements ”;

Arduino – Loops

Arduino – Loops ”; Previous Next Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − C programming language provides the following types of loops to handle looping requirements. S.NO. Loop & Description 1 while loop while loops will loop continuously, and infinitely, until the expression inside the parenthesis, () becomes false. Something must change the tested variable, or the while loop will never exit. 2 do…while loop The do…while loop is similar to the while loop. In the while loop, the loop-continuation condition is tested at the beginning of the loop before performed the body of the loop. 3 for loop A for loop executes statements a predetermined number of times. The control expression for the loop is initialized, tested and manipulated entirely within the for loop parentheses. 4 Nested Loop C language allows you to use one loop inside another loop. The following example illustrates the concept. 5 Infinite loop It is the loop having no terminating condition, so the loop becomes infinite. Print Page Previous Next Advertisements ”;

Arduino – String Object

Arduino – String Object ”; Previous Next The second type of string used in Arduino programming is the String Object. What is an Object? An object is a construct that contains both data and functions. A String object can be created just like a variable and assigned a value or string. The String object contains functions (which are called “methods” in object oriented programming (OOP)) which operate on the string data contained in the String object. The following sketch and explanation will make it clear what an object is and how the String object is used. Example void setup() { String my_str = “This is my string.”; Serial.begin(9600); // (1) print the string Serial.println(my_str); // (2) change the string to upper-case my_str.toUpperCase(); Serial.println(my_str); // (3) overwrite the string my_str = “My new string.”; Serial.println(my_str); // (4) replace a word in the string my_str.replace(“string”, “Arduino sketch”); Serial.println(my_str); // (5) get the length of the string Serial.print(“String length is: “); Serial.println(my_str.length()); } void loop() { } Result This is my string. THIS IS MY STRING. My new string. My new Arduino sketch. String length is: 22 A string object is created and assigned a value (or string) at the top of the sketch. String my_str = “This is my string.” ; This creates a String object with the name my_str and gives it a value of “This is my string.”. This can be compared to creating a variable and assigning a value to it such as an integer − int my_var = 102; The sketch works in the following way. Printing the String The string can be printed to the Serial Monitor window just like a character array string. Convert the String to Upper-case The string object my_str that was created, has a number of functions or methods that can be operated on it. These methods are invoked by using the objects name followed by the dot operator (.) and then the name of the function to use. my_str.toUpperCase(); The toUpperCase() function operates on the string contained in the my_str object which is of type String and converts the string data (or text) that the object contains to upper-case characters. A list of the functions that the String class contains can be found in the Arduino String reference. Technically, String is called a class and is used to create String objects. Overwrite a String The assignment operator is used to assign a new string to the my_str object that replaces the old string my_str = “My new string.” ; The assignment operator cannot be used on character array strings, but works on String objects only. Replacing a Word in the String The replace() function is used to replace the first string passed to it by the second string passed to it. replace() is another function that is built into the String class and so is available to use on the String object my_str. Getting the Length of the String Getting the length of the string is easily done by using length(). In the example sketch, the result returned by length() is passed directly to Serial.println() without using an intermediate variable. When to Use a String Object A String object is much easier to use than a string character array. The object has built-in functions that can perform a number of operations on strings. The main disadvantage of using the String object is that it uses a lot of memory and can quickly use up the Arduinos RAM memory, which may cause Arduino to hang, crash or behave unexpectedly. If a sketch on an Arduino is small and limits the use of objects, then there should be no problems. Character array strings are more difficult to use and you may need to write your own functions to operate on these types of strings. The advantage is that you have control on the size of the string arrays that you make, so you can keep the arrays small to save memory. You need to make sure that you do not write beyond the end of the array bounds with string arrays. The String object does not have this problem and will take care of the string bounds for you, provided there is enough memory for it to operate on. The String object can try to write to memory that does not exist when it runs out of memory, but will never write over the end of the string that it is operating on. Where Strings are Used In this chapter we studied about the strings, how they behave in memory and their operations. The practical uses of strings will be covered in the next part of this course when we study how to get user input from the Serial Monitor window and save the input in a string. Print Page Previous Next Advertisements ”;

Arduino – Interrupts

Arduino – Interrupts ”; Previous Next Interrupts stop the current work of Arduino such that some other work can be done. Suppose you are sitting at home, chatting with someone. Suddenly the telephone rings. You stop chatting, and pick up the telephone to speak to the caller. When you have finished your telephonic conversation, you go back to chatting with the person before the telephone rang. Similarly, you can think of the main routine as chatting to someone, the telephone ringing causes you to stop chatting. The interrupt service routine is the process of talking on the telephone. When the telephone conversation ends, you then go back to your main routine of chatting. This example explains exactly how an interrupt causes a processor to act. The main program is running and performing some function in a circuit. However, when an interrupt occurs the main program halts while another routine is carried out. When this routine finishes, the processor goes back to the main routine again. Important features Here are some important features about interrupts − Interrupts can come from various sources. In this case, we are using a hardware interrupt that is triggered by a state change on one of the digital pins. Most Arduino designs have two hardware interrupts (referred to as “interrupt0” and “interrupt1”) hard-wired to digital I/O pins 2 and 3, respectively. The Arduino Mega has six hardware interrupts including the additional interrupts (“interrupt2” through “interrupt5”) on pins 21, 20, 19, and 18. You can define a routine using a special function called as “Interrupt Service Routine” (usually known as ISR). You can define the routine and specify conditions at the rising edge, falling edge or both. At these specific conditions, the interrupt would be serviced. It is possible to have that function executed automatically, each time an event happens on an input pin. Types of Interrupts There are two types of interrupts − Hardware Interrupts − They occur in response to an external event, such as an external interrupt pin going high or low. Software Interrupts − They occur in response to an instruction sent in software. The only type of interrupt that the “Arduino language” supports is the attachInterrupt() function. Using Interrupts in Arduino Interrupts are very useful in Arduino programs as it helps in solving timing problems. A good application of an interrupt is reading a rotary encoder or observing a user input. Generally, an ISR should be as short and fast as possible. If your sketch uses multiple ISRs, only one can run at a time. Other interrupts will be executed after the current one finishes in an order that depends on the priority they have. Typically, global variables are used to pass data between an ISR and the main program. To make sure variables shared between an ISR and the main program are updated correctly, declare them as volatile. attachInterrupt Statement Syntax attachInterrupt(digitalPinToInterrupt(pin),ISR,mode);//recommended for arduino board attachInterrupt(pin, ISR, mode) ; //recommended Arduino Due, Zero only //argument pin: the pin number //argument ISR: the ISR to call when the interrupt occurs; //this function must take no parameters and return nothing. //This function is sometimes referred to as an interrupt service routine. //argument mode: defines when the interrupt should be triggered. The following three constants are predefined as valid values − LOW to trigger the interrupt whenever the pin is low. CHANGE to trigger the interrupt whenever the pin changes value. FALLING whenever the pin goes from high to low. Example int pin = 2; //define interrupt pin to 2 volatile int state = LOW; // To make sure variables shared between an ISR //the main program are updated correctly,declare them as volatile. void setup() { pinMode(13, OUTPUT); //set pin 13 as output attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE); //interrupt at pin 2 blink ISR when pin to change the value } void loop() { digitalWrite(13, state); //pin 13 equal the state value } void blink() { //ISR function state = !state; //toggle the state when the interrupt occurs } Print Page Previous Next Advertisements ”;

Arduino – Ultrasonic Sensor

Arduino – Ultrasonic Sensor ”; Previous Next The HC-SR04 ultrasonic sensor uses SONAR to determine the distance of an object just like the bats do. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package from 2 cm to 400 cm or 1” to 13 feet. The operation is not affected by sunlight or black material, although acoustically, soft materials like cloth can be difficult to detect. It comes complete with ultrasonic transmitter and receiver module. Technical Specifications Power Supply − &plus;5V DC Quiescent Current − <2mA Working Current − 15mA Effectual Angle − <15° Ranging Distance − 2cm – 400 cm/1″ – 13ft Resolution − 0.3 cm Measuring Angle − 30 degree Components Required You will need the following components − 1 × Breadboard 1 × Arduino Uno R3 1 × ULTRASONIC Sensor (HC-SR04) Procedure Follow the circuit diagram and make the connections as shown in the image given below. Sketch Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. Arduino Code const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor const int echoPin = 6; // Echo Pin of Ultrasonic Sensor void setup() { Serial.begin(9600); // Starting Serial Terminal } void loop() { long duration, inches, cm; pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(10); digitalWrite(pingPin, LOW); pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print(“in, “); Serial.print(cm); Serial.print(“cm”); Serial.println(); delay(100); } long microsecondsToInches(long microseconds) { return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { return microseconds / 29 / 2; } Code to Note The Ultrasonic sensor has four terminals – &plus;5V, Trigger, Echo, and GND connected as follows − Connect the &plus;5V pin to &plus;5v on your Arduino board. Connect Trigger to digital pin 7 on your Arduino board. Connect Echo to digital pin 6 on your Arduino board. Connect GND with GND on Arduino. In our program, we have displayed the distance measured by the sensor in inches and cm via the serial port. Result You will see the distance measured by sensor in inches and cm on Arduino serial monitor. Print Page Previous Next Advertisements ”;