Arduino – Serial Peripheral Interface

Arduino – Serial Peripheral Interface ”; Previous Next A Serial Peripheral Interface (SPI) bus is a system for serial communication, which uses up to four conductors, commonly three. One conductor is used for data receiving, one for data sending, one for synchronization and one alternatively for selecting a device to communicate with. It is a full duplex connection, which means that the data is sent and received simultaneously. The maximum baud rate is higher than that in the I2C communication system. Board SPI Pins SPI uses the following four wires − SCK − This is the serial clock driven by the master. MOSI − This is the master output / slave input driven by the master. MISO − This is the master input / slave output driven by the master. SS − This is the slave-selection wire. The following functions are used. You have to include the SPI.h. SPI.begin() − Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high. SPI.setClockDivider(divider) − To set the SPI clock divider relative to the system clock. On AVR based boards, the dividers available are 2, 4, 8, 16, 32, 64 or 128. The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter of the frequency of the system clock (5 Mhz for the boards at 20 MHz). Divider − It could be (SPI_CLOCK_DIV2, SPI_CLOCK_DIV4, SPI_CLOCK_DIV8, SPI_CLOCK_DIV16, SPI_CLOCK_DIV32, SPI_CLOCK_DIV64, SPI_CLOCK_DIV128). SPI.transfer(val) − SPI transfer is based on a simultaneous send and receive: the received data is returned in receivedVal. SPI.beginTransaction(SPISettings(speedMaximum, dataOrder, dataMode)) − speedMaximum is the clock, dataOrder(MSBFIRST or LSBFIRST), dataMode(SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3). We have four modes of operation in SPI as follows − Mode 0 (the default) − Clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0). Mode 1 − Clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1). Mode 2 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0). Mode 3 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1). SPI.attachInterrupt(handler) − Function to be called when a slave device receives data from the master. Now, we will connect two Arduino UNO boards together; one as a master and the other as a slave. (SS) : pin 10 (MOSI) : pin 11 (MISO) : pin 12 (SCK) : pin 13 The ground is common. Following is the diagrammatic representation of the connection between both the boards − Let us see examples of SPI as Master and SPI as Slave. SPI as MASTER Example #include <SPI.h> void setup (void) { Serial.begin(115200); //set baud rate to 115200 for usart digitalWrite(SS, HIGH); // disable Slave Select SPI.begin (); SPI.setClockDivider(SPI_CLOCK_DIV8);//divide the clock by 8 } void loop (void) { char c; digitalWrite(SS, LOW); // enable Slave Select // send test string for (const char * p = “Hello, world!r” ; c = *p; p++) { SPI.transfer (c); Serial.print(c); } digitalWrite(SS, HIGH); // disable Slave Select delay(2000); } SPI as SLAVE Example #include <SPI.h> char buff [50]; volatile byte indx; volatile boolean process; void setup (void) { Serial.begin (115200); pinMode(MISO, OUTPUT); // have to send on master in so it set as output SPCR |= _BV(SPE); // turn on SPI in slave mode indx = 0; // buffer empty process = false; SPI.attachInterrupt(); // turn on interrupt } ISR (SPI_STC_vect) // SPI interrupt routine { byte c = SPDR; // read byte from SPI Data Register if (indx < sizeof buff) { buff [indx++] = c; // save data in the next index in the array buff if (c == ”r”) //check for the end of the word process = true; } } void loop (void) { if (process) { process = false; //reset the process Serial.println (buff); //print the array on serial monitor indx= 0; //reset button to zero } } Print Page Previous Next Advertisements ”;

Arduino – Fading LED

Arduino – Fading LED ”; Previous Next This example demonstrates the use of the analogWrite() function in fading an LED off. AnalogWrite uses pulse width modulation (PWM), turning a digital pin on and off very quickly with different ratios between on and off, to create a fading effect. 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 /* Fade This example shows how to fade an LED on pin 9 using the analogWrite() function. The analogWrite() function uses PWM, so if you want to change the pin you”re using, be sure to use another PWM capable pin. On most Arduino, the PWM pins are identified with a “~” sign, like ~3, ~5, ~6, ~9, ~10 and ~11. */ int led = 9; // the PWM pin the LED is attached to int brightness = 0; // how bright the LED is int fadeAmount = 5; // how many points to fade the LED by // the setup routine runs once when you press reset: void setup() { // declare pin 9 to be an output: pinMode(led, OUTPUT); } // the loop routine runs over and over again forever: void loop() { // set the brightness of pin 9: analogWrite(led, brightness); // change the brightness for next time through the loop: brightness = brightness + fadeAmount; // reverse the direction of the fading at the ends of the fade: if (brightness == 0 || brightness == 255) { fadeAmount = -fadeAmount ; } // wait for 30 milliseconds to see the dimming effect delay(300); } Code to Note After declaring pin 9 as your LED pin, there is nothing to do in the setup() function of your code. The analogWrite() function that you will be using in the main loop of your code requires two arguments: One, telling the function which pin to write to and the other indicating what PWM value to write. In order to fade the LED off and on, gradually increase the PWM values from 0 (all the way off) to 255 (all the way on), and then back to 0, to complete the cycle. In the sketch given above, the PWM value is set using a variable called brightness. Each time through the loop, it increases by the value of the variable fadeAmount. If brightness is at either extreme of its value (either 0 or 255), then fadeAmount is changed to its negative. In other words, if fadeAmount is 5, then it is set to -5. If it is -5, then it is set to 5. The next time through the loop, this change causes brightness to change direction as well. analogWrite() can change the PWM value very fast, so the delay at the end of the sketch controls the speed of the fade. Try changing the value of the delay and see how it changes the fading effect. Result You should see your LED brightness change gradually. Print Page Previous Next Advertisements ”;

Arduino – Pulse Width Modulation

Arduino – Pulse Width Modulation ”; Previous Next Pulse Width Modulation or PWM is a common technique used to vary the width of the pulses in a pulse-train. PWM has many applications such as controlling servos and speed controllers, limiting the effective power of motors and LEDs. Basic Principle of PWM Pulse width modulation is basically, a square wave with a varying high and low time. A basic PWM signal is shown in the following figure. There are various terms associated with PWM − On-Time − Duration of time signal is high. Off-Time − Duration of time signal is low. Period − It is represented as the sum of on-time and off-time of PWM signal. Duty Cycle − It is represented as the percentage of time signal that remains on during the period of the PWM signal. Period As shown in the figure, Ton denotes the on-time and Toff denotes the off-time of signal. Period is the sum of both on and off times and is calculated as shown in the following equation − $$T_{total} = T_{on}+T_{off}$$ Duty Cycle Duty cycle is calculated as the on-time of the period of time. Using the period calculated above, duty cycle is calculated as − $$D = frac{T_{on}}{T_{on}+T_{off}} = frac{T_{on}}{T_{total}}$$ analogWrite() Function The analogWrite() function writes an analog value (PWM wave) to a pin. It can be used to light a LED at varying brightness or drive a motor at various speeds. After a call of the analogWrite() function, the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() or a call to digitalRead() or digitalWrite() on the same pin. The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz. On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 – 13 and 44 – 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11. The Arduino Due supports analogWrite() on pins 2 through 13, and pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs. You do not need to call pinMode() to set the pin as an output before calling analogWrite(). analogWrite() Function Syntax analogWrite ( pin , value ) ; value − the duty cycle: between 0 (always off) and 255 (always on). Example int ledPin = 9; // LED connected to digital pin 9 int analogPin = 3; // potentiometer connected to analog pin 3 int val = 0; // variable to store the read value void setup() { pinMode(ledPin, OUTPUT); // sets the pin as output } void loop() { val = analogRead(analogPin); // read the input pin analogWrite(ledPin, (val / 4)); // analogRead values go from 0 to 1023, // analogWrite values from 0 to 255 } Print Page Previous Next Advertisements ”;

Arduino – Connecting Switch

Arduino – Connecting Switch ”; Previous Next Pushbuttons or switches connect two open terminals in a circuit. This example turns on the LED on pin 2 when you press the pushbutton switch connected to pin 8. Pull-down Resistor Pull-down resistors are used in electronic logic circuits to ensure that inputs to Arduino settle at expected logic levels if external devices are disconnected or are at high-impedance. As nothing is connected to an input pin, it does not mean that it is a logical zero. Pull down resistors are connected between the ground and the appropriate pin on the device. An example of a pull-down resistor in a digital circuit is shown in the following figure. A pushbutton switch is connected between the supply voltage and a microcontroller pin. In such a circuit, when the switch is closed, the micro-controller input is at a logical high value, but when the switch is open, the pull-down resistor pulls the input voltage down to the ground (logical zero value), preventing an undefined state at the input. The pull-down resistor must have a larger resistance than the impedance of the logic circuit, or else it might pull the voltage down too much and the input voltage at the pin would remain at a constant logical low value, regardless of the switch position. Components Required You will need the following components − 1 × Arduino UNO board 1 × 330 ohm resistor 1 × 4.7K ohm resistor (pull down) 1 × LED 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 on New. Arduino Code // constants won”t change. They”re used here to // set pin numbers: const int buttonPin = 8; // the number of the pushbutton pin const int ledPin = 2; // the number of the LED pin // variables will change: int buttonState = 0; // variable for reading the pushbutton status void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize the pushbutton pin as an input: pinMode(buttonPin, INPUT); } void loop() { // read the state of the pushbutton value: buttonState = digitalRead(buttonPin); // check if the pushbutton is pressed. // if it is, the buttonState is HIGH: if (buttonState == HIGH) { // turn LED on: digitalWrite(ledPin, HIGH); } else { // turn LED off: digitalWrite(ledPin, LOW); } } Code to Note When the switch is open, (pushbutton is not pressed), there is no connection between the two terminals of the pushbutton, so the pin is connected to the ground (through the pull-down resistor) and we read a LOW. When the switch is closed (pushbutton is pressed), it makes a connection between its two terminals, connecting the pin to 5 volts, so that we read a HIGH. Result LED is turned ON when the pushbutton is pressed and OFF when it is released. Print Page Previous Next Advertisements ”;

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