Month: July 2016

Understanding Image Compression

The internet has grown to connect a very large user base in recent times, but still bandwidth remains limited. Images take up a large amount of bandwidth. Hence we make use of different image compression methods. One famous format is the JPEG(joint photographic Experts Group).This format makes use of Discrete cosine transforms. In this post we will try to understand the simple idea behind DCT(Discrete Cosine Transformations).

For our demo I will be using Octave(it is an equivalent of Matlab).

I will be using the following image, which is a 512×512 image. As shown:

The code for understanding DCT is fairly simple.

  • The first line reads the image into the matrix ‘x’. By this, the image can now be imagined as a matrix of 512 rows and 512 columns and each value of the matrix corresponds to the contrast of that part in the figure.for example the eyes in the image may correspond to the location of [260,256]. Therefore the matrix value at this address is 0 indicating completely black. (on a scale of 255, where 255 is white). If the picture was a colour image, the matrix would be of the size 512X3,512X3 where the first three values refer to the RGB of the first pixel(Red Blue and Green values. This is referred to as a 3 channel image).
  • Next we find the DCT of this image and store it on ‘y’.Remember that the DCT is not really a one to one mapping like the case above (each matrix entry is not really referring to the complete information of the picture).Instead the entries refer to the weights of the pixels. Not going much into the thoery, lets move on.
  • The next 5 lines of code is used to take a part of the matrix ‘y’ and save it onto matrix z. Here only 200×200 elements of the matrix ‘y’ are saved on ‘z’.The plot of ‘y’ and ‘z’ are show later.
  • The above operation is similar to cropping of the image.
  • Now we find the inverse DCT of the matrix ‘z’ this should give us the image back, but it will not. a scaling factor of around 255 is required,either multiply or divide play around to find the correct one.Divide works for me.
  • Hence the line: imshow(z1/255).

The resulting image is shown along side. Now to understand what we actually did we have to look at the details of the image.

Just type in “whos z1” (without quotes)in your main terminal and u will see that the resulting image is a 200×200. Not only has the image been re-sized but the important point is we recovered the complete image with only 200×200 values of the DCT. This is what we mean by energy compaction,where the most of the image data is stored in the first few elements of the matrix. So instead of having a 512×512 information where each pixel data is important to define the picture, we have converted that to a set of 200×200 matrix where the first few entries talk about the contrast of the whole picture and the rest are data which can be ‘mutiplied’ in a sense of saying to the contrast to get the whole picture.

Output Image

Image Details

imshow for the DCT image

Posted by admin in Image Processing, 0 comments

Report : Product development talk @SVIT

FSMK conducted a 5 day residential workshop at svit during the last days of January. We were invited to give a talk on product development using free hardware.

The talk was attended by around 150 students from various colleges spread across karnataka and some from outside karnataka too.

Aravind Started the talk by explaining how a basic hobby idea can be made and then grown into a complete product for development. Explaining this with the evolution of the basic obstacle avoider bot to a remote controlled one to a gesture based bot.

The audience seemed to be enthralled by the demo’s given, and hopefully they have been inspired to work on their own and contribute to the community.

Posted by admin in FHM, 0 comments

Report:SJCE,Mysore talk on Freedom Hardware

SJCE Mysore conducted their yearly tech event,tuxedo this weekend. A completely opensource event where students and industry people present talks and small workshops based on FOSS.

It was quite interesting to see a collage so much into FoSS,unlike the collages i’ve seen in Bangalore  There was a prof who gave a talk on latex a software for making tech papers. He was using zen walk OS. He also kept inspiring his students to work on linux. To add to that he has contributed few clip arts for paper presentations. Parallelly the linux computing group of SJCE had their event, various coding competitions and talks.

The college has its own hardware and software groups which conduct workshops and also attend various other events.

Our talk was an introduction to freedom hardware ,though many of them were acquainted with various technologies ,the idea of community learning was something new to them.

The session was attended by about 50 students from circuit branches and spread across all semesters . They loved the various demos on kinect and pi. A large group showed interest and came back for offline discussions.

Being optimistic and patiently waiting to see the results of the talk 

Posted by admin in FHM, 0 comments

Report:Freedom Hardware Symposium

The day started off with talks, Surprisingly we had a jam packed auditorium.
Talk 1: Jaykumar and Senthil from FSMK(Free Software Movement karnataka) gave a brief talk on the on-going free software movement and the need for a parallel hardware movement.
Talk 2: Me (Ashfaq) presented the idea of Freedom hardware and its need in our world.
Talk 3: Prof. Dinesh from IISc spoke about product development, Inspiring students to start working of various projects.
Talk 4: Aravind(Junior Research Fellow @ IISc gave a demo of interfacing the arduino and Raspberry and controlling a motor over the internet.
This was then followed by an open house exhibition.Students displayed projects done by them.The Projects on display:

Hardware based.
1. Line-follower.-Basic line follower made using a motor driver and Ir sensors
2. Manual bot- Manually controlled wireless bot.
3. Wi-Gi(wireless Gesture Input ) – A glove which controls the mouse on your computer,taking the movements on                                                     the Hand.(using wireless communication)
4.Kinect:- A bot the follows you!!
5. 7-segment Display-A basic 1ft by 1ft display made as a display for basket ball matches,done by students.
6. Speaker-A simple arduino Project which takes input from a tv remote(via IR, and plays a tone)
7. PIR.-The door was hooked with a pir sensor, which would count the number of people entering the hall.
8. Power Supply- the basic bridge power supply, used to explain basic capacitance to students.
9. Led Cube: using arduino( 4X4X4 cube)
10:EMF sensor: an arduino based project that would give display the reading of radiation present in the air.

And many more projects….

Software Projects:

1. Web programming: Basic Html website.
2. Fun with Bash:explaining the bash script.
3. Blender:animation using blender.
4. Kernel compilation
5. Rahul’s Table: Rahul our web developer explained various upcoming technologies in website building.
6.Filters on octave

In parallel to the exhibition a workshop on PCB designing was conducted. The workshop taught the student s to use Kicad for designing PCB and also a brief explanation on how to fabricate them at home.We had planned to cater to 30 students, but surprisingly we had a demand for more than 150 registrations. hence the workshop was conducted in 3 sessions of about 45-50 students each.

The Road Ahead!This event got many of the students interested in the movement, now we plan to help them work on projects by providing technical support and also giving a common platform to learn,share and teach.

Posted by admin in FHM, 0 comments

Your First Hardware Project

The toughest part of getting your self to work is the first project. Once you’ve over come this first project the rest seem much more easier. This post basically aims at getting one started. A few steps i think will help you get past this learning curve with a little ease.

Step 1:
Define the problem statement clearly for yourself, Write down all the requirements, dont go too technical. Just mention on the outside what you want your project to do.

Step 2: Break up step one into different parts. Go technical here. Break it into, mechanical, coding, Hardware electronics. and then further down into different components.

Step 3: Start writing down your plan for each component. If its a program write the algorithm and logic for it.
For, Electronic circuits a block diagram, mechanical part put down the designs.(Dont be too technical here again)

Step 4: List down all the components you need for your project. In case there are things your not cirtain of get a way to conduct some tests on it. that is: instead of buying all the components get one of it and see if it works the way you want it to.

Step 5: Get all the components and dependencies required by your project.

Step 6: Convert the Flowcharts and designs into actual code and the block diagrams into complete circuits.

Step 7: Test the components you’ve made separately.

Step 8: Put them all together. you’ll have your idea materialized.

Step 9: Test the complete product.

Step 10: Feel happy and start a new project.

This is just a birds eye view of how you should go about your project.

Posted by admin in General, 0 comments

Bootloading an Arduino board

I guess by now most of us, coding freaks by now are into arduino directly or indirectly. One major problem we all have faced with arduino is the frequent deletion of the boot-loader from the Atmega IC. There could be N number of reasons for this, and I shall not get into that. I will give you a way to solve this problem and also convert your normal atmega chip to an arduino chip.(Most of you pro’s will tell me AVR and Arduino are the same. YES they are, but for those freshers who have just been introduced to AVR and Arduino take them as different things, as time goes you will know what I mean)Requirements to boot-load:
1) A programmer or another working arduino board.
2)the board you want to boot-load.
3)6-7 plugs(wires)



Connect your programmer to the arduino IC. the pins are as follows:

pin 13,12,11 on the arduino corresponds on sck,miso,mosi respectively. use this config to connect to the usbasp.


On the arduino IDE(arduino1.0 and up) select the corresponding board which you want to boot-load


select your programmer.(usbASP or if your using arduino itself select arduino as ISP)

Step 4:

Connect the programmer to the computer.

Step 5:

In the arduino IDE select tools>burn bootloader

Step 6:

Plug out the arduino and now get coding on your freshly bootloaded chip!!!

Posted by admin in Arduino, 0 comments

Digital Voltmeter

Now that we have established a communication system to the computer which is programming the device, we make use of this feature to make a small digital voltmeter. This is an indispensable tool in the field of electronics!. Whenever there is a need to debug, we need a voltmeter reading to get a better understanding of the circuit. For this example, we’ll use a new tool, Analog Read.So lets get right to it. Onto the theory!


The theory here will make an attempt to brief ADC(Analog to digital Conversion). Though most programmable pins are 0 and 5V logic(1 and 0) some pins are also 0 to 5V sensitive. These pins are the analog pins. When a certain voltage is given to these pins, within the limits of the reference voltage of course, a digital equivalent can be generated and read into a register inside the Arduino.

The theory for ‘sampling’ the analog value into a digital value is quite complex, but we will not go into that detail. For, the basic understanding we’ll stick to the picture on the left.

Vref  is the reference voltage to which the input voltage will be digitized. This means that if Vref is 5V, then the input voltage can vary from 0V(common ground) to 5V.
Arduino has a 10 bit ADC. This means that the analog values can be resolved into a digital value ranging from 0 to 255 where 0 corresponds to 0V and 255 corresponds to 5V.

The working is explained as follows:
The input voltage is ‘quantized’ by sampling at constant frequency known as the sampling frequency. This means that every certain amount of time, the value at the analog pin is compared against a set of reference values generated by the main reference voltage.
If vref=5V then, from the circuit on the left, the various reference voltages to the op-amps are 4.375V,3.125V,1.875V,0.625V (got by using resistor divider rule). Therefore, if the Vin(the input voltage) is more than the reference voltage for that op-amp, the output of that op-amp will be high. Lets consider this 2 bit ADC above for a voltage of 2V. 2V<4.375V ,so the first op-amp will send a 5V(logic 1 because its inverting op-amp) as output,similarly its lesser than the second reference(3.125V) hence output is 5V. 2V is>1.875V>0.625V. Therefore the remaining op-amps will give a low output. Now the NAND gates inputs are respectively 1,0 ; 1,1 ; 0,1 ; giving the final output at B as 10 ( 2 in decimal). So, in a 4bit ADC, if the output is 2, the digital reading indicates that the analog value is 3.125V . This quantizing error of 1.25V(max possible error) can be improved by having a higher resolution (i.e higher bit ADC).

The Arduino utilizes a 10bit ADC. This means that 0-5V can be digitized as 0 to 1024 value range. Let’s look at the resolution. 5/1024 =5mV . This means that the most possible error in reading is 5mV! thats more than enough for our usage!.

Enough nerding! lets put it in use! 


The code is very simple. Just a one line add-on to the previous serial code.
In the Loop function, we wish to continuously sample the pin A0 by calling the
analogRead function. This returns a value of 0 to 1024 into the int variable sensorValue.
I leave it to the users to convert this value to a voltage reading.
Hint: in Serial.println , just add a multiplication factor to sensorValue to convert 0 to 1024 to 0 to 5V.

compile and run the code, and in the serial monitor on the computer you should be able to see the voltage value print infinitely amd also change as you rotate the pot.

So simple! 

Food For Thought:

Q.You mentioned that the ADC uses sampling time? Should we take into consideration of the time elapsed?
A. Depends on the application, but most situations does not require it. Do notice that each ADC can only be sampled individually and not together in one shot. So,if you were to sample all analog pins, then time considerations might show up, but even then, its manageable.

Q.Is there a way to change the range of values to an upper limit and lower limit instead of 0 to 1024?
A. yes, It is possible. The function is called map. You can use it like this : int OutputValue=map(sensorValue , 0 , 1023 , 0 , 255) in the above code. This returns a value to the ‘OutputValue’ ranging from 0 to 255. So we have effectively scaled a 10bit to 8bit resolution. This is helpful when data has to be transmitted byte wise in serial communication.

Q.Can analog pins be used as PWM output pins?
A. No,they are strictly read only for analog. But, they can also be used as DigitalWrite or DigitalRead . The parameter to those functions will still be A0-A5.

Q.How do i sample a voltage that is not supplied from the Arduino board(external sensor, etc)? need to have a common ground between the two devices. Say your external sensor is connected to A0, then make sure that the ground pin of the external sensor is also connected to AGND on the Arduino, which is the in the case of the board ANY GND pin. This way the Arduino knows that the 0V reference of the sensor to calibrate the reading.

Q.How do i sample voltage of different reference(instead of 0-5V , need to use 0-3V)?
A.For this, you need to generate the reference voltage and pass it to AREF pin on the Arduino, I wouldn’t recommend this as it unnecessarily wastes power. Instead use the existing readings and use constrain(click to see usage) to saturate values above 3V. Also note that the AREF voltage cannot be greater than 5.5V.

Posted by admin in Arduino, 0 comments

Serial Communication

The most important part of any project with Arduino I feel is the communication to the user. To display the readings of a sensor or to ask for a command from the user is the basic importance of most projects. Arduino’s most effective form of communication is the Serial Communication. In this tutorial we shall try to understand how to setup a serial communication link with the computer which is programming the device and use the same to debug programs and also to display results in understandable formats.


Serial Communication in itself is quite vast. Hence, we’ll address it as different tutorials. This basic tutorial will concentrate on a simplex mode to equip the user to use these tools for future tutorials and the whole communication protocol will be explained in tutorials to come.

Serial communication on the very basic level uses three lines. Tx(Transmitter), Rx(Receiver) and GND(Ground) lines.Data are encrypted as sets of pulses and sent on either the Tx or Rx line with respect to the GND. These pulses are usually 10bit data unless otherwise mentioned. The 10 bits consists of a start bit, a stop bit, and a 8 bit data. This constitutes one packet of data.

The rate at which the bits are transmitted is known as the ‘baud rate’ . Once serial transmission is enabled, the contents of a memory location known as the ‘data buffer‘  is transmitted. As soon as it is empty new data can be written into it and it is transmitted at the baud rate.

This much is enough to understand basic serial transmission. Onto the practical section.


Since this is the basic communication tutorial, we will concentrate on the built in serial communication through the USB cable. The actual way of using serial communication is through the Tx and Rx pins which we will cover in later tutorials.

– Arduino
– The USB cable that comes along with it to program it.

So this tutorial has no external setup. Onto the code!

The code is the simplest of all!

In the setup we initialize the baud rate of the serial communication.
In this case, its set to 9600. This means that the bits are transmitted at the rate 9600 bits per second.

In the loop we are continuously transmitting the letter ‘a’ infinitely.The subclass println signifies that the Arduino prints the character ‘a’ followed by a ‘ln’ or new line. These again are command bytes sent along with the data. The ASCII equivalent of this would be 10 and 13 (refer to carriage return and new line). This means that the Arduino first prints the character ‘a’ then returns to the start of the line and then creates a new line. These are the sequence of commands sent on the serial line.

When you run this program and look at the Serial Monitor window, you’ll see the character ‘a’ being printed in each new line continuously.If not make sure the baud rate on the serial monitor is set to 9600. If a new line is not desired (if its required to print a string), use Serial.print instead of Serial.println .
Thats it! a simple communication program.

Food For Thought:

A packet of Questions!

Q. Instead of writing ASCII characters, I want to write bytes of hex values. Is it possible?
A. yes, for that its preferable to use Serial.Write(value). It prints the hex values as bytes of data.

Q. I want the data to be transmitted on the Tx Line. Not on the USB..What do i do?
A. It is actually printing on the Tx Line! The USB lines tap the data from these lines and convert it to USB protocols to make life simpler. Otherwise the same data is actually coming on the Tx line as 97(‘a’) 10 and 13.

Q.How important are these baud rates and why the funny number 9600?
A. Well basically, these bauds are standard rates decided long ago for uniformity. Both ends of the Tx and Rx lines need to have the same baud to be able to communicate. If the bauds are different then, the communication wont occur properly. These funny numbers are a result of the dividing possibility of a 11.0592Mhz crystal. That frequency can be divided accurately to get these baud rates. But actually the Arudino uses a 16Mhz crystal  .

Q.What about receiving data on the Arduino?
A. Will be answered in future tutorials as it requires a little more understanding.

Q.How fast can we transmit data ?
A. It depends. Actually after the transmission of a data, its desirable to introduce a delay before transmitting to ensure the buffer is emptied properly. Therefore a delay of 2ms in the above program after the transmission of the character ‘a’ would ensure almost error-free transmission. The baud rate themselves can be increased upto 115200 baud for Arduino family.

Posted by admin in Arduino, 0 comments

Button Interface

Right! so we got an LED blinking on a pin. Cute,but not effective if there is no control over it. Here’s the next part then, to interface a button to the Arduino, to blink the led manually.
Again, the code is very simple. The circuit is also simple, but we’re going to touch upon theory a little more to make it more effective and learn electronics at the same time.
So let’s get started! Onto the Theory!


The classic push button is what we’ll learn to interface in this segment. A button is just like a retractable short between two pins. So when you press the button all you are doing is connecting two pins and forming a path for the current to flow between them and if the arduino detects the current it assumes an input has occured. The direction of the current acts as the ‘edge detection’ . We’ll come to this later.
Again, the only parameters we worry about is the voltage and the current. In this case the voltage doesn’t play a role cause the button works at any voltage(its just forming a path!). Its  current dependent in the sense that u can probably give around 2A before the button pin melts :D. Anyways,the Arduino input pin is voltage dependent. Hence we’ll design a voltage based approach as follows.
If we were to put a button between the Arduino and GND , one pin to each, then when we press the button, its equivalent to that pin being directly connected to GND(current flowing towards GND) and when the button is not pressed, its as if the Arduino pin was open(not connected to anything and hence no current flow). This should work great if your code were to be like
If(PIN==GND) {do}

else{ do somethine else}
But, this is not a good way to code because when the pin is open, its like a small antenna which can take in noise and this noise might give erroneous readings. Its best to keep the pin either at high or low. So, the best way would be to do the following

Analyzing this yet again simple circuit, we can notice that the input pin is default powered by the 5V supply through the resistor as long as the button is not pressed(the ends are not shorted to GND). Once the button is pressed, the Input pin is brought to 0V, giving the effect of a ‘falling edge’. This can be recognised as a button press.
Hence we can now write a better when the input pin reads a HIGH and one when it reads a LOW.

Now we are ready to move on to the practical section!


Physical description of most push buttons are as shown. The leads which are NOT nearer are shorted, which means they are the same pin, and the ones nearer are not shorted, which will be the pins that we shall use.

Components Required:
– Arduino Uno
– Push Button
– 10k and 330 resistor
– Red LED

In this example we shall interface a button to the Arduino to toggle an LED.

Yes, the circuit is a little poor in design but the idea and implementation are very simple!. Using the same idea as above in the circuit, we have interfaced the button to Digital Pin 2 of the Arduino keeping the LED at pin 8.
This way the press of a button should be read at pin 2 and effected at pin 8.

We will do two small examples related to push buttons.

The first piece of code we will write is very simple. when the button is pressed, the LED will glow and when it is let go the led goes off.
The code for this is as shown below.Go ahead open up the button code from examples->digital->button


Once the code is loaded remember to change the ledPin value to 8 as thats where our led is!
Again here we have the two functions, the setup which is straightforward. It initializes pin 2 as INPUT and pin 8 as OUTPUT. Notice the use of global variables ledPin and buttonPin. These are just to avoid confusion. You can always put the number directly.
In the loop function we see what is called ‘polling’. This refers to reading the input pin at frequent duration and based on the reading, an if else statement effects the output led. The digitalRead function returns the status of the input pin(HIGH  if button unpressed or LOW if button is pressed).

Straightforward right?
Now the problem here is quite obvious. The LED glows only when the switch is held down. Once its let off, the LED turns off too. So, how are we going to fix this?
It might instantly strike that instead of turning the LED on when the switch is pressed, we just toggle the LED that is
int led_status = LOW;
if (buttonState == LOW)
if( status==LOW)// if previous state was LOW
digitalWrite(ledPin, HIGH);  //output to HIGH state
led_status=HIGH;                    //set status as current state i.e HIGH
else                      //if previous state was HIGH

This would remember the previous state and toggle the led. This should theoretically work. But when you test this u’ll see a problem. The LED say 3/10 tries might not toggle. This is cause of the ‘switch debouncing’ effect.
This brings us to the second piece of code.. The actual button interface to arduino.

Code 2

When a switch is pressed, there is a change from one state to another(HIGH to LOW or vice versa). Because of the imperfections of the switch, the first contact need not be firm, that is to say when we press the switch, the pin takes time to settle down to the GND value, because the switch toggles from contact to no contact a couple of times before establishing a firm contact between its leads as shown beside in the picture.
This can be wrongly read by the Arduino as a series of press and release of the button, which makes the led blink a couple of times before settling to the appropriate value.
To overcome this we give a delay function so that once we read the pin status we check again after a small delay in the order of milliseconds to see if the change actually occurred or if it was due to debouncing effect.
Slightly modifying the above program we get,

if (buttonState == LOW)
    delay(50);    buttonState = digitalRead(buttonPin);
         if( status==LOW)// if previous state was LOW
digitalWrite(ledPin, HIGH);  //output to HIGH state
led_status=HIGH;                    //set status as current state i.e HIGH
else                      //if previous state was HIGH
So what we are doing here is to first see if the button was pressed(i.e shorted to GND). If so, wait for 50mS and again check if it really went LOW. If it did then toggle the LED. else do nothing. This is the perfect way to interface a switch to the Arduino. The final code is as shown below.

Food For Thought:

Here are some Questions:

Q.Why the resistor? why not just directly one pin to 5V and the other to GND?
A. Well!, when you press the switch you will be shorting the 5V directly to GND right? that would damage your power supply. The resistor exists for the sole purpose of limiting the current when the switch is pressed between the power and GND.

Q.Does it mean i can use any value of resistance as long as the power supply can handle the current?
A. Yes you can in theory! but practically a small part of the current will also flow into the Arduino.We do not want that part though a small fraction of the major to affect the Arduino when the switch is not pressed.Also why waste current? keep a low current flowing in the circuit at all times to efficiently use power. But not so low that the Arduino wont even detect it!.

Q.Is debouncing really an issue? it will eventually settle to one state before we realize..
A. It matters when you are using the button to count an event. You wouldn’t want it to count many times when its only once. 

Q.I’m an EC student, we have studied in our curriculum that the pins have an internal pullup resistor to 5V so that we need not use the external resistor.
A. Yes dude, you are right! but theory and practicals are different  . It is a weak internal pullup to 5V. There are always chances the arduino might not read the state right!.

Q.What happens when we digitalRead a pin defined as OUTPUT mode in the setup?
A. I’m not entirely sure on this. But as far as my experimentation goes, it will just return the state of the pin you have written the output pin to. That is, if you have earlier defined the pin in output mode and also written digitalWrite(pin,HIGH) and then follow up with a digitalRead(pin), the function should return the value as HIGH.

Posted by admin in Arduino, 0 comments

Fading LED

In the Last tutorial, we have successfully managed to interface a button to toggle a LED. This time we’ll learn to control the brightness of the LED. We will use something called as AnalogWrite to accomplish this. Ever seen those fading lights on a lot of phones that give a ‘breathing’ effect? Glowing up and dimming down continously? We are going to do just that now! On with the theory!


Until now we were using digitalWrite function which is very simple to understand. HIGH referred to 5V or LOGIC 1 and LOW referred to 0V or LOGIC 0. Now we are going to use analogWrite which defines levels between these two voltages and assigns a digital integer number to them. We will try to define a 8 bit DAC(Digital to Analog Converter). To put simply, it just converts a 8 bit value (0 to 255) to voltages ( 0 to 5V). This means we can now access voltage outputs of steps =5/255=0.02V.
We shall touch upon a simple idea of PWM here to get a simple understanding of how this works. Imagine a voltage wave which is on for 0.5 sec and off for 0.5 sec and so on(refer to 50% duty cycle in figure). This means that it alternates between 5V and 0V every one second..if you were to average it out for one second then the average value would be (5+0)/2 = 2.5V . This is the effective DC voltage coming at the output pin.
Now if it was on for a shorter time and off for a longer time(20% duty cycle example), then output = 0.2*5=1.0V.

The effect of these changing voltages will show on the LED as a dimmer source or a brighter source. So effectively all we are doing is to split the 100% into 255 digital levels so that we can have varying voltages of step resolution=0.02V.

So the crux of the theory is this. Suppose we write a value of 128 to analogWrite, its equivalent to a 50 duty cycle of a square wave appearing at the output. Since the LED is a DC device, it will recognise the average value of this wave which is 50% of 5V =2.5V and hence will glow half as bright as it would have for a digital value of 255 =>100% duty cycle => constant 5V.

Now onto the practical section.


This is exactly like the first LED blink program we wrote. The only difference being that the LED is now connected to pin 9 instead of 8. This is something we have to pay careful attention to. The Arduino has only 3 Hardware PWM channels capable of analogWrite( Pins 3,6,9).
The rest are digitalWrite only!.

Nothing more to explain! onto the code!
Go ahead open the code from examples->Basic->Fade.

Yet another easy code!
Setup function initiates pin 9 as an output pin.
In the loop function, we call the function analogWrite to output a 8 bit value to the pin 9. Starting from 0. It is then incremented by a value =fadeAmount preset as 5.
therefore in the successive iterations the value output is 5,10,15,20,etc till 255 once we reach 255 there is an if condition that says fadeamount will now be =-5 which will count down from 255 to 0 and again up to 255 and so on..
once the value is written to the output pin we delay for 30ms . This is purely for the eye to be able to distinguish it rising and dimming.
Pretty simple huh!?
Compile it off and run it to see the magic. I think you can put this code into a night lamp and give a nice effect..of course u’ll need to do the circuit for a lamp not for an LED .. 

Food For Thought:

There always is a Question :-D

Q. Dosen’t the resistor value make a difference for every changing value of the voltage at the pin?
A. No, it does not. The resistor is just a current limiting component. What we need is a changing brightness with respect to the voltage we give. In fact putting a resistor value of 100 ohm when the analog value is approx 70 would give the same brightness as that of 5V and 330 ohm.

Q. What other applications?
A. Quite some actually.. how about a buzzer which can act like a siren. You could also use this to do speed control of motors(future tutorials will show how).

Q.Can this be used as a variable power source from 0V to 5V?
A. Definitely NOT!. Its just a signal not a power source..A power source requires substantial amount of current to support the components its connected to. This cannot act as such a source. But it can trigger a voltage controlled source or a current controlled source.

Posted by admin in Arduino, 0 comments