About Me

Pilani, Rajasthan, India
I am an engineering student currently pursuing an undergraduate degree in Electronics & Instrumentation from BITS Pilani, Pilani campus. My hobbies are reading novels- fiction and non-fiction alike, playing and watching football, dabbling with new software and going through blogs. I love reading Electronics For You. It has helped me a lot in my college life. And sometimes, people around me.

Hope you find this blog useful. Thank you.

Tuesday, August 30, 2011

Introduction to Pulse Width Modulation

Hi all. It’s been a while since the last post. But, it has been an eventful period all the same with placements going on in BITS Pilani.
Anyway, in this post, I shall be giving a basic introduction to a concept called Pulse Width Modulation, its need and applications and how it can be implemented on an ATmega32/16.

Pulse Width Modulation (PWM) – Basics

In layman language, PWM is a technique in which you vary the ratio of HIGH time to LOW time of a pulse. One of the applications is simulation of an analogue signal using digital TTL signals. What if you want to supply 2.5 Volts to a component? You can use a voltage divider circuit using R1=R2 and then supply the output across any one of these resistors to your component of interest. Simple enough? But what you are overlooking is the fact that this circuit is highly inefficient as there is always going to be power dissipation across the resistors. Also, this configuration is highly susceptible to errors because a slight change in resistance owing to wear and tear or long use is bound to change your input voltage.
 In PWM, you are actually fooling your component by switching between 5 Volts and 0 Volts so fast that it is not able to distinguish between the 5 Volts and 0 Volts and ends up seeing the average of these two signals i.e. 2.5 Volts. A corollary you can draw from this is that by simply adjusting the ratio of these two signals in a given time period, you can supply a variety of ‘analogue-like’ signals. For instance, in a PWM signal with a time period of 1 second, if I am supplying 5 Volts for 0.7 seconds and 0 Volts for the rest, what analogue voltage would my component see? That’s right – 3.5 Volts!

Why do I need to know PWM technique?

The world is analogue. Yes, there are desktops and laptops and mobiles and tablets and what not? All of these are digital in nature. But suppose you want to adjust the speed of your DC motor or you want a system in which the strength of the LED glow is proportional to some system parameter or you want to build a simple all-digital temperature control system? There are many applications in which PWM is helpful for the simple reason – It is energy-efficient as well as accurate, easy to implement and being digital in nature, it is not easily affected by noise.

Basically, in any digital system where you are varying a system parameter over a wide range, there is a high probability that PWM is involved; such is the popularity of this technique.

PWM using ATmega32/16

In any microcontroller, PWM is implemented by using the timers/counters available. The timers/counters have a PWM mode in which the user is supposed to let the controller know the desired time period and also the value of the counter at which the output has to go HIGH/LOW depending on the type of PWM.
For instance, suppose I want a PWM signal of 2.5 Volts. What I will do is I will tell the counter that I want a prescaler of 64 (say) on my clock of 1MHz (say). Also, I will tell it that it should set the output low whenever the counter reaches the value 127 (referred to as 'OCR' value). So, on its way to 255 (referred to here as the 'TOP'), whenever the counter encounters the value 127, the output goes HIGH/LOW. The following diagram will throw more light on the working of PWM in microcontrollers.

Now we will see how to implement this using AVR Studio. Please have your datasheet with you.J 

PWM implementation in AVR Studio
 There are various types of PWM:

1)      Fast PWM – In this type of PWM, in a single time period, a PWM signal will have first the HIGH signal and then the LOW signal.
2)      Phase-correct PWM – In this type of PWM, in a single time period, a PWM signal will be symmetric about the centre i.e. if plotted against time, the signal to the left and right of the centre of the signal will be mirror images.

3)      Phase and frequency correct PWM – In this type of PWM, you can alter the frequency of your signal. In the other types, your frequency remains fixed – only the duty cycle can be altered.

In this post, I will be covering only Fast PWM as it is the simplest to understand for beginners. Other modes will be covered in a future post. Watch out J

So let’s get started!

Registers and Terms involved in Fast PWM implementation

First and foremost, in any kind of PWM implementation, you will come across the following terms:
a)      MAX – This is the maximum value upto which the counter can count. For an 8-bit counter, MAX = 0XFF (255).
b)      BOTTOM – This is the value from where the counter starts counting at the start of every period. For an 8-bit counter, BOTTOM = 0 (0X00).
c)      TOP – This is the value with which the count is compared to decide when to switch the output to HIGH/LOW. (Please note, in the diagram above, TOP and MAX were used interchangeably. This is not always the case. Henceforth, we won't use the two terms interchangeably.)
d)     Duty cycle – This is the ratio of the on-time in a given period to the length of the entire time-period of the PWM signal.

We will be working with the 8-bit timer/counter to keep things simple enough. The registers involved in Fast PWM implementation are the same as the ones I mentioned in the post on Timers. You can refer to the description of the registers in that post for a better understanding. A brief recapitulation follows:

1)      TCCR0 – Manipulating WGM bits in this register help select the desired PWM mode and manipulating the CS bits help select the desired prescaler for the clock generation. Please refer to the datasheet for the required manipulations.
2)      TCNT0 – This 8-bit register stores the current value of the counter.
3)      OCR0 – This register stores the TOP value.
4)      TIFR – This register has a bit called OCF0 which goes HIGH whenever TCNT0 = OCR0 i.e. whenever the output switches from HIGH to LOW or vice versa (depending on the configuration selected). You need to write a ‘1’ to this bit to clear it. (Peculiar right?)

Following is the code for the generation of a 40% duty cycle Fast PWM signal with a clock frequency of 1 MHz prescaled by 64. The code is fully commented, but please make sure you have the datasheet with you to understand the various bit manipulations.

#include <avr/io.h>

int main(void)
        TCCR0 |= (1<<WGM01)|(1<<WGM00);//selecting Fast PWM mode
TCCR0 |= (1<<COM01)|(0<<COM00); // selecting non-//inverting mode of PWM operation
// In non-inverting mode of operation, the HIGH portion of the //signal comes first during a given time period
TCCR0 |= (1<<CS01)|(1<<CS00); // selecting a pre-scaler //of 64
OCR0 = 101; // this is the TOP value; for 40% duty cycle, //TOP = (0.4*256)-1
// This code will generate a square wave having 40% duty cycle on the pin OC0 i.e. PB3 

Some more information

One thing that would have become very clear is that the frequency of our PWM signal is different from the clock signal. There is a formula to evaluate your signal frequency. The formula (for an 8-bit counter) is given by:

256 is replaced by 65536 for a 16-bit counter.

To summarize, in Fast PWM mode:

1)      We can change the PWM frequency (also called modulation frequency) by changing the system clock settings and the prescaler value.
2)      We can change the PWM duty cycle by altering the TOP value which is stored in the register OCR0.


This post would not have been possible without the following treasures of information.


The other types of PWM and their implementation will be covered in a later post.
Hope this was helpful J   

Friday, August 5, 2011

Timers in AVR - A basic introduction

Hello all. Back to Pilani, for one last time J Anyway, in this post, I shall be introducing the concept of Timers using ATmega32/16. So if you don’t like using those fancy delay functions that the IDEs provide or simply, want to create your own delay function, this post might be a good start.

So what are Timers?

Needless to say, Timers are those circuits in your controller that allow you to keep track of time. Any time-related activity – like the blink effect in your blinking LED, the rotation of your motor for precisely 5 seconds, those beautiful lighting patterns that you see in Diwali lightings - takes place because of timers in your controller.

Why do I need to know about Timers?

Yes, every IDE has a library that contains delay functions that you can use. But if you are a curious user, you will want to know as to what is happening when you say you want a delay of 1000ms. Or you will want to know why the function can’t give you a delay above a certain fixed value.
Yet another reason – if you want to implement Pulse Width Modulation (PWM), knowledge of timers is essential. So, it is time to ‘time’! Let us begin.

Basic Concept

First of all, you need to know that the clock of your controller may or may not be the same as that of your timer. This simply means, that the rate at which your CPU executes instructions can be different from the rate at which the timer times. Timing is done with the help of a counter register that counts up to its maximum possible value and then again goes to zero, only to repeat the entire cycle. Checking the value of this register against a particular value helps you to achieve the desired delay. The methods of timing differ in the method of checking this value, as described below.

Timers in ATmega32/16

One look at the ATmega32/16 datasheet tells that it has two 8-bit timers and one 16-bit timer. 8-bit and 16-bit refers to the size of the counter register. The counter of the 8-bit timer can count up to 255 (28 – 1) before resetting to 0 and the counter of the 16-bit timer can count up to 65535 (216 – 1) before resetting to 0.
I will be talking about the 8-bit counter named Timer/Counter0, as it is easier to work with than the 16-bit timer. First, I will explain the crude method of checking the register value with an ‘if’ condition. And second, I will explain the ‘Clear on Timer Compare’ (CTC) Mode.

Crude Method

I call this the crude method because it is the easiest method and involves no software complexity. The steps involved in timing using this method are:
      1)      Enable the timer
      2)      Decide the timer frequency
      3)      Decide the delay needed
      4)      Calculate the counter value that corresponds to the desired delay
      5)      Use this value in the ‘if’ condition in your program

Enable the timer

Looking at the register description for this timer/counter, on Page 80 of the datasheet, we see that the lowermost three bits of the register TCCR0 are involved in the enabling process. The table on Page 82 tells that to enable the timer, we need to write a ‘1’ to the CS00 bit of TCCR0 register. The corresponding code is:
TCCR0 |= (1<<CS00);

Decide the timer frequency, delay and calculations

As mentioned in the post, the clock of the timer and the CPU may or may not be the same. And this facility is extended to us by the presence of ‘prescaler circuits’ in the controller. These circuits enable us to scale down the CPU frequency (F_CPU) by 8, 64, 256 and 1024 times. For instance, if we are using a prescaler of 64 and F_CPU is 1MHz, then the timer will not see each period of the CPU as 1µs but as 64µs. Therefore, the increment in counter register that would have happened after 1µs will now take place after 64µs. That is, the frequency has been scaled down by 64 times. As a result, longer delays can be realized without the need of an external clock.
Suppose we wish to blink an LED at a frequency of approximately 5 Hz i.e. goes on-off at every 0.2 seconds. We have been given that F_CPU is 1MHz. We have to keep in mind that our counter can’t count above 255. With proper calculation, we see that using a prescaler of 1024 and checking the counter for a value of 199 will do the job roughly.

Calculation: 1µs * 1024 * 200 = 0.2048 seconds.

Now, you will say – “Hey! That’s not right...I need precision.” Well then, you will have to use the 16-bit timer/counter. In that case, you can use a prescaler of 8 and the counter value to be checked is 25000-1 = 24999.

Calculation: 1µs * 8 * 25000 = 0.2 seconds.

Note: The value to be checked is 1 less than the number of counts because the counter starts counting up from 0, not 1.

Code: For 8-bit timer/counter0, register involved for prescaling is TCCR0 and bits are CS02, CS01 and CS00. The table tells that writing a ‘1’ to CS02 and CS00 enable the 1024 prescaler.
TCCR0 |= ((1<<CS02)|(1<<CS00));

Using the ‘if’ condition

Now that you are done with the enabling, configuration and calculations, you need to actually implement the timing effect. This is done by checking the value of the counter against the calculated value. In the 8-bit case, the counter register is named TCNT0. The calculated value in the 8-bit case above was 199.

if(TCNT >= 199)
 //your code here
TCNT0 = 0;

Observations from the above snippet:

      1)      Using a ‘>=’ is safer than ‘==’ as it is possible that the controller will miss the exact value due to some glitch.
      2)      It is necessary to reset the timer at the end of the ‘if’ condition, otherwise you will never get the desired delay (unless the value to be checked is itself 255! :P)
Assuming that the LED is connected to PORTB0 pin, the entire code using the 8-bit counter is:

#include <avr/io.h>

int main(void)
    DDRB = 0b00000001;
       TCCR0 |= ((1<<CS00)|(1<<CS02)); // enabling the timer with 1024 prescaler
       // on calculation the value to be checked comes out to be 199

       if(TCNT0 >= 199)
                 PORTB ^= (1<<0); //toggling the status of pin – XOR bit operator in C
                 TCNT0 = 0;

The code for the 16-bit timer/counter can be made on similar lines using the registers mentioned in the datasheet.

Clear on Timer Compare (CTC) Mode

In this mode of timing, the checking of the counter value with the desired value obtained from calculations is done by the hardware instead of the software i.e. the ‘if’ condition. As a result, the time wasted in executing the piece of code is saved which can be fruitful in a complex application.
The overall funda of working remains the same except that instead of an ‘if’ condition, we store the desired counter value in a particular register and as soon as the counter obtains that value, the controller  sets (writes ‘1’) a bit in a register. Hence, we just need to check the status of a bit regularly rather than compare values, which is a much heavier operation.

Registers involved

      1)      The CTC mode is enabled by writing a ‘1’ to the WGM01 bit in the TCCR0 register (See table on Page 80).
      2)      The clock frequency selection for CTC is done in the same manner as the crude method.
      3)      The register used to store the value against which the counter value is to be compared is OCR0.   Naturally, it is an 8-bit register.
      4)      The bit that is set to ‘1’ when the counter reaches the value stored in OCR0 is the OCF0 bit in the TIFR register. A very important behaviour of this bit is that to reset this bit, we have to actually write a ‘1’ to it. The circuitry is such that it requires to be set to be reset.

#include <avr/io.h>

int main(void)
    DDRB = 0b00000001;
       TCCR0 |= ((1<<CS00)|(1<<CS02)); // enable the timer with a prescaler of 1024
       TCCR0 |= (1<<WGM01); // enable the CTC mode
       OCR0 = 199; // store 199 into OCR0
        if(TIFR & (1<<OCF0)) // check if bit OCF0 is set to '1'
                     PORTB ^= (1<<0); // toggle status of pin PORTB0
                     TIFR = (1<<OCF0); // write a '1' to OCF0 to reset it

Therefore, the same timing operation carried out by the Crude Method is carried out by CTC Mode operation in a much more efficient manner.

The aim of this post was to cover the basics of timers in microcontrollers and how they work. A more detailed post on timers later J
See ya!

Wednesday, July 27, 2011

Serial Communication on ATmega32/16

Hello all. In this post, I will be covering a very basic introduction to RS232 based serial communication on ATmega32/16 using the USART hardware. But before you start reading, let me warn you – this post is a bit lengthy (but contains everything you need as a beginner...so no skipping :P), so bear with it. Secondly, please keep a datasheet of ATmega32 ready with you, this is the link.

The Basics

I want to talk to my friend. I use my vocal cords (hardware) to transmit meaningful information (software - analogy) but using the rules of language to do it, so that he can understand it. So generalizing, for any form of communication to take place, you need hardware, software and some rules that govern the communication, right?
In the opening statement to this post, I referred to three terms which are very important to understand. Most of the time, there is always a confusion regarding this terms and it is desirable to know the difference. Amongst various advantages, it helps the show-off factor.
First of all, serial communication is the form of communication in which data is sent – one bit at a time - across a communication channel. The other option is parallel communication, in which, many bits are sent simultaneously across the communication channel. Needless to say, parallel communication is faster than serial communication and also easier to fathom. But a major disadvantage is the cabling cost, which is a very important factor in the transition from parallel to serial communication over the years.

RS232 (RS = Recommended Standard) is a protocol – a set of standards/rules – using which control signals are sent to and from the transmitter and receiver used for serial communication. In very simple words, RS232 is a set of rules by which you can perform serial communication. That 9-pin male socket at the back of your desktop’s CPU is a serial port that carries out communication using RS232, when in use.

USART (Universal Synchronous and Asynchronous Receiver and Transmitter) is hardware – an integrated circuit – most of the times, that helps accomplish serial communication. USART is present inside the microcontroller – begging you to use it.
So, we know what the hardware, software and the rules are – now what?

Serial Communication – why should I care?

Serial communication is the basis of a lot of communication going around you. The communication inside your cell-phone, those noisy printers at the medicine stores, Distributed Control Systems in industries, MP3 players amongst many other systems. The protocols used vary from RS232, RS485, I2C, SPI, Token-passing etc.
As for techfest aspirants, those IP-based events in which you perform image processing on some software (Matlab, OpenCV, Scilab etc.) and are supposed to control your robot using the results of the same – involve serial communication. Yes – you CAN use parallel communication but that not only increases the hardware but also makes it necessary to have a desktop computer. What college kid uses a desktop?! :P
Apart from this, you can make a lot of projects based on this in various project competitions. So, hope you read on – with a purpose.

RS232 – information you should know

So we all agree that the set of rules used is the most important thing when you want to communicate with someone. If there are no rules, there would be no communication!
You will read on a number of sites that it supports both synchronous and asynchronous modes.   

Synchronous serial communication is that type of serial communication in which you supply a constant external clock and all the bits are transmitted with respect to this clock. The clock is analogous to a musical beat of any instrument, say drums. You must have noticed, in songs there is generally a beat going on and the words/lyrics start only at particular beats. Different instruments kick in, words stop and all types of such events take place at particular beats making the song memorable. Similar is the case with synchronous serial communication.

Asynchronous serial communication is that type of serial communication in which there is no need of an external clock. Immediately, the question comes to mind – how do I differentiate between messages? The answer is – with the help of start and stop bits. These bits are preset sequences of electronic signals that signify the start or stop of a meaningful message. In very simple terms, an asynchronous data-packet is like your data-bits enclosed in an envelope of start and stop bits. Hence just like content inside one envelope can’t affect the content inside another, the data inside one data-packet is separated from that in the other.
Also, a very important thing to know about RS232 is the logic level. In this protocol, a logical ‘1’ is signified by -3 to -15 volts and a logical ‘0’ by +3 to +15 volts (yes – it is NOT a typo, the logic is inverted). Hence, when establishing a connection between your computer and microcontroller, a logic-level shifter is needed to convert the TTL logic of your mu-c to the above-mentioned logic.

The Circuitry

The IC generally used for the logic shifting purpose is MAX232. It is quite cheap and almost universally used for this purpose. Refer to the following schematic for the circuit connections. Please note: in the 9 pins present on the serial connector, only three pins – RX, TX and GND are needed for most beginner applications. Refer to the pinout diagram of 9 pin male connector to identify the pins to be used.
Circuit Schematic
RS232 connector - male Pinout (9-pin)

Initialization of USART - theory

You have some knowledge about RS232. You have your circuit ready. Now how to make USART work?
USART has to be initialized first. Initialization is important to let the microcontroller know as to what conditions it has to work under. For beginner-level applications, initialization involves specifying the Baud Rate, setting the Frame Format, enabling the Transmitter/Receiver depending on the application and lastly, selecting the mode of operation – synchronous or asynchronous.

Baud Rate is the speed of your communication and is measured in bits per second. At this stage, you need not worry too much about the baud rate and how to set the correct clock frequency to get 0% error. I will discuss that in a future post.

Frame Format refers to how you want your data packet to look. How many start bits do you want? How many stop bits? How many data bits? Do you want a parity bit (need not bother about this now). We will focus only on selecting the data bits.

Initialization is done by writing ‘1’ or ‘0’ to particular bits of special registers meant for USART. This section 
covered only the theory. Scroll down for the code and register details. But if you are a beginner, I suggest you read this post sequentially.

Sending and Receiving data – theory

Once you are done with the initialization, you will be impatient to see some communication. So, without further ado, we will get to the theory of sending and receiving data. ATmega32/16 has a special register allocated for data handling, called UDR.

Sending Data – When using the USART for transmission, just writing a byte of data to the UDR register will ensure that your data is sent serially. ATmega32/16 also has the facility of checking if the data has been sent successfully and also if the UDR register is ready to accept data for transmission which help in more efficient communication.

Receiving Data – When using the USART for reception of data, the same register UDR is used to store the incoming data. On detection of a valid start bit/start bit pattern, data starts entering the UDR register and with the detection of a valid stop bit after the specified number of data bits (during initialization), the UDR register is ready to be read. ATmega32/16 has facilities to directly check if data storage inside the UDR is complete, thus simplifying the user’s task.

Since, the USART can behave as either a Receiver or a Transmitter at a given time, there can be no confusion as to what UDR should contain, at a given instant.

Coding Time! – Initialization and Sending/Receiving data

First things first – please re-read the above theory if the process of serial communication is not clear. Even if the applications get tougher, the theory remains the same.
Before you begin coding, please go through the USART Register Summary in the ATmega32 datasheet to know the registers that we will be fiddling with. When working with microcontrollers, any task – be it I/O, communication, ADC, PWM etc. – requires you to deal with registers, hence keep the datasheet ready – always.

Registers and bits involved in Initialization
1) Baud Rate: The microcontroller does not accept the baud rate value. Instead, this value is used to  calculate a value called Baud Number which is stored in a 16-bit register called UBRR (divided into lower  and higher byte – UBRRL and UBRRH). The equation used to convert baud rate into baud number is:
       Baud Number =  (F_CPU / (USART_BAUDRATE * 16)) – 1
      This number signifies that value from which the counter has to go to zero so as to get/send the next bit. Hence, choosing a value of F_CPU = 8 MHz and a Baud Rate of 9600bps, we get Baud Number = 51. Therefore, each time before sending/receiving a bit, the CPU counts from 51 to 0.   

     Code: Suppose the Baud Number, by calculation comes out to be 51 as above and is stored in a variable called Baud_Number, then the corresponding code is:
   UBRRH = Baud_Number>>8; // load upper 8 bits of Baud_Number into UBRRH
UBRRL = Baud_Number; // load lower 8 bits of Baud_Number into UBRRL

      2)   To enable the receiver and/or transmitter: This is done by writing a ‘1’ to the RXEN and/or TXEN bits of the register UCSRB.

Code: The piece of code that accomplishes this purpose is:

UCSRB |= (1<<RXEN | 1<<TXEN); // writing ‘1’ to both bits enables both receiver //and transmitter  

   3) Frame Format: Check out the table on Page 163 of the datasheet. The bit UCSZ2 is present in the register UCSRB. The bits UCSZ0 & UCSZ1 are present in the register UCSRC. Now, a very important thing to note is the default values of the bits. In the general case, the number of data bits required is 8 which requires a setting of 0,1 and 1 to the bits UCSZ2, UCSZ1 and UCSZ0. But this is the default configuration as well. Hence, there is no need to alter any setting.

Code: UCSRC |= (1<<UCSZ1)|(1<<UCSZ0);// self-explanatory

     4)  Selecting mode of operation: You can use USART in synchronous as well as asynchronous mode (as explained above). That is done by altering the UMSEL bit in the UCSRC register. Refer to page 162 for the details. Asynchronous mode is generally used (which is the default selection).
Code:  UCSRC |= (1<<UMSEL);

Now, that we have learnt the procedure to initialize, we shall move onto the communication part. At the end of the post is a sample code that features the entire initialization code together. Check it out!

Registers and bits involved in Sending data

As I explained in the theory section of ‘Sending Data’, we have to simply write data to a register named UDR to send the data serially. But before that, we have to check if the register is actually ready to receive data. That is done by checking the status of a bit named UDRE. If its status is ‘1’, it means that UDR is at your service! And if it is 0, well...wait for it to become ‘1’ because it is already busy serving you.
Code: Assuming that the data to be sent is stored in a variable named Mujhe_Bhejo:

while (UCSRA & (1<<UDRE) ==0)
{}; // do nothing till UDRE is ‘0’, please notice the bit operations performed to //check the status of UDRE
UDR = Mujhe_Bhejo; // writing the variable Mujhe_Bhejo to UDR

Register and bits involved in Receiving data

As I explained in the theory section of ‘Receiving Data’, in order to receive data, we have to simply transfer the contents of UDR into a variable. But before this, we have to check if we have received the entire byte. This is done by checking the status of RXC bit. If RXC is ‘1’, then there is an unread byte in UDR which needs to be emptied so as to receive the next byte of data. Sounds OK? Here’s the code.
Code: Assuming the variable used to store data from UDR is Mai_aa_gaya:

while (UCSRA & (1<<RXC) ==0)
{  }; //do nothing till RXC is still 0, RXC = 0 means that data is still being //received
Mai_aa_gaya = UDR; // transfer contents of UDR into your variable

Sample program – the serial loop

For the sake of having a full working code for serial communication, we will write a code for a circuit in which the RX and TX pins of either the micocontroller or the RS232 9 pin connector are shorted. If you are shorting the RX and TX of a microcontroller, then you won't need the MAX232 circuit as you are not involving any external device.This circuit will form a loop. Hence, a data that you send from the mu-c should come back to it. Following is the code with comments for understanding.

# define F_CPU 8000000UL
#include <avr/io.h>
#include <util/delay.h>

int main(void)
  UCSRC |= (1<<UMSEL); // select asynchronous mode
  UBRRH = 51>>8;   // higher 8 bits of 51
  UBRRL = 51;      // lower 8 bits of 51
  UCSRB |= (1<<RXEN)|(1<<TXEN); // enable transmitter and receiver both
  UCSRC |= (1<<UCSZ0)|(1<<UCSZ1); // number of data bits is 8
  char Mujhe_Bhejo = 'a', Mai_aa_gaya;
        while(UCSRA & (1<<UDRE) == 0) {}; // empty loop - to wait for UDR to be ready for data
                     UDR = Mujhe_Bhejo;
                     _delay_ms(10);  // you can omit this delay if you want - just 'timepass'
        while(UCSRA & (1<<RXC) ==0) {}; //empty loop - to wait for UDR to be ready
                     Mai_aa_gaya = UDR;
                     _delay_ms(10); // same with this delay as above


This post would not have been possible without the following references:
1) AVR Freaks - Tutorial - Excellent tutorial.
2) Scienceprog tutorial - Again....awesome!
3) Extremeelectronics tutorial - Desi tutorial - but very good !

And some other pages from where I gathered tidbits of info.


Hope, this post introduced the concept of RS232 based serial communication on a microcontroller well. Please try it out yourself. Trust me, you will enjoy the first time you receive a sent byte back. Urmish Thakker and I did...immensely.
Please rate this post (option is available at the very end of the post). See ya!

Sunday, July 17, 2011

About Robotics and Techfests

Hello everyone. In this post, I will be sharing basic generalized information for robotics events in major technical festivals and also a list of some of the major technical festivals (more popularly, “techfest”) in Indian engineering colleges.

Technical festival – briefest info 

One of the parameters on which an engineering college is judged by people is the quality of its technical festival. You will notice that the technical festivals of the top engineering colleges in India are very reputed. The IITian techfests are all very well known and well-attended by colleges from all over India. The major features of a good techfest are the quality of their workshops, guest lectures and the diversity in events. Events range from technical to non-technical and further, the events may be multi-disciplinary which cranks up the participation.

Robotics in techfests

All the major techfests feature robotics events which generally have a pre-declared problem statement. The teams or individuals are supposed to register for the event online. Some techfests also require the teams to submit a Team Description Paper (TDP) or some other similar document, at least a month before the event. In the TDP, apart from the team description, the teams also have to let the organisers know as to how they are going to tackle the problem statement, a photograph/video of the robot progress, the brief list of inventory used etc. The TDP deadline also acts as a wake-up call to the teams that had conveniently registered in full enthusiasm and forgotten all about it on-campus (Talking from experience :P).

General problem statements

Generally the problem statements require the team to make a manual robot or/and an autonomous robot

The manual robot problem statements generally revolve around picking up objects and storing it on the bot itself. Generally, there are restrictions in terms of the bot dimensions apart from others. Other types of manual robot statements are also possible – like building a ‘climbing robot’ that climbs up a flight of stairs or a vertical stack of rods. It depends from event to event and techfest to techfest.

As far as the autonomous robots statements are concerned, generally the teams are supposed to build an obstacle-avoiding robot or a line-follower robot. An obstacle-avoider is supposed to go from one point on the arena to another without colliding with any obstacle placed purposefully by the organisers. The line-follower robots are supposed to do the same but instead of obstacle-avoidance, the constraint here is that the robot has to move on a given circuit without stepping outside the track. These are the general cases. The other variety of autonomous robot very commonly a part of robotics events is the ‘IP-based robots’. IP is Image Processing. The task generally involves either number-recognition, character-recongnition or simply color recognition. And once this is done, the robot moves according to the required movements. Here too, there are restrictions based on dimensions generally.

The events that involve both manual and autonomous robot generally involve the transfer of contents lifted/collected by the manual robot to the autonomous robot following which the autonomous bot has to start moving. Such events are considered quite tough and also carry a large prize money.

One important restriction – many techfests require you to solder the circuits yourself or if you are getting the circuits printed, you are required to provide the Gerber files (they are like the blueprint of your PCB) of that circuit to the concerned organisers.

Links to technical festivals

Given below are major technical festivals, their organizing colleges and links to their websites.

      a)      The order of the under-mentioned fests is random and does not indicate ranking or anything else.
      b)      The source of the following information is Shubham Sharmathis is his e-pensieve J - I have just formatted the data and presented.

Sr. No. - Name – College - Link
1) Techfest - IIT Bombay – www.techfest.org
2) Tryst – IIT Delhi – www.tryst2011.com
3) Techniche – IIT Guwahati – www.techniche.org    
4) Techkriti – IIT Kanpur – www.techkriti.org
5) Kshitij – IIT Kharagpur – www.ktj.in
6) Shaastra – IIT Madras – www.shaastra.org
7) Technozion – NIT Warangal – www.technozion.org
8) Mindbend – NIT Surat – www.mindbend.in
9) Tathva – NIT Calicut – www.tathva.org  
10) Pragyan – NIT Trichy – www.pragyan.org
11) Engineer – NIT Surathkal – www.engineer.org.in
12) Renaissance – DCE, Delhi – www.rentech.in
13) Kurukshetra – COE Guindy, Anna University – www.kurukshetra.org.in
14) Felicity - IIIT Hyderabad – www.felicity.iiit.ac.in
15) Neuron – MNIT, Jaipur - www.neuronmnit.in
16) APOGEE - BITS Pilani, Pilani campus - www.bits-apogee.org
17) Quark - BITS Pilani, Goa campus - www.bits-quark.org 

Mind you all, the list is not comprehensive or restrictive or suggestive. It is only indicative. :P 

So what are you waiting for? Search for the event of your choice and start preparing!

Saturday, July 16, 2011

A very simple ATmega32 project

Hello everyone. In the last post, Atmega32 explained his I/O operations and how to address its ports and pins. In this post, I will be discussing the interfacing of a simple IR sensor (digital output) and a DC motor to Atmega32. But before that I want to tell you that before trying to implement this one, make sure you have blinked a few LEDs and LED patterns so that you are quite familiar with mu-c coding in C. So, the problem statement at hand is:

Design a microcontroller based circuit that enables a DC motor to rotate for 5 seconds whenever an obstacle is detected by an IR sensor. Also, during the motion of the DC motor, an LED should glow and switch off as soon as the DC motor shaft stops rotation.

Simple enough? Let us start with the basics.


      1)      An IR sensor – already discussed in an earlier post  
      2)      A DC motor driver circuit – already discussed in an earlier post
      3)      An LED and a resistor
      4)      A microcontroller – let us assume we are using Atmega32

Flow chart:

Circuit schematic:

The circuit schematic has been drawn using EAGLE.

Choice of I/O pins:

We have chosen:
      1) PB0 as the sensor input pins
      2)      PB1 and PB2 as the input pins to the motor driver circuit
      3)      PB3 as the LED driving pin

Alternate problem statements:

Done with this much?
Now try to tweak the problem statement by changing: 
      1)      The duration of the motor rotation
      2)      The direction of motor rotation
      3)      The on-off behaviour of the LED (switching off when obstacle detected and vice versa)
      4)      The range of your IR sensor by changing the potentiometer resistance
      5)      The I/O pins involved


      1)      The number of pins required for this circuit is only 4 whereas the available number of I/O pins is 32. You can go for a smaller controller like any one of the AVR Attiny series. The code won’t change. But the project settings in your development IDE will.
      2)      This circuit or a modified form is a basic component of almost any autonomous robot. Eg: Obstacle avoider, line-follower, micromouse etc.
3)      The IR sensor output is a function of the colour of the obstacle. Try it out yourself J
Later posts will also cover some more helpful microcontroller projects. Cheers!