Arduino LED Projects with code (Best Tutorial 2019)

Arduino LED Projects code

Arduino LED Projects with Arduino LED code Tutorial 2019

In this tutorial, we have to explain the Arduino LED Projects with Arduino LED codeLED, we can start to control multiple LEDs with Arduino. We will start by making a simple traffic light module and then create a pair of LED glasses.


Simple traffic light controller

For making simple traffic light controller firstly we connect red, yellow, and green LEDs with pins 9, 10, and 11 respectively to Arduino LED. In the case of pin 13, it has an in-built pull-up resistor.


Pull up resistors are used to limit the current supplied to an LED. We can't give a current of more than a few mA to LEDs. But, with pin 13, current is itself limited in Arduino by the internal pull-up resistor.


If we want to connect to pins other than 13, we need to add resistors in the Arduino LED circuit. Connect the longer head of the red LED to pin 9 and the shorter head to the resistor and then the resistor to ground. Make a similar connection with the yellow and green LEDs to pins 10 and 11 respectively in Arduino LED.

Arduino LED Projects

Once you have made the connection, write the following code in the editor window of Arduino IDE:

// Initializing LEDs for using it in the code.

// Initializing outside any function so global variable can be accessed throughout the code
int redLed = 9;
int yellowLed = 10;
int greenLed = 11;
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin for red, yellow and green led as an output.
pinMode(redLed, OUTPUT); pinMode(yellowLed, OUTPUT); pinMode(greenLed, OUTPUT);
// the loop function runs over and over again forever
void loop() {
digitalWrite(redLed, HIGH); // Making red led high
digitalWrite(yellowLed, LOW); // Making yellow led low
digitalWrite(greenLed, LOW); // Making green led low
delay(10000); // Wait for 10 seconds (10000
digitalWrite(redLed, LOW);
// Making red led low
digitalWrite(yellowLed, LOW); // Making yellow led low
digitalWrite(greenLed, HIGH); // Making green led high
delay(10000); // Wait for 10 seconds (10000
digitalWrite(redLed, LOW); // Making red led low
digitalWrite(yellowLed, HIGH); // Making yellow led high
digitalWrite(greenLed, LOW); // Making green led low
delay(3000); // Wait for 3 seconds 3000


Arduino LED Projects

In the preceding code, you can see that it is much the same as the "Hello World" program, except here we are controlling multiple LEDs. Here, we are initializing the variables as integers and using that same variable throughout the code.


So, in the future, if we need to change an Arduino pin, we just have to make a change in one place, instead of making changes at multiple places in the code. It is a good practice to use variables instead of directly using pin numbers in the code.


In the setup function, we are setting pins as OUTPUT. If we don't initialize the port to either INPUT or OUTPUT, a port might be in an indefinite state. So, it will give a random output.

We have completed the code for one direction of our traffic light. Similarly, you can create your code for the other remaining directions.


LED fading

Arduino LED

You can fade out and fade in the light of an LED using Arduino's analogWrite(pin, value) function. Before we get into using the analogWrite() function, we will understand the concept behind the analogWrite() function. To create an analog signal, Arduino uses a technique called Pulse width modulation (PWM).


Pulse width modulation (PWM)

PWM is a technique for getting an analog signal using digital means. By varying the duty cycle (duty cycle is the percentage of a period when a signal is active.), we can mimic an "average" analog voltage.


As you can see in the following image, when we want medium voltage, we will keep the duty cycle at 50%. Similarly, if we want to achieve low voltage and high voltage, we will keep the duty cycle like 10% and 90% respectively. In this application, PWM is the process to control the power sent to the LED:


Using PWM on Arduino

Arduino UNO has 14 digital I/O pins. As mentioned in Blog Getting Started with Arduino and LEDs, we can use six pins (3, 5, 6, 9, 10, and 11) as PWM pins. These pins are controlled by on-chip timers, which toggle the pins automatically at a rate of about 490 Hz. As discussed earlier, we will be using the analogWrite() function.


In the following figure, the analogWrite() function takes the pin number and pin value as its parameter. Here, as you can see in the image, the pin value can be between 0 and 255, with the duty cycle mapped to 0% and 100%:


Connect the anode (longer head) of the LED to pin 11 (PWM pin) through a 220 Ω resistor and the cathode (shorter head) to ground, and write the following code in your editor window:

int led = 11; // the pin that the LED is attached to

int brightness = 0; // how bright the LED is
int steps = 5; // how many points to fade the LED by
void setup() {
pinMode(led, OUTPUT);
void loop() {
// Setting brightness of LED: analogWrite(led, brightness);
// change the brightness for next time through the loop: brightness = brightness + steps;
// When brightness value reaches either 0 or 255, reverse direction of fading
if (brightness == 0 || brightness == 255) { steps = -steps ;
// wait for 30 milliseconds to see the dimming effect


We are using pin 11(PWM pin) for fading the LED. We are storing the brightness of the LED in variable brightness. Initially, we are setting 0 brightness to the LED. When the loop function runs again, we are incrementing the value by steps of 5.


As in the analogWrite() function, we can set the value between 0 and 255. Once brightness reaches a maximum, we are decrementing the value. Similarly, once brightness reaches 0, we start incrementing brightness in steps of 1. To see the dimming effect, we are putting a delay of 30 milliseconds at the end of the code.


LED Glasses


In this blog, we will look at how to create a pair of LED glasses.

The materials needed are:

  • 30 LEDs (5 mm) in any color
  • A trinket board or an Arduino micro board
  • An FTDI to USB converter
  • Wires
  • A soldering iron
  • A 3-5V lithium battery (the smaller the better)
  • A JST female connector
  • 3 mm MDF
  • 220Ω resistors


Making the glasses

You can make your glasses out of anything you like and it might even be possible to modify a pair of existing sunglasses if they are big enough. In the figure, you will find the design of the glasses with measurements. Remember that these measurements might need to be modified so that the glasses it your particular head size.


The design of the glasses is very simple yet its the purpose. The design consists of three main pieces, the front, and two side frames. The two smaller pieces are used for added support when connecting the frames to the front panel.


The frames can be simply glued to the corners of the front panel, while the two small pieces are glued to the inside corners on each end.


The design template can be used to cut the pieces out from any material you like, but I recommend a sturdy material of at least 3 mm thickness. Plastic materials would also work for this project, or you could even make the frames out of cardboard, which can easily be cut by hand.


The glasses presented in this blog were cut from 3 mm MDF using a laser cutter. I don't expect most readers to have their own laser cutter, but many bigger cities today have something called hackerspaces or Fab Labs, and some even have them in their city's libraries.


The concept of Fab Labs was developed by the Massachusetts Institute of Technology, building on the idea of hackerspaces, which are locations that offer access to different fabrication tools and equipment where different people come to work on projects.


Hackerspaces are usually a place where people interested in electronics and programming meet to share ideas and work on projects. Fab Labs are more oriented toward fabrication, not a just digital entity, and are open to the public.


If you haven't checked already, I suggest you investigate whether there is a hackerspace or Fab Labs close by since you now have the perfect excuse to head over for a visit.


 If you choose to modify the design, remember to keep the size of the holes at 5 mm since this is the size of the LEDs we will be using. You can swap these LEDs for the smaller 3 mm ones if you like, but I would not recommend LEDs bigger than 5 mm since these might complicate the design.


Entering the matrix


An LED matrix is also known as a diode matrix, referring to the LED's one-directional polarity. An LED matrix is a two-dimensional grid with an LED connected to each intersection where a row crosses a column. The columns and rows are isolated from one another in order for the matrix to work. In electronics, this is also known as multiplexing.


The figure illustrates the entire schematic of all the connections. To the right, you will find the matrix layout. All the negative sides of the LEDs are connected in rows and all the positive sides of the LEDs are connected in columns.


When power is applied to one of the columns, and a ground connection is opened up on the negative rows, only one LED will light up.


As you might have noticed, we have connected part of the matrix to the analog pins. Since there are not enough digital pins, we will use some of the analog pins instead. The analog pins can be operated as digital pins and their numbering continues on from pin 13. In other words, analog pin A1 is the same as digital pin 14, and so on.


As I said before, the current can only pass through an LED in one direction, a fact we are using to our benefit while creating the LED matrix, giving us the possibility of controlling many LEDs with fewer pins.


If we did not connect everything in a matrix, we would need 30 pins in order to control all the LEDs separately. The downside of using a matrix configuration is that we can only control one LED at a time.


However, we will take advantage of another phenomenon called POV (persistence of vision). POV is a term used to describe an optical illusion where multiple images blend into one image in the mind of the beholder. The brain can only interpret about 25 discreet images per second; any more than that and the images start to blend together.


Arduino is fast, even faster than the human eye, so we will use this speed to our advantage in order to give the impression of lighting up many LEDs at the same time.


As I said, we can't technically light up more than one LED at once in the matrix but we can switch between them so fast that the human eye will perceive it as more than one LED being on. But before we get to this part, we need to connect everything, and this means it is time to turn on the soldering iron.


Before we start soldering, we need to place the LEDs in the right order. A good idea is to check that all your LEDs work before soldering them. By connecting the LEDs one by one to a 3.3V coin cell battery, or using the power that goes from your Arduino to a breadboard, you can easily do this. If you are using a breadboard, don't forget to add a 220Ω resistor.


If you cut 5 mm holes, the LEDs should it nicely. If they are a bit lose don't worry, as once they are soldered together everything will be held in place. To create the matrix, we need to solder the LEDs into rows and columns.


I have prepared the LEDs for soldering by bending the legs of the LEDs into the desired rows and columns.


All the negative legs (the shorter ones) will be soldered in horizontal lines, and then the positive legs (the longer ones) will be soldered in vertical lines. Make sure that you bend the positive lines over the negative lines so they do not come into contact with one another.


If they do, the matrix will not work as it is supposed to. If you want, you can cover up your lines using some tape needed. This is done by placing a small piece of tape in between the legs of the LEDs so they do not touch one another.


Once you are done, we can move on and add the wiring and the resistors that will connect to our Arduino board. The figure shows a close-up of the resistors connected straight to the positive column in the glasses, and the wires connected to the other side of the resistors.

The idea is to place the Arduino board on the inside of either the left or right frame.


Before you cut your wires, measure the distance between the row and the location of the Arduino board where it will be placed on the inside of the side frame. Make sure you add some extra length before you cut them because it is better to have wires that are too long than too short.


Now is also a good time to put the JST female connectorJST connectors are a fairly standard connector for batteries, and in this project, we will be using a very small 3.7V battery with a male JST connector.


You can place the JST connector anywhere you like, but I found a good spot where the front panel meets the frame just under the supporting piece of MDF. Make sure you leave enough space on the back side of the connector to it the power cable that connects to the Arduino board. To keep the JST connector in place, use some glue:


When you have added the wires to all the positive columns, you can add three cables for the negative rows, again ensuring you make them long enough to reach the Arduino board. You don't need resistors on these lines since these will act as our GND channels.


Once you have all the LEDs, resistors, and wires in place, it is time to connect everything to the Arduino board. In this blog, we are using the Trinket board from Adafruit, but you could also use an Arduino micro board, which is very similar in size.


These boards are some of the smallest Arduino boards that offer most of the functionality of a standard Arduino board.


Soldering all the wires in place might be tricky. I started by gluing the board to the inside of the frame and then soldering the wires one by one. I would suggest that you place them where they it best. You can always switch the layout in the code later on. 


Take your time soldering all the wires in place. I admit that even someone with good soldering skills might find this project a bit tricky since it requires some unconventional soldering. I call this type of solder action "soldering" since you usually end up with something that looks like it came from a movie.


Usually, you solder components on a flat surface, but with wearable projects like this one you need to be a bit creative when it comes to soldering things together. Eventually, you will end up with an inside that is as impressive as the outside.


Next, we will move on to the programming sideand this is where we get to see the glasses in action. For the programming part, we will power the glasses via the USB cable, and once we are done we will add a battery, then you will be ready to head out into the night to impress everyone.


[Note: You can free download the complete Office 365 and Office 2019 com setup Guide for here]


Programming the glasses

In order to make the Trinket board so small, the serial to USB conversion is left out from the design. On a regular Arduino board, this conversion is handled by another Atmega chip, and on older versions, this was done by an FTDI (Future Technology Devices International) chip.


Normally, you solder male pins to the end of the Trinket board that connects to the FTDI converter, but in this case, we want to keep the Trinket board as lat as possible and we don't want sharp pins on the inside of the glasses that might hurt your eyes.


So the trick is to just attach the male pin headers to the FTDI converter and hold it in place while programming the Trinket board. Once in a while, there will be glitches in the connection and the upload will fail.


This is probably due to the FTDI not connecting properly to the Trinket board. However, this is not a big problem since you can just start the upload over again while making sure the pins have a good connection.


Now let's make a sketch that checks that all of the LEDs light up. In order to do so, we will loop through the LEDs one by one to see that everything works as it is supposed to.


The Trinket is programmed as a normal Arduino. Uno board, so make sure you select this type in the board menu Upload the following code and check the LEDs in front of the glasses:

/*Collect all the positive columns pins in one array. You need to make sure that these pins correspond to the direction you have placed the columns in the glasses*/
int powerPin[]={
/*Collect all the negative row pins in one array. Again make sure they are added in the same order corresponding to the glasses*/
int gndPins[]={ 10,11,12};
void setup(){
/*In order for the matrix to work we need to be able to control our gnd lines in the matrix. The trick is to use all pins as output. When we turn the gnd pins HIGH we will be able to block the ground connection*/
for(int i=0; i<20;i++){ pinMode(i,OUTPUT); } //Turn all the gnd pins HIGH in order to keep all LEDs off for(int j=0;j<3;j++){ digitalWrite(gndPins[j],HIGH); } } void loop(){ //Run the function looper(); } void looper(){ /*In this function we run through all the LEDs using two for loops starting by opening a gnd connection*/ for(int i=0; i<11;i++){ digitalWrite(powerPin[i],HIGH); //Once a gnd pin is accessible we turn on one of the LEDs for(int j=0;j<3;j++){ digitalWrite(gndPins[j],LOW); delay(50); digitalWrite(gndPins[j],HIGH); delay(50); } digitalWrite(powerPin[i],LOW); } //Loop everything backwards for(int i=10; i>=0;i--){
for(int j=3;j>=0;j--){


In this example sketch, we are implementing a trick in order to be able to control the ground connections. If we connected the negative rows of the matrix straight to GND we would not be able to control the separate LEDs.


The trick is to use normal pins as outputs. When a pin is LOW, it connects to ground, which we can use to light up our LEDs in the matrix.


But once it turns to HIGH, we block the connection to the ground. So now we can control each LED individually by turning one of the positive columns HIGH and one of the negatives rows LOW.


You will need to make sure that your pin declarations line up with the actual physical layout in your glasses or else looping through them could get very hard. As you can see in the schematic in Figure, the columns are connected after one another to the digital pins.


Making a pattern


In the next code example, we will implement some pattern designs. These patterns are stored in arrays that correspond to the layout of the LEDs in the glasses. We can draw our patterns in code and later loop through the array and activate the LEDs.


When the code is formatted as it is in the next sketch, we get a visual repetition of the pattern. A 0 in the array represents a turned off LED in the same position in the matrix and a 1 represents an LED that is turned HIGH:


/*Collect all the positive columns pins in one array. You need to make sure that these pins correspond to the direction you have placed the columns in the glasses*/
int powerPin[]={19,18,17,16,14,9,8,6,5,4,3};
/*Collect all the negative row pins in one array. Again make sure they are added in the same order corresponding to the glasses*/
int gndPins[]={12,11,10};
//This is a two dimensional array that holds the pattern int pattern[3][11] = {
{1,1,1,1,0,0,0,1,1,1,1 },
{0,1,1,0,0,0,0,1,0,0,1 },
{0,1,1,0,0,0,0,1,1,1,1 }
//Variable to store the refresh rate on the led display int refreshRate=200;
void setup(){
//Declare all pins as outputs
for(int i=0; i<20;i++){
//turn all the gnd ports High to keep them blocked for(int j=0;j<3;j++){
void loop(){
//Run the pattern function
/*Function that runs through all the positions in the pattern array*/
void displayPattern()
for (byte x=0; x<3; x++) {
for (byte y=0; y<11; y++) {
int data =pattern[x][y];
//If the data stored in the array is 1 turn on the led if (data==1) {
//If it is something else turn the led off
else {
} } }


This sketch implements a two-dimensional array, which is the same as placing an array into an array. As you can see, we have three arrays, and inside each of those arrays, we have 11 positions in the first two and eight in the last one, which corresponds to the layout of the matrix.


Using the two-dimensional array, we can now fetch the positions of the LEDs similar to x and y coordinates, which is much easier than storing everything in a normal array.


If the values are stored in a normal array, we would need to define where each row ends on our own. This could be done using if sentences to check where the row begins, but using a two-dimensional array makes things much easier and makes for the better-looking code.


Then the arrays run through the display pattern function, which loops through all the positions in the array. Every time it finds a 1 in the array it turns on the LED corresponding to the position in the actual glasses.


It only turns it on for a brief time based on the refresh rate before it turns it off since we can only have one LED on at a time in the LED matrix.


Again, this is where we use the POV phenomenon, looping through all the LEDs very fast so that when we look at the glasses it looks like multiple LEDs are on, though in fact there is only one LED on at a time.


In order to get a better understanding of the code, I would suggest you modify the pattern array by changing which LEDs light up. If you look closely at the array, you might make out that I have tried to spell my initials TO with 1s in the code, which corresponds to LEDs turned on. Try switching the letters for your own initials and upload the code to your glasses.


Finishing the glasses Knight Rider style


For the last code example, we will have a look at how to create an animation.


Animation is a simulation of motion, and in one sense the first code example in this blog is a form of animation. We will build on the same principle in this section. Once you get the hang of the basic concepts, you can start building your own animations, combining the knowledge from the pattern example with the knowledge in this sketch.


In my beginner, Arduino classes, the Knight Rider example is a classic. This example is inspired by the 80s hit show Knight Rider with David Hasselhoff.


To be more precise, the example is inspired by the robotic car featured in the show, which is called Kit. In the front of Kit, there is a small LED display that shows a bouncing light effect. This is the effect we will recreate on the front of the glasses.


The code example is fairly simple and does the same thing as the test sketch, but instead of lighting up only one LED at a time we will light up an entire column. We will move the light column from left to right and once we hit the end of the glasses, we will move the column back again:

int powerPin[]={ 19,18,17,16,14,9,8,6,5,4,3};
int gndPins[]={ 12,11,10};
int refreshRate=200;
void setup(){
for(int i=0; i<20;i++){ pinMode(i,OUTPUT); } // for(int j=0;j<3;j++) { digitalWrite(gndPins[j],HIGH); } } void loop(){ nightrider(); } // void nightrider() { /*Instead of starting to loop through the columns we loop through the row*/ for(int i=0; i<11; i++){ /*Then we loop through the column for(int j=0; j<3; j++){ /*In order to perceive that the column is lit we need to loop it a few times*/ for(int k=0; k<50; k++){ /*Then we light the column digitalWrite(powerPin[i],HIGH); digitalWrite(gndPins[j],LOW); delayMicroseconds(refreshRate); digitalWrite(powerPin[i],LOW); digitalWrite(gndPins[j],HIGH); } } } /*Once we have reached the end of the glasses we do the same thing backward*/ for(int i=11; i>0; i--){
for(int j=3; j>0; j--){
for(int k=0; k<50; k++){
} }


Once your code is done, upload it to the board and enjoy. In order to show off your new glasses, we need to finish up the circuit by attaching the battery to the glasses so you can walk around with them (since being forced to be connected to a USB port at all times might not look as cool).


Any battery between 3-5V will work for this project, and the more amperes the battery has, the longer the glasses will stay on. However, large ampere batteries are also bigger.


The smallest lithium battery I have found is the 3.7V 150mAh battery, which I recommend. There are smaller ones with fewer amperes but this type will still it your glasses and give you enough power to keep the glasses long enough for you to impress a few people.


Before you connect the battery, you need to solder wires from the JST connector to the board. The pins for external power on the Trinket board are marked BAT+ for the positive connection.


Next, to this pin, there is a pin marked with only a G for the ground connection. This connection is connected to the negative side of the JST connector.


In order to figure out which pin is which on the JST connector, check with the battery cables. Usually, these cables are red and black; the red one is the positive and the black one is the ground.


The design of the glasses should leave enough space on the inside of the frames to place a small battery.


I recommend gluing the battery in place using hot glue, but be careful not to heat the battery for too long or it might explode. This might sound scary, but you would need to heat it for some time before it explodes. However, I always recommend caution when combining heat and batteries.


As you might have noticed by now, visibility is limited in these glasses and it has to be fairly dark for the light to be visible, so be careful when using them. You can still look cool while keeping safe.


Project 2 – Remote Controlled TV Backlight

In this blog, we will start by learning the basics of IR LEDs and the basics of IR communication. Once you have learned about programming the IR sensor, we will use it to control a TV backlight using a remote.


Introduction to IR LEDs

In the world of wireless technology, IR (infrared) is one of the most common, inexpensive, and easy to use modes of communication. You might have always wondered how a TV remote works.


A TV remote uses IR LEDs to send out the signal. As the wavelength of light emitted from the IR LED is longer than the visible light, one can't see it with the naked eye.


But, if you look through the camera of your mobile or any other camera, you can see the light beaming when you press any key on the remote. Let's first understand what an IR LED is and what the different applications of an IR LED are.


What is IR LED?

An IR (infrared) LED, also known as an IR (infrared) transmitter, transmits infrared waves in the range of 875 nm to 950 nm. Usually, IR LEDs are made up of gallium arsenide or aluminum gallium arsenide.


The working principle of an IR LED is the same as we mentioned in the previous blogs. The longer lead of the LED is the anode and the shorter one is the cathode, as shown here:


Applications of IR LED / IR communication

Apart from using IR communication in TV remote controls, there are a number of other applications that use IR communication. Infrared light can also be used to transfer data between electronic devices.


Although infrared light is invisible to the eye, digital cameras and other sensors can see this light, so infrared light can be used for many security systems and night vision technology.


Apart from technical uses, the U.S. Food and Drug Administration Department has approved several products with IR LEDs for use in some medical and cosmetic procedures.


IR sensors


We have learned the basics of IR communication and IR LEDs, so now we will move on to making our own IR sensor. 


There are various types of IR sensors, depending upon the application. Proximity sensors, obstruction sensors, and contrast sensors (used in line follower robot) are a few examples which use IR sensors.


Working mechanism


An IR sensor consists of an IR LED (which works as a transmitter) and a photodiode (which works as a receiver) pair. The IR LED emits IR radiation, which, on receiving at the photodiode dictates the output of the sensor.


There are different types of use cases for an IR sensor. For example, if we held an IR LED directly in front of the photodiode, such that almost all the radiation reaches the photodiode, this can be used as a burglar alarm.


So, when anyone interrupts the line of sight between the IR LED and the photodiode, this will break the continuous radiation coming from the IR LED, and we can program it to raise an alarm.


This type of mechanism is also called a direct incidence, as we are not using any reflective surface in between the transmitter and receiver.


Another use case is with indirect incidence, in which we use physics' law of absorption. This means, when the light is directed at a black surface, the black surface will actually absorb the light.


Similarly, when IR radiation is directed at a black surface, the surface will absorb the IR radiation. But, when it is directed toward a white surface, the surface will reflect the IR radiation.


Based on the amount of light received back from the surface, we can detect, if the robot is following a line or not. So, the absorption principle can be used for line follower robot:


As you can see in the preceding image, whenever an obstacle is detected in the path of the IR, some of the IR radiation is reflected back, which, on receipt of the IR waves, gives the output. This type of setup is also useful for detecting any object/obstacle in the path.


Programming a basic IR sensor

After understanding the basic workings of a simple IR sensor, we will learn how to program this sensor. Based on the principle of direct incidence, we will develop a simple burglar alarm. Once you have connected the circuit as shown in the following diagram, upload the following code to Arduino:

int IRTransmitter = 8;
int IRReceiver = A0; //IR Receiver is connected to pin 5
int buzzer = 9; // Buzzer is connected with pin 9.
int output = 0; // Variable to store the value from the IR sensor int ambientLight = 500;
void setup()
void loop()
output = analogRead(IRReceiver);
// If anything comes in between the IR Transmitter and IR receiver
// IR receiver will not give the output. Make an alarm.
if (output < ambientLight)
} }
void makeAlarm(unsigned char time)


In the preceding code, we are continuously making the IR transmitter ON. So, the IR receiver/photodiode will continuously receive an IR signal. Whenever any person tries to break into the house or safe, the IR signal will get interrupted, which in turn will lower the voltage drop across the IR receiver and an alarm will be raised.


Here, based on the conditions around you, you will have to change the value of the ambient light variable in the code.


How to receive data from a TV remote


As we discussed earlier, a TV remote has an IR LED, which transmits IR light with a 38 kHz frequency. So, whenever that radiation is detected at the receiver part of the TV (the control circuit of the TV), we need to filter that signal.

As you can see in the following image when a signal is actually transmitted from the TV remote, it will look like a series of waves:


For filtering the actual signal from a TV remote from ambient noise, we will use TSOP38238 IC. TSOP38238 looks like a transistor, but actually, this device combines an IR sensitive photocell, a 38 kHz bandpass filter, and an automatic gain controller.


Here, the IR sensitive photocell works as an IR receiver (photodiode), and the 38 kHz bandpass filter is required to smooth the received modulated signal.


After passing through the 38 kHz bandpass filter, the output signal will look as shown in the following, which is much cleaner and easier to read:


Also, TSOP38238 is covered in the lead package epoxy frame, which acts as an IR filter. So, the disturbance light (DC light from a tungsten bulb, or a modulated signal from fluorescent lamps) does not reach the photodiode.


This demodulated signal can be directly decoded by any microprocessor (in our case, Arduino). Because of this, apart from the preamplifier, it ignores all other IR light unless it is modulated at a specific frequency (38 kHz).


This IC is as simple as an IC can get with its three pins. There are two power pins and one pin for the output signal:

TSOP38238 can be powered with a supply from 2.5 V to 5.5 V, which makes it suitable for all types of application. Also, it can receive signals from almost all types of remotes.


To start with, we will control a single LED using an IR remote. For that, we will be using the IRRemote library, available at


Once you have downloaded and extracted the code in the libraries folder of Arduino, you will be able to see the examples in the Arduino IDE. We need to record the value of all the buttons for future use.


Connect the first pin of TSOP38238 to pin 11 of Arduino, the second pin to the ground pin of Arduino, and the third pin to the 5 V pin of Arduino. Connect Arduino over USB and try to compile the following code:

#include <IRremote.h>
const int IR_RECEIVER = 11;
IRrecv receiver(IR_RECEIVER);
decode_results buttonPressed;
void setup()
receiver.enableIRIn(); // Start the receiver
void loop()
if (receiver.decode(&buttonPressed))
Serial.println(buttonPressed.value); //Printing values coming from the IR Remote
receiver.resume(); // Receive the next value


In the latest version of Arduino, the IRremote.h library is already installed in the RobotIRremote folder. But, you won't have all the examples available from the downloaded library. So, delete the Robot IRremote library and try to compile the code again.


Once you have deleted the duplicate file, you should be able to successfully compile the code. After uploading the preceding code, open the serial monitor. As we want to control a single LED using a remote, we will have to know the value of the button pressed. So, try noting down the values of all the buttons one after the other.


For example, digit 1 has 54,528 codes for a certain remote. You might have to check for the remote that you have. We will now control the LED by using the IR remote. Along with the IR receiver, we will connect one LED, as shown in the following circuit:


Update the code for controlling the LED, based on your readings from the previous exercise:


#include <IRremote.h>
const int IR_RECEIVER = 11;
IRrecv receiver(IR_RECEIVER);
decode_results buttonPressed;
long int buttonValue = 0;
const long int buttonOne = 54528; //Update value one according to your readings
const long int buttonTwo = 54572; //Update value two according to your readings
int LEDpin = 9;
void setup()
receiver.enableIRIn(); // Start the receiver pinMode(LEDpin,OUTPUT);
void loop()
if (receiver.decode(&buttonPressed))
buttonValue = buttonPressed.value;
switch (buttonValue){
case buttonOne:
case buttonTwo:
Serial.println("Waiting for input. ");
receiver.resume(); // Receive the next value


Now you will be able to control a single LED using the IR remote. In a similar way, you can control anything that you want to control using an IR remote. At the end of this blog, we want to control a TV backlight using an IR remote.


We will develop a TV backlight using an LED strip. So, we will now learn about how to control an LED array.

Microphone for Arduino 2018



Spy Microphone for Arduino

In this blog, we build a spy microphone. using the Arduino, with a simple amplified microphone and an SD card. for building microphone using the Arduino Firstly configure the project and then, recorded an audio file in SD card. Let's dive in!


Hardware and software requirements

Microphone for Arduino

Let's first see what the required components for this project are. As usual, we will use an Arduino Uno board as the 'brain' of the project. Then, we will need a microphone. I used a simple SparkFun electret microphone, which has an amplifier onboard, as shown in the following image:


The most important thing here is that the microphone is amplified. For example, SparkFun is amplified 100 times, making it possible for the Arduino Uno to record usual sound levels (such as voices). Then, you will need a microSD card with an adapter:


You will also need a way to record data on the SD card. There are many ways to do so with Arduino. The easiest, which is the solution that I chose here, is to use a shield. I had an Ethernet Shield available, which is great because it also has an onboard microSD card reader.


You can, of course, use any shield with a microSD card reader or even a microSD reader breakout board. You will also need a breadboard and some jumper wires to make the required connections.


Finally, the following is the list of all the components that we will use in this project:

Microphone Arduino

Arduino Uno (
Arduino Ethernet Shield (
Electret Microphone (
microSD card (
Breadboard (
Jumper wires (


On the software side, you will need a special version of the SD card library called SdFat. We can't use the usual Arduino SD library here as we will do some really fast write operations on the SD card, which can't be handled by the SD library that comes with the Arduino software.

You can download this library from https://github. com/greiman/SdFat.


Using the SD card


The first thing that we are going to do in this project is to test whether we can actually access the SD card. This will ensure that we don't run into SD card-related problems later in the project. This is a picture of the Ethernet Shield that I used, with the microSD card mounted on the right:


Let's now see the code that we will use to test the SD card's functionalities. The following is the complete code for this section:

// Include the SD library #include <SPI.h> #include <SD.h>

// Set up variables using the SD utility library functions: Sd2Card card;
SdVolume volume; SdFile root;
// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = 4;
void setup()
// Open serial communications and wait for port to open: Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
Serial.print("\nInitializing SD card...");
// we'll use the initialization code from the utility libraries
// since we're just testing if the card is working!
if (!card.init(SPI_HALF_SPEED, chipSelect)) {
Serial.println("initialization failed. Things to check:");
Serial.println("* is a card inserted?");
Serial.println("* is your wiring correct?");
Serial.println("* did you change the chipSelect pin to match your
shield or module?");
} else {
Serial.println("Wiring is correct and a card is present.");
} // print the type of card Serial.print("\nCard type: "); switch (card.type()) {
case SD_CARD_TYPE_SD1: Serial.println("SD1"); break;
case SD_CARD_TYPE_SD2: Serial.println("SD2"); break;
case SD_CARD_TYPE_SDHC: Serial.println("SDHC"); break;
// Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
if (!volume.init(card)) {
Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
// print the type and size of the first FAT-type volume uint32_t volumesize;
Serial.print("\nVolume type is FAT"); Serial.println(volume.fatType(), DEC); Serial.println();
volumesize = volume.blocksPerCluster(); // clusters are
collections of blocks
volumesize *= volume.clusterCount(); // we'll have a lot of
volumesize *= 512; // SD card blocks are
always 512 bytes
Serial.print("Volume size (bytes): ");
Serial.print("Volume size (Kbytes): ");
volumesize /= 1024;
Serial.print("Volume size (Mbytes): ");
volumesize /= 1024;
Serial.println("\nFiles found on the card (name, date and size in bytes): ");
// list all files in the card with date and size | LS_DATE | LS_SIZE);
void loop(void) {
This code tests a lot of things on the SD card, such as the file format and available space, and also lists all the files present on the SD card. However, what we are really interested in is to know whether the SD card can be read by the Arduino board. This is done with the following code snippet:
if (!card.init(SPI_HALF_SPEED, chipSelect)) {
Serial.println("initialization failed. Things to check:");
Serial.println("* is a card inserted?");
Serial.println("* is your wiring correct?");
Serial.println("* did you change the chipSelect pin to match your
shield or module?");
} else {
Serial.println("Wiring is correct and a card is present.");

Now, let's test the code. You can simply copy this code and paste it into the Arduino IDE.


Then, upload it to the Arduino Uno board and open the serial monitor. Make sure that the serial speed is set to 115200 bps. This is what you will see. If you can see this, congratulations, your SD card, and card reader are correctly configured and ready to host some spy audio recordings.


Testing the microphone


We are now going to make sure that the microphone is working correctly and especially check whether it can record voice levels, for example. I had a problem when I was testing the prototype of this project with a microphone that wasn't amplified; I just couldn't hear anything on the recording.


The first step is to plug the microphone into the Arduino board. There are 3 pins to connect the microphone: VCC, GND, and AUD. Connect VCC to the Arduino 5V pin, GND to the Arduino GND pin, and AUD to the Arduino analog pin A5.


We are now going to use a very simple sketch to read out the signal from the microphone and print it on the serial monitor:

// Microphone test void setup() {
// Start Serial Serial.begin(115200);
void loop() {
// Read the input on analog pin 5: int sensorValue = analogRead(A5);
// Print out the value you read: Serial.println(sensorValue);
delay(1); // delay in between reads for stability


This sketch, basically, continuously reads the data from the A5 pin, where the microphone is connected, and prints it on the serial monitor.


Now, copy and paste this sketch in the Arduino IDE and upload it to the board. Also, open the serial monitor.

While looking at the serial monitor, speak around the microphone. You should immediately see some variations in the signal that is read by the board. This means that your voice is being recorded by the microphone and the amplification is sufficient for the microphone to record a normal voice level.


In this section, we are going to put everything together and actually build our spy microphone.

The hardware for the project is nearly ready if you followed the previous section. You just need to plug the SD card into the reader again. I also added an LED on pin 7, just to know when the recording is on.


If you want to do the same, you just need an LED and a 330 Ohm resistor. Of course, remove this LED when you actually want to use it as a spy microphone or your project might get noticed.


The schematic to help you out is as follows:

We are now going to see the details of the code for the project. Basically, we want the device to record audio from the microphone for a given amount of time and then stop the recording.


As the code is long and complex, we are only going to see the most important parts here. The first step is to include the SdFat library: #include <SdFat.h>


Then, we will create the instances that are necessary in order to write on the SD card:

SdFat sd;

SdFile rec;
After that, we will define on which pin we want the optional recording LED to be:
const int ledStart = 7;
We will also define a variable for the internal counter of the project:
byte recordingEnded = false;
unsigned int counter;
unsigned int initial_count;
unsigned int maxCount = 10 * 1000; // 10 Seconds
Note that here you will have to modify the maxCount variable according to the time for which you want the device to record. Here, I just used 10 seconds by default as a test.
Then, we will initialize the ADC (Analog-Digital Converter):
After that, we will initialize the SD card and also flash the LED if this is successful:
if (sd.begin(chipSelect, SPI_FULL_SPEED)) {
for (int dloop = 0; dloop < 4; dloop++) {
digitalWrite(ledStart,!digitalRead(ledStart)); delay(100);
Then, we will actually start the recording with the following function:
We will also initialize the counter with the following line of code:
initial_count = millis();
Then, in the loop() function of the sketch, we will update the counter, which helps to keep track of the elapsed time:
counter = millis() - initial_count;
Still in the loop() function, we will actually stop the recording if we reach the maximum amount of time that we defined previously:
if (counter > maxCount && !recordingEnded) { recordingEnded = true;


Note that the whole code for this section can be found in the GitHub repository of the blog at


Recording on the SD card

sd card

In the last section of the blog, we are actually going to test the project and record some audio.


First, copy all the code and paste it into the Arduino IDECompile it and upload it to the Arduino board. Note that, as soon as you do that, the project will start recording the audio. If you have connected the optional LED on pin 7, the LED should also be on during the recording phase.


You can now talk a bit or play your favorite song just to make sure that actual audio is being recorded by the microphone. Then, after the amount of time defined in the code, stop the project by disconnecting the power. Then, remove the SD card and insert it into your computer.


On your computer, navigate to the SD card and you will see that one file was recorded: You can now simply open this file with your favorite audio player and listen to what was just recorded.


I, for example, opened it with the free audio editing software, Audacity, to see how the waveform looked like. Congratulations, you just built your own spy microphone! You can now play with the different settings, for example, using a longer recording time.


Tweet-a-Light – Twitter-Enabled Electric Light


In this blog, we will learn:

  • How to install Python on Windows
  • How to install some useful libraries on Python, including pySerial and Tweepy
  • How to create a Twitter account and obtain Twitter API keys
  • How to write a simple Python Script to read Twitter tweets and write data on the serial port
  • How to write a simple Arduino sketch to read incoming data from the serial port


Hardware and software requirements

To complete this project, you will require the following hardware and software.


Arduino UNO Rev3 board (

A computer with Windows installed and Internet-connected

PowerSwitch Tail (120V or 240V depending on your voltage of mains electricity supply)—( aspx)

A light bulb (120V or 240V depending on your voltage of mains electricity supply), holder, and wires rating with 120V/240V

A USB A-to-B cable (

Some hook-up wires



The software needed for this project is mentioned under each topic so that it will be easier to download and organize without messing things up.


Getting started with Python

Python is an interpreted, object-oriented, and high-level computer programming language with very powerful features that's easy to learn because of its simple syntax. For this project, we can easily write an interface between Twitter and Arduino using the Python script.


Installing Python on Windows

The following steps will explain how to install Python on a Windows computer:

1. Visit

2. Click on Downloads | Windows. The Python home page

3. Then, you will navigate to the Python Releases for Windows web page:


4. Python can be downloaded from two development branches: legacy and present. The legacy releases are labeled as 2.x.x, and present releases are labeled as 3.x.x.


5. Click on the latest (see the date) Windows x86-64-executable installer to download the executable installer setup file to your local drive under Python 3.x.x.


6. Alternately, you can download a web-based installer or embedded ZIP file to install Python on your computer.


7. Browse the default Downloads folder in your computer and find the downloaded setup file. (My default downloads folder is C:\Downloads). Double-click on the executable file to start the setup:


8. Click on the Run button if prompted as a security warning:


9. The Python setup wizard starts:

Optionally, you can check Add Python 3.5 to PATH, or later, you can add it using Windows system properties. Click on the Customize installation section. The Optional Features dialog box will appear:


10. Click on the Next button to proceed. The Advanced Options dialog box will appear. Keep the selected options as default.


The default installation path can be found under Customize install location. If you like, you can change the installation location by clicking on the Browse button and selecting a new location on your computer's local drive.


11. Finally, click on the Install button.

If prompted for User Access Control, click on OK. The Setup Progress screen will be displayed on the wizard: Python setup installation progress


12. If the setup is successful. Click on the Close button to close the dialog box:


Setting environment variables for Python

If you have already set to Add Python 3.5 to PATH for writing the environment variables during the Python setup installation process, ignore this section. If not, then follow these steps to set environment variables for Python.


1. Open the Windows Control Panel and click on System. Then, click on Advanced system settings.

2. The System Properties dialog box will appear. Click on the Advanced tab. Then, click on the Environment Variables… button:

3. The Environment Variables dialog box will appear. Click on the New… button under user variables:


4. The New User Variable dialog box appears:

Type the following for the respective textboxes:

Variable name: PATH
Variable Value: C:\Users\Pradeeka\AppData\Local\Programs\


5. Click on the OK button three times to close all the dialog boxes.

Open Windows Command Prompt and type python, and then press the Enter key. The Python Command Prompt will start. The prompt begins with >>> (three greater than marks):


Python Command Prompt

This ensures that the Python environment variables are successfully added to Windows. From now, you can execute Python commands from the Windows command prompt. Press Ctrl + C to return the default (Windows) command prompt.


Installing the setup tools utility on Python

The setup tools utility lets you download, build, install, upgrade, and uninstall Python packages easily. To add the setuptools utility to your Python environment, follow the next steps. At the time of writing this blog, the setuptools utility was in version 18.0.1.


Visit the setuptools download page at setuptools.
Download the script by clicking on the link (https://

The script opens in the browser's window itself, rather than downloading as a file. Therefore, press Ctrl + A to select all the code and paste it into a new Notepad file:


4. Next, save the file as in your local drive.


5. Open Windows Command Prompt and navigate to the location of the file using the cd command. We assume that the drive is labeled as the letter D:, and the folder name is ez_setup: C:\>D:

D:\>CD ez_setup


6. Type python and press the Enter key to run the Python script. This installs the easy setup utility package on your Python environment:


Installing the pip utility on Python

The pip utility package can be used to improve the functionality of setuptools. The pip utility package can be downloaded from pip. You can now directly install the pip utility package by typing the following command into Windows Command Prompt: C:\> easy_install pip

However, you can ignore this section if you have selected pip, under Optional Features, during the Python installation.


Opening the Python interpreter

Follow these steps to open the Python interpreter:

  • 1. Open Command Prompt and type the following: C:\> Python
  • 2. This command will load the Python interpreter: To exit from the Python Interpreter, simply type exit() and hit the Enter key.


Installing the Tweepy library

The Tweepy library provides an interface for the Twitter API. The source code can be found at You do not have to download the Tweepy library to your computer. The pip install command will automatically download the library and install it on your computer.


Follow these steps to install the Python-Twitter library on your Python installation:

Open the Windows command prompt and type: C:\>pip install tweeps

2. This begins the installation of the Tweepy library on Python:


Installing pySerial

To access the serial port in the Python environment, we have to first install the pySerial library on Python:


Open the Windows Command Prompt and type the following:

C:\>pip install pyserial


After installing the pySerial library, type the following command to list the available COM ports in your computer:

C:/> python -m


Creating a Twitter app and obtaining API keys

To proceed with our project, use the following steps to create a Twitter App and obtain the API keys.


1. Go to and sign in with your Twitter login credentials (create a new Twitter account if you don't have one). The following page will display on the browser:, the Application Management start page


2. Click on the Create New App button. The Create an application page will display:


3. Fill in the required fields (for the website text box, just type http://www. as a placeholder), accept the Developer Agreement by clicking on the Yes, I agree on checkbox.


4. After this, click on the Create your Twitter application button.


5. You will be navigated to the following page:

Click on the Keys and Access Tokens tab. Under this tab, you will find Consumer Key (API Key) and Consumer Secret (API Secret). Copy these two keys and paste them in a Notepad file, because you will require them in the next section:


The Tweepy library provides a set of easy functions to interface with the Twitter API. Our Python script provides the following operations and services:

  • Read tweets from the specified twitter screen name.
  • Always read the latest tweet
  • If the tweet includes the text, #switchon, then print the tweet on the console and write 1 on the serial port
  • If the tweet includes the text, #switchoff, then print the tweet on the console and write 0 on the serial port
  • Otherwise, maintain the last state


The following Python script will provide an interface between Twitter and the serial port of your computer. The sample script,, can be found inside the Blog codes folder. Copy the file to your local drive and open it using Notepad or NotePad++:


import tweepy
import time
import serial
import struct
auth = tweepy.OAuthHandler('SZ3jdFXXXXXXXXXXPJaL9w4wm', 'jQ9MBuy7SL6wgRK1XXXXXXXXXXGGGGIAFevITkNEAMglUNebgK') auth.set_access_token('3300242354-sJB78WNygLXXXXXXXXXXGxkTKWBck6vYIL79jjE', 'ZGfOgnPBhUD10XXXXXXXXXXt3KsxKxwqlcAbc0HEk21RH')
api = tweepy.API(auth)
ser = serial.Serial('COM3', 9600, timeout=1)
public_tweets = api.user_timeline(screen_name='@PacktPub',count=1)
while True: # This constructs an infinite loop
for tweet in public_tweets:
if '#switchon' in tweet.text: #check if the tweet contains the text #switchon
print (tweet.text) #print the tweet
if last_tweet == "#switchoff":
if not ser.isOpen(): #if serial port is not open; #open the serial port ser.write('1') # write 1 on serial port
print('Write 1 on serial port') #print message on console last_tweet="#switchon"
elif "#switchoff" in tweet.text: #check if the tweet contains the text #switchoff
print (tweet.text) #print the tweet
if last_tweet == "#switchon":
if not ser.isOpen(): #if serial port is not open; #open the serial port; #open the serial port ser.write("0") # write 0 on serial port
print('Write 0 on serial port') #print message on console last_tweet="#switchoff"
ser.close() #close the serial port
time.sleep(30) #wait for 30 seconds
Now, replace the following code snippet with your Twitter Consumer Key and
Consumer Secret:
auth = tweepy.OAuthHandler('SZ3jdFXXXXXXXXXXPJaL9w4wm', 'jQ9MBuy7SL6wgRK1XXXXXXXXXXGGGGIAFevITkNEAMglUNebgK')
auth = tweepy.OAuthHandler(' Consumer Key (API Key)', ' Consumer Secret (API Secret)')
Also, replace the following code snippet with Access Token and Access Token Secret:
auth.set_access_token(' Access Token, ' Access Token Secret ')
Next, replace the COM port number with which you wish to attach the Arduino UNO board. Also, use the same baud rate (in this case, 9,600) in Python script and Arduino sketch (you will write in the final step of this blog):
ser = serial.Serial('Your Arduino Connected COM Port', 9600, timeout=1)
Finally, replace the Twitter screen name with your Twitter account's screen name:
public_tweets = api.user_timeline(screen_name='@PacktPub',count=1)
public_tweets =


Now, save the file and navigate to the file location using Windows Command Prompt. Then, type the following command and press Enter:


Replace your_python_script with the filename. The script will continuously monitor any incoming new Twitter tweets and write data on the serial port according to the command that has been sent: Windows Command Prompt will display any incoming Tweets and actions against them.


Reading the serial data using Arduino


You can read incoming data from the serial port where we wrote data using the Python script in the previous section using Arduino. The following Arduino sketch will read the incoming data from the serial port and turn on the PowerSwitch Tail if it finds 1, and turn off the power switch Tail if it finds 0.


The sample code, B04844_07_01.ino, can be found in the Blog codes folder, so you can copy and paste it on a new Arduino IDE and upload it to your Arduino UNO board.


Connecting the PowerSwitch Tail with Arduino

Connect the PowerSwitch Tail to your Arduino UNO board, as shown in the following Fritzing diagram. For this project, we will use a 240V AC PowerSwitch Tail:

  • Using a hook-up wire, connect the Arduino digital pin 5 with the PowerSwitch Tail positive (+ in) connector.
  • Using another hook-up wire, connect the Arduino ground pin with the PowerSwitch Tail negative (- in) connector.
  • Connect a 240V AC light bulb to the LOAD end of the PowerSwitch Tail.


Connect the LINE end of the PowerSwitch Tail to the wall power socket and make sure that the main's electricity is available to the PowerSwitch Tail. 


Using a USB A-to-B cable, connect the Arduino UNO board to the computer or laptop on which you wish to run the Python script. Make sure that you attach the USB cable to the correct USB port that is mentioned in the Python script.


Connect your computer to the Internet using Ethernet or Wi-Fi. Now, run the Python script using Windows Command Prompt. 


Log in to your Twitter account and create a new tweet including the text, #switchon. In a few seconds, the light bulb will turn on. Now, create a new tweet that includes the text, #switchoff. In a few seconds, the light bulb will turn off.


The drawback to this system is that you can't send the same Tweet more than once, because of the Twitter restrictions. Each time, make sure you create different combinations of text to make your tweet and include your control word (#switchon, #switchoff) with it.