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 – DC Motor

Arduino – DC Motor ”; Previous Next In this chapter, we will interface different types of motors with the Arduino board (UNO) and show you how to connect the motor and drive it from your board. There are three different type of motors − DC motor Servo motor Stepper motor A DC motor (Direct Current motor) is the most common type of motor. DC motors normally have just two leads, one positive and one negative. If you connect these two leads directly to a battery, the motor will rotate. If you switch the leads, the motor will rotate in the opposite direction. Warning − Do not drive the motor directly from Arduino board pins. This may damage the board. Use a driver Circuit or an IC. We will divide this chapter into three parts − Just make your motor spin Control motor speed Control the direction of the spin of DC motor Components Required You will need the following components − 1x Arduino UNO board 1x PN2222 Transistor 1x Small 6V DC Motor 1x 1N4001 diode 1x 270 Ω Resistor Procedure Follow the circuit diagram and make the connections as shown in the image given below. Precautions Take the following precautions while making the connections. First, make sure that the transistor is connected in the right way. The flat side of the transistor should face the Arduino board as shown in the arrangement. Second, the striped end of the diode should be towards the +5V power line according to the arrangement shown in the image. Spin ControlArduino Code int motorPin = 3; void setup() { } void loop() { digitalWrite(motorPin, HIGH); } Code to Note The transistor acts like a switch, controlling the power to the motor. Arduino pin 3 is used to turn the transistor on and off and is given the name ”motorPin” in the sketch. Result Motor will spin in full speed when the Arduino pin number 3 goes high. Motor Speed Control Following is the schematic diagram of a DC motor, connected to the Arduino board. Arduino Code int motorPin = 9; void setup() { pinMode(motorPin, OUTPUT); Serial.begin(9600); while (! Serial); Serial.println(“Speed 0 to 255″); } void loop() { if (Serial.available()) { int speed = Serial.parseInt(); if (speed >= 0 && speed <= 255) { analogWrite(motorPin, speed); } } } Code to Note The transistor acts like a switch, controlling the power of the motor. Arduino pin 3 is used to turn the transistor on and off and is given the name ”motorPin” in the sketch. When the program starts, it prompts you to give the values to control the speed of the motor. You need to enter a value between 0 and 255 in the Serial Monitor. In the ”loop” function, the command ”Serial.parseInt” is used to read the number entered as text in the Serial Monitor and convert it into an ”int”. You can type any number here. The ”if” statement in the next line simply does an analog write with this number, if the number is between 0 and 255. Result The DC motor will spin with different speeds according to the value (0 to 250) received via the serial port. Spin Direction Control To control the direction of the spin of DC motor, without interchanging the leads, you can use a circuit called an H-Bridge. An H-bridge is an electronic circuit that can drive the motor in both directions. H-bridges are used in many different applications. One of the most common application is to control motors in robots. It is called an H-bridge because it uses four transistors connected in such a way that the schematic diagram looks like an “H.” We will be using the L298 H-Bridge IC here. The L298 can control the speed and direction of DC motors and stepper motors, and can control two motors simultaneously. Its current rating is 2A for each motor. At these currents, however, you will need to use heat sinks. Components Required You will need the following components − 1 × L298 bridge IC 1 × DC motor 1 × Arduino UNO 1 × breadboard 10 × jumper wires Procedure Following is the schematic diagram of the DC motor interface to Arduino Uno board. The above diagram shows how to connect the L298 IC to control two motors. There are three input pins for each motor, Input1 (IN1), Input2 (IN2), and Enable1 (EN1) for Motor1 and Input3, Input4, and Enable2 for Motor2. Since we will be controlling only one motor in this example, we will connect the Arduino to IN1 (pin 5), IN2 (pin 7), and Enable1 (pin 6) of the L298 IC. Pins 5 and 7 are digital, i.e. ON or OFF inputs, while pin 6 needs a pulse-width modulated (PWM) signal to control the motor speed. The following table shows which direction the motor will turn based on the digital values of IN1 and IN2. IN1 IN2 Motor Behavior BRAKE 1 FORWARD 1 BACKWARD 1 1 BRAKE Pin IN1 of the IC L298 is connected to pin 8 of Arduino while IN2 is connected to pin 9. These two digital pins of Arduino control the direction of the motor. The EN A pin of IC is connected to the PWM pin 2 of Arduino. This will control the speed of the motor. To set the values of Arduino pins 8 and 9, we have used the digitalWrite() function, and to set the value of pin 2, we have to use the analogWrite() function. Connection Steps Connect 5V and the ground of the IC to 5V and the ground of Arduino, respectively. Connect the motor to pins 2 and 3 of the IC. Connect IN1 of the IC to pin 8 of Arduino. Connect IN2 of the IC to pin 9 of Arduino. Connect EN1 of IC to pin 2 of Arduino. Connect SENS A pin of IC to the ground. Connect Arduino using Arduino USB cable and upload the program to Arduino using Arduino IDE software. Provide

Arduino – Water Detector / Sensor

Arduino – Water Detector / Sensor ”; Previous Next Water sensor brick is designed for water detection, which can be widely used in sensing rainfall, water level, and even liquid leakage. Connecting a water sensor to an Arduino is a great way to detect a leak, spill, flood, rain, etc. It can be used to detect the presence, the level, the volume and/or the absence of water. While this could be used to remind you to water your plants, there is a better Grove sensor for that. The sensor has an array of exposed traces, which read LOW when water is detected. In this chapter, we will connect the water sensor to Digital Pin 8 on Arduino, and will enlist the very handy LED to help identify when the water sensor comes into contact with a source of water. Components Required You will need the following components − 1 × Breadboard 1 × Arduino Uno R3 1 × Water Sensor 1 × led 1 × 330 ohm resistor Procedure Follow the circuit diagram and hook up the components on the breadboard 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 on New. Arduino Code #define Grove_Water_Sensor 8 // Attach Water sensor to Arduino Digital Pin 8 #define LED 9 // Attach an LED to Digital Pin 9 (or use onboard LED) void setup() { pinMode(Grove_Water_Sensor, INPUT); // The Water Sensor is an Input pinMode(LED, OUTPUT); // The LED is an Output } void loop() { /* The water sensor will switch LOW when water is detected. Get the Arduino to illuminate the LED and activate the buzzer when water is detected, and switch both off when no water is present */ if( digitalRead(Grove_Water_Sensor) == LOW) { digitalWrite(LED,HIGH); }else { digitalWrite(LED,LOW); } } Code to Note Water sensor has three terminals – S, Vout(&plus;), and GND (-). Connect the sensor as follows − Connect the &plus;Vs to &plus;5v on your Arduino board. Connect S to digital pin number 8 on Arduino board. Connect GND with GND on Arduino. Connect LED to digital pin number 9 in Arduino board. When the sensor detects water, pin 8 on Arduino becomes LOW and then the LED on Arduino is turned ON. Result You will see the indication LED turn ON when the sensor detects water. Print Page Previous Next Advertisements ”;

Arduino – Math Library

Arduino – Math Library ”; Previous Next The Arduino Math library (math.h) includes a number of useful mathematical functions for manipulating floating-point numbers. Library Macros Following are the macros defined in the header math.h − Given below is the list of macros defined in the header math.h Macros Value Description M_E 2.7182818284590452354 The constant e. M_LOG2E 1.4426950408889634074 /* log_2 e */ The logarithm of the e to base 2 M_1_PI 0.31830988618379067154 /* 1/pi */ The constant 1/pi M_2_PI 0.63661977236758134308 /* 2/pi */ The constant 2/pi M_2_SQRTPI 1.12837916709551257390 /* 2/sqrt(pi) */ The constant 2/sqrt(pi) M_LN10 2.30258509299404568402 /* log_e 10 */ The natural logarithm of the 10 M_LN2 0.69314718055994530942 /* log_e 2 */ The natural logarithm of the 2 M_LOG10E 0.43429448190325182765 /* log_10 e */ The logarithm of the e to base 10 M_PI 3.14159265358979323846 /* pi */ The constant pi M_PI_2 3.3V1.57079632679489661923 /* pi/2 */ The constant pi/2 M_PI_4 0.78539816339744830962 /* pi/4 */ The constant pi/4 M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */ The constant 1/sqrt(2) M_SQRT2 1.41421356237309504880 /* sqrt(2) */ The square root of 2 acosf – The alias for acos() function asinf – The alias for asin() function atan2f – The alias for atan2() function cbrtf – The alias for cbrt() function ceilf – The alias for ceil() function copysignf – The alias for copysign() function coshf – The alias for cosh() function expf – The alias for exp() function fabsf – The alias for fabs() function fdimf – The alias for fdim() function floorf – The alias for floor() function fmaxf – The alias for fmax() function fminf – The alias for fmin() function fmodf – The alias for fmod() function frexpf – The alias for frexp() function hypotf – The alias for hypot() function INFINITY – INFINITY constant isfinitef – The alias for isfinite() function isinff – The alias for isinf() function isnanf – The alias for isnan() function ldexpf – The alias for ldexp() function log10f – The alias for log10() function logf – The alias for log() function lrintf – The alias for lrint() function lroundf – The alias for lround() function Library Functions The following functions are defined in the header math.h − Given below is the list of functions are defined in the header math.h S.No. Library Function & Description 1 double acos (double __x) The acos() function computes the principal value of the arc cosine of __x. The returned value is in the range [0, pi] radians. A domain error occurs for arguments not in the range [-1, +1]. 2 double asin (double __x) The asin() function computes the principal value of the arc sine of __x. The returned value is in the range [-pi/2, pi/2] radians. A domain error occurs for arguments not in the range [-1, +1]. 3 double atan (double __x) The atan() function computes the principal value of the arc tangent of __x. The returned value is in the range [-pi/2, pi/2] radians. 4 double atan2 (double __y, double __x) The atan2() function computes the principal value of the arc tangent of __y / __x, using the signs of both arguments to determine the quadrant of the return value. The returned value is in the range [-pi, +pi] radians. 5 double cbrt (double __x) The cbrt() function returns the cube root of __x. 6 double ceil (double __x) The ceil() function returns the smallest integral value greater than or equal to __x, expressed as a floating-point number. 7 static double copysign (double __x, double __y) The copysign() function returns __x but with the sign of __y. They work even if __x or __y are NaN or zero. 8 double cos(double __x) The cos() function returns the cosine of __x, measured in radians. 9 double cosh (double __x) The cosh() function returns the hyperbolic cosine of __x. 10 double exp (double __x) The exp() function returns the exponential value of __x. 11 double fabs (double __x) The fabs() function computes the absolute value of a floating-point number __x. 12 double fdim (double __x, double __y) The fdim() function returns max(__x – __y, 0). If __x or __y or both are NaN, NaN is returned. 13 double floor (double __x) The floor() function returns the largest integral value less than or equal to __x, expressed as a floating-point number. 14 double fma (double __x, double __y, double __z) The fma() function performs floating-point multiply-add. This is the operation (__x * __y) + __z, but the intermediate result is not rounded to the destination type. This can sometimes improve the precision of a calculation. 15 double fmax (double __x, double __y) The fmax() function returns the greater of the two values __x and __y. If an argument is NaN, the other argument is returned. If both the arguments are NaN, NaN is returned. 16 double fmin (double __x, double __y) The fmin() function returns the lesser of the two values __x and __y. If an argument is NaN, the other argument is returned. If both the arguments are NaN, NaN is returned. 17 double fmod (double __x, double__y) The function fmod() returns the floating-point remainder of __x / __y. 18 double frexp (double __x, int * __pexp) The frexp() function breaks a floating-point number into a normalized fraction and an integral power of 2. It stores the integer in the int object pointed to by __pexp. If __x is a normal float point number, the frexp() function returns the value v, such that v has a magnitude in the interval [1/2, 1) or zero, and __x equals v times 2 raised to the power __pexp. If __x is zero, both parts of the result are zero. If __x is not a finite number, the frexp() returns __x as is and stores 0 by __pexp. Note − This implementation permits a zero pointer as a directive to skip a storing the exponent. 19 double hypot (double __x, double__y) The hypot() function returns sqrt(__x*__x + __y*__y). This is the length of the hypotenuse of a right triangle with sides of length