Arduino – Keyboard Message

Arduino – Keyboard Message ”; Previous Next In this example, when the button is pressed, a text string is sent to the computer as keyboard input. The string reports the number of times the button is pressed. Once you have the Leonardo programmed and wired up, open your favorite text editor to see the results. Warning − When you use the Keyboard.print() command, the Arduino takes over your computer”s keyboard. To ensure you do not lose control of your computer while running a sketch with this function, set up a reliable control system before you call Keyboard.print(). This sketch includes a pushbutton to toggle the keyboard, so that it only runs after the button is pressed. Components Required You will need the following components − 1 × Breadboard 1 × Arduino Leonardo, Micro, or Due board 1 × momentary pushbutton 1 × 10k 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 New. Arduino Code /* Keyboard Message test For the Arduino Leonardo and Micro, Sends a text string when a button is pressed. The circuit: * pushbutton attached from pin 4 to +5V * 10-kilohm resistor attached from pin 4 to ground */ #include “Keyboard.h” const int buttonPin = 4; // input pin for pushbutton int previousButtonState = HIGH; // for checking the state of a pushButton int counter = 0; // button push counter void setup() { pinMode(buttonPin, INPUT); // make the pushButton pin an input: Keyboard.begin(); // initialize control over the keyboard: } void loop() { int buttonState = digitalRead(buttonPin); // read the pushbutton: if ((buttonState != previousButtonState)&& (buttonState == HIGH)) // and it”s currently pressed: { // increment the button counter counter++; // type out a message Keyboard.print(“You pressed the button “); Keyboard.print(counter); Keyboard.println(” times.”); } // save the current button state for comparison next time: previousButtonState = buttonState; } Code to Note Attach one terminal of the pushbutton to pin 4 on Arduino. Attach the other pin to 5V. Use the resistor as a pull-down, providing a reference to the ground, by attaching it from pin 4 to the ground. Once you have programmed your board, unplug the USB cable, open a text editor and put the text cursor in the typing area. Connect the board to your computer through USB again and press the button to write in the document. Result By using any text editor, it will display the text sent via Arduino. Print Page Previous Next Advertisements ”;

Arduino – Wireless Communication

Arduino – Wireless Communication ”; Previous Next The wireless transmitter and receiver modules work at 315 Mhz. They can easily fit into a breadboard and work well with microcontrollers to create a very simple wireless data link. With one pair of transmitter and receiver, the modules will only work communicating data one-way, however, you would need two pairs (of different frequencies) to act as a transmitter/receiver pair. Note − These modules are indiscriminate and receive a fair amount of noise. Both the transmitter and receiver work at common frequencies and do not have IDs. Receiver Module Specifications Product Model − MX-05V Operating voltage − DC5V Quiescent Current − 4mA Receiving frequency − 315Mhz Receiver sensitivity − -105DB Size − 30 * 14 * 7mm Transmitter Module Specifications Product Model − MX-FS-03V Launch distance − 20-200 meters (different voltage, different results) Operating voltage − 3.5-12V Dimensions − 19 * 19mm Operating mode − AM Transfer rate − 4KB / S Transmitting power − 10mW Transmitting frequency − 315Mhz An external antenna − 25cm ordinary multi-core or single-core line Pinout from left → right − (DATA; VCC; GND) Components Required You will need the following components − 2 × Arduino UNO board 1 × Rf link transmitter 1 × Rf link receiver 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. Note − You must include the keypad library in your Arduino library file. Copy and paste the VirtualWire.lib file in the libraries folder as highlighted in the screenshot given below. Arduino Code for Transmitter //simple Tx on pin D12 #include <VirtualWire.h> char *controller; void setup() { pinMode(13,OUTPUT); vw_set_ptt_inverted(true); vw_set_tx_pin(12); vw_setup(4000);// speed of data transfer Kbps } void loop() { controller=”1″ ; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone digitalWrite(13,1); delay(2000); controller=”0″ ; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone digitalWrite(13,0); delay(2000); } Code to Note This is a simple code. First, it will send character ”1” and after two seconds it will send character ”0” and so on. Arduino Code for Receiver //simple Rx on pin D12 #include <VirtualWire.h> void setup() { vw_set_ptt_inverted(true); // Required for DR3100 vw_set_rx_pin(12); vw_setup(4000); // Bits per sec pinMode(5, OUTPUT); vw_rx_start(); // Start the receiver PLL running } void loop() { uint8_t buf[VW_MAX_MESSAGE_LEN]; uint8_t buflen = VW_MAX_MESSAGE_LEN; if (vw_get_message(buf, &buflen)) // Non-blocking { if(buf[0]==”1”) { digitalWrite(5,1); } if(buf[0]==”0”) { digitalWrite(5,0); } } } Code to Note The LED connected to pin number 5 on the Arduino board is turned ON when character ”1” is received and turned OFF when character ”0” received. Print Page Previous Next Advertisements ”;

Arduino – Mouse Button Control

Arduino – Mouse Button Control ”; Previous Next Using the Mouse library, you can control a computer”s onscreen cursor with an Arduino Leonardo, Micro, or Due. This particular example uses five pushbuttons to move the onscreen cursor. Four of the buttons are directional (up, down, left, right) and one is for a left mouse click. Cursor movement from Arduino is always relative. Every time an input is read, the cursor”s position is updated relative to its current position. Whenever one of the directional buttons is pressed, Arduino will move the mouse, mapping a HIGH input to a range of 5 in the appropriate direction. The fifth button is for controlling a left-click from the mouse. When the button is released, the computer will recognize the event. Components Required You will need the following components − 1 × Breadboard 1 × Arduino Leonardo, Micro or Due board 5 × 10k ohm resistor 5 × momentary pushbuttons Procedure Follow the circuit diagram and hook up the components on the breadboard as shown in the image 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. For this example, you need to use Arduino IDE 1.6.7 Arduino Code /* Button Mouse Control For Leonardo and Due boards only .Controls the mouse from five pushbuttons on an Arduino Leonardo, Micro or Due. Hardware: * 5 pushbuttons attached to D2, D3, D4, D5, D6 The mouse movement is always relative. This sketch reads four pushbuttons, and uses them to set the movement of the mouse. WARNING: When you use the Mouse.move() command, the Arduino takes over your mouse! Make sure you have control before you use the mouse commands. */ #include “Mouse.h” // set pin numbers for the five buttons: const int upButton = 2; const int downButton = 3; const int leftButton = 4; const int rightButton = 5; const int mouseButton = 6; int range = 5; // output range of X or Y movement; affects movement speed int responseDelay = 10; // response delay of the mouse, in ms void setup() { // initialize the buttons” inputs: pinMode(upButton, INPUT); pinMode(downButton, INPUT); pinMode(leftButton, INPUT); pinMode(rightButton, INPUT); pinMode(mouseButton, INPUT); // initialize mouse control: Mouse.begin(); } void loop() { // read the buttons: int upState = digitalRead(upButton); int downState = digitalRead(downButton); int rightState = digitalRead(rightButton); int leftState = digitalRead(leftButton); int clickState = digitalRead(mouseButton); // calculate the movement distance based on the button states: int xDistance = (leftState – rightState) * range; int yDistance = (upState – downState) * range; // if X or Y is non-zero, move: if ((xDistance != 0) || (yDistance != 0)) { Mouse.move(xDistance, yDistance, 0); } // if the mouse button is pressed: if (clickState == HIGH) { // if the mouse is not pressed, press it: if (!Mouse.isPressed(MOUSE_LEFT)) { Mouse.press(MOUSE_LEFT); } } else { // else the mouse button is not pressed: // if the mouse is pressed, release it: if (Mouse.isPressed(MOUSE_LEFT)) { Mouse.release(MOUSE_LEFT); } } // a delay so the mouse does not move too fast: delay(responseDelay); } Code to Note Connect your board to your computer with a micro-USB cable. The buttons are connected to digital inputs from pins 2 to 6. Make sure you use 10k pull-down resistors. Print Page Previous Next Advertisements ”;

Arduino – Inter Integrated Circuit

Arduino – Inter Integrated Circuit ”; Previous Next Inter-integrated circuit (I2C) is a system for serial data exchange between the microcontrollers and specialized integrated circuits of a new generation. It is used when the distance between them is short (receiver and transmitter are usually on the same printed board). Connection is established via two conductors. One is used for data transfer and the other is used for synchronization (clock signal). As seen in the following figure, one device is always a master. It performs addressing of one slave chip before the communication starts. In this way, one microcontroller can communicate with 112 different devices. Baud rate is usually 100 Kb/sec (standard mode) or 10 Kb/sec (slow baud rate mode). Systems with the baud rate of 3.4 Mb/sec have recently appeared. The distance between devices, which communicate over an I2C bus is limited to several meters. Board I2C Pins The I2C bus consists of two signals − SCL and SDA. SCL is the clock signal, and SDA is the data signal. The current bus master always generates the clock signal. Some slave devices may force the clock low at times to delay the master sending more data (or to require more time to prepare data before the master attempts to clock it out). This is known as “clock stretching”. Following are the pins for different Arduino boards − Uno, Pro Mini A4 (SDA), A5 (SCL) Mega, Due 20 (SDA), 21 (SCL) Leonardo, Yun 2 (SDA), 3 (SCL) Arduino I2C We have two modes – master code and slave code – to connect two Arduino boards using I2C. They are − Master Transmitter / Slave Receiver Master Receiver / Slave Transmitter Master Transmitter / Slave Receiver Let us now see what is master transmitter and slave receiver. Master Transmitter The following functions are used to initialize the Wire library and join the I2C bus as a master or slave. This is normally called only once. Wire.begin(address) − Address is the 7-bit slave address in our case as the master is not specified and it will join the bus as a master. Wire.beginTransmission(address) − Begin a transmission to the I2C slave device with the given address. Wire.write(value) − Queues bytes for transmission from a master to slave device (in-between calls to beginTransmission() and endTransmission()). Wire.endTransmission() − Ends a transmission to a slave device that was begun by beginTransmission() and transmits the bytes that were queued by wire.write(). Example #include <Wire.h> //include wire library void setup() //this will run only once { Wire.begin(); // join i2c bus as master } short age = 0; void loop() { Wire.beginTransmission(2); // transmit to device #2 Wire.write(“age is = “); Wire.write(age); // sends one byte Wire.endTransmission(); // stop transmitting delay(1000); } Slave Receiver The following functions are used − Wire.begin(address) − Address is the 7-bit slave address. Wire.onReceive(received data handler) − Function to be called when a slave device receives data from the master. Wire.available() − Returns the number of bytes available for retrieval with Wire.read().This should be called inside the Wire.onReceive() handler. Example #include <Wire.h> //include wire library void setup() { //this will run only once Wire.begin(2); // join i2c bus with address #2 Wire.onReceive(receiveEvent); // call receiveEvent when the master send any thing Serial.begin(9600); // start serial for output to print what we receive } void loop() { delay(250); } //—–this function will execute whenever data is received from master—–// void receiveEvent(int howMany) { while (Wire.available()>1) // loop through all but the last { char c = Wire.read(); // receive byte as a character Serial.print(c); // print the character } } Master Receiver / Slave Transmitter Let us now see what is master receiver and slave transmitter. Master Receiver The Master, is programmed to request, and then read bytes of data that are sent from the uniquely addressed Slave Arduino. The following function is used − Wire.requestFrom(address,number of bytes) − Used by the master to request bytes from a slave device. The bytes may then be retrieved with the functions wire.available() and wire.read() functions. Example #include <Wire.h> //include wire library void setup() { Wire.begin(); // join i2c bus (address optional for master) Serial.begin(9600); // start serial for output } void loop() { Wire.requestFrom(2, 1); // request 1 bytes from slave device #2 while (Wire.available()) // slave may send less than requested { char c = Wire.read(); // receive a byte as character Serial.print(c); // print the character } delay(500); } Slave Transmitter The following function is used. Wire.onRequest(handler) − A function is called when a master requests data from this slave device. Example #include <Wire.h> void setup() { Wire.begin(2); // join i2c bus with address #2 Wire.onRequest(requestEvent); // register event } Byte x = 0; void loop() { delay(100); } // function that executes whenever data is requested by master // this function is registered as an event, see setup() void requestEvent() { Wire.write(x); // respond with message of 1 bytes as expected by master x++; } Print Page Previous Next Advertisements ”;

Arduino – Due & Zero

Arduino – Due & Zero ”; Previous Next The Arduino Due is a microcontroller board based on the Atmel SAM3X8E ARM Cortex-M3 CPU. It is the first Arduino board based on a 32-bit ARM core microcontroller. Important features − It has 54 digital input/output pins (of which 12 can be used as PWM outputs) 12 analog inputs 4 UARTs (hardware serial ports) 84 MHz clock, an USB OTG capable connection 2 DAC (digital to analog), 2 TWI, a power jack, an SPI header, a JTAG header Reset button and an erase button Characteristics of the Arduino Due Board Operating volt CPU speed Analog in/out Digital IO/ PWM EEPROM [KB] SRAM [KB] Flash [KB] USB UART 3.3 Volt 84 Mhz 12/2 54/12 – 96 512 2 micro 4 Communication 4 Hardware UARTs 2 I2C 1 CAN Interface (Automotive communication protocol) 1 SPI 1 Interface JTAG (10 pin) 1 USB Host (like as Leonardo) 1 Programming Port Unlike most Arduino boards, the Arduino Due board runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. Applying voltages higher than 3.3V to any I/O pin could damage the board. The board contains everything needed to support the microcontroller. You can simply connect it to a computer with a micro-USB cable or power it with an AC-to-DC adapter or battery to get started. The Due is compatible with all Arduino shields that work at 3.3V. Arduino Zero The Zero is a simple and powerful 32-bit extension of the platform established by the UNO. The Zero board expands the family by providing increased performance, enabling a variety of project opportunities for devices, and acts as a great educational tool for learning about 32-bit application development. Important features are − The Zero applications span from smart IoT devices, wearable technology, high-tech automation, to crazy robotics. The board is powered by Atmel’s SAMD21 MCU, which features a 32-bit ARM Cortex® M0+ core. One of its most important features is Atmel’s Embedded Debugger (EDBG), which provides a full debug interface without the need for additional hardware, significantly increasing the ease-of-use for software debugging. EDBG also supports a virtual COM port that can be used for device and bootloader programming. Characteristics of the Arduino Zero board Operating volt CPU speed Analog in/out Digital IO/ PWM EEPROM [KB] SRAM [KB] Flash [KB] USB UART 3.3 Volt 48 Mhz 6/1 14/10 – 32 256 2 micro 2 Unlike most Arduino and Genuino boards, the Zero runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. Applying voltages higher than 3.3V to any I/O pin could damage the board. The board contains everything needed to support the microcontroller. You can simply connect it to a computer with a micro-USB cable or power it with an AC-to-DC adapter or a battery to get started. The Zero is compatible with all the shields that work at 3.3V. Print Page Previous Next Advertisements ”;

Arduino – LED Bar Graph

Arduino – LED Bar Graph ”; Previous Next This example shows you how to read an analog input at analog pin 0, convert the values from analogRead() into voltage, and print it 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 ohm variable resistor (potentiometer) 2 × Jumper 8 × LED or you can use (LED bar graph display as shown in the image below) 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 New. 10 Segment LED Bar Graph These 10-segment bar graph LEDs have many uses. With a compact footprint, simple hookup, they are easy for prototype or finished products. Essentially, they are 10 individual blue LEDs housed together, each with an individual anode and cathode connection. They are also available in yellow, red, and green colors. Note − The pin out on these bar graphs may vary from what is listed on the datasheet. Rotating the device 180 degrees will correct the change, making pin 11 the first pin in line. Arduino Code /* LED bar graph Turns on a series of LEDs based on the value of an analog sensor. This is a simple way to make a bar graph display. Though this graph uses 8LEDs, you can use any number by changing the LED count and the pins in the array. This method can be used to control any series of digital outputs that depends on an analog input. */ // these constants won”t change: const int analogPin = A0; // the pin that the potentiometer is attached to const int ledCount = 8; // the number of LEDs in the bar graph int ledPins[] = {2, 3, 4, 5, 6, 7, 8, 9}; // an array of pin numbers to which LEDs are attached void setup() { // loop over the pin array and set them all to output: for (int thisLed = 0; thisLed < ledCount; thisLed++) { pinMode(ledPins[thisLed], OUTPUT); } } void loop() { // read the potentiometer: int sensorReading = analogRead(analogPin); // map the result to a range from 0 to the number of LEDs: int ledLevel = map(sensorReading, 0, 1023, 0, ledCount); // loop over the LED array: for (int thisLed = 0; thisLed < ledCount; thisLed++) { // if the array element”s index is less than ledLevel, // turn the pin for this element on: if (thisLed < ledLevel) { digitalWrite(ledPins[thisLed], HIGH); }else { // turn off all pins higher than the ledLevel: digitalWrite(ledPins[thisLed], LOW); } } } Code to Note The sketch works like this: first, you read the input. You map the input value to the output range, in this case ten LEDs. Then you set up a for-loop to iterate over the outputs. If the output”s number in the series is lower than the mapped input range, you turn it on. If not, you turn it off. Result You will see the LED turn ON one by one when the value of analog reading increases and turn OFF one by one while the reading is decreasing. Print Page Previous Next Advertisements ”;

Arduino – Time

Arduino – Time ”; Previous Next Arduino provides four different time manipulation functions. They are − S.No. Function & Description 1 delay () function The way the delay() function works is pretty simple. It accepts a single integer (or number) argument. This number represents the time (measured in milliseconds). 2 delayMicroseconds () function The delayMicroseconds() function accepts a single integer (or number) argument. There are a thousand microseconds in a millisecond, and a million microseconds in a second. 3 millis () function This function is used to return the number of milliseconds at the time, the Arduino board begins running the current program. 4 micros () function The micros() function returns the number of microseconds from the time, the Arduino board begins running the current program. This number overflows i.e. goes back to zero after approximately 70 minutes. Print Page Previous Next Advertisements ”;

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 – 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 ”;