Thursday, August 27, 2009

Interfacing LCD with Microcontrollers


Tutorial 2009-10/I

[This is a tutorial written for Embedded Hardware Design Course here at IIIT-Hyd]

LCD (Liquid Crystal Display) has become very popular option for displaying in Embedded Applications. Since they are very cheap and easy to interface with microcontrollers, they are widely found in devices like telephones, vending machines, washing machines, toys etc.

LCD comes in several varieties i.e. 16*2, 20*2, 20*4 etc. These different LCD varieties can display different number of characters i.e. 16*2 can display 32 characters at a time.


The LCD module that we will be using is 16*2 JHD162A. This model has 2 lines and 16 rows of display blocks. Each block can be used to display 1 character. So there are total 32 such blocks. One block has 8*5 pixels. Depending on which pixel is ON and which is OFF we can display several Alpha-Numeric characters. This model also has a green backlight, which helps us to see the display even in dark. In reality this module consists of a controller chip, a segment driver chip, LCD display and some passive components.

There are total 16 pins in the LCD module.

Pin Number

Pin Name

Pin Function

Connection to ATMega16



GND Supply



+5V LCD Power



Contrast Adjustment



Register Signal Select(Command/Data)




Read/Write Select




Enable (read/write enable)




Data pin




Data pin




Data pin




Data pin




Data pin




Data pin




Data pin




Data pin




Backlight Power +5V



Backlight Power GND

These connections have already been made to the USB BootLoader Kit so when you insert the LCD module properly, the connections are made as mentioned in the Table.

While using LCD, we can think a simple analogy for its operation. Each of the 32 blocks is a memory, as soon as we write an ASCII number into one of these 32 memory locations the corresponding character is displayed on that block. The function of displaying the character after decoding the data is done by an onboard controller chip.

In reality the LCD module consists of several memory locations apart from the 32 dedicated for the display. Since LCD module can be used in several ways we need to select one of these modes and configure the LCD for this mode.

The various operations that we need to perform are:-

1. Write to LCD memory to display data

2. Configure LCD module by writing commands to memory location

3. Read data in Memory locations

4. Perform some special operations like Clear Screen , Bring Cursor to starting position etc

The various pins that are provided like RS, R/W etc acts as a way to do all these operations.The 3 control pins have important functions

1. RS The LCD has 2 modes of operation Character and Instruction. Depending on its value the data on the data line (DB0-DB7) is treated as either command or character. If RS is LOW then the data on DB0-DB7 is an Instruction and if RS is HIGH then data on data line is character

2. Enable – The pin acts like a clock for the LCD module, when there is a falling clock edge then the data on the data lines is taken in by the LCD module and processed.

3. R/W - This pin identifies if the operation to be performed is a read or write.

If R/W = 0 write operation R/W = 1 read operation

RS = 0 Command RS = 1 Character

E -> falling edge , data processed by LCD Module

To be able to correctly perform an operation we have to assign the values of these 3 control pins and data lines in a proper sequence.

Let’s look at one example i.e. displaying a character by writing to its memory location. The steps are:-

1. Set the data on the data lines i.e. the 8 bits of data are assigned to each of the 8 pins (DB0-DB7) like LSB -> DB0 and MSB ->DB7.

2. Set RS pin i.e. make RS pin HIGH.

3. Clear RW pin i.e. make RW pin LOW.

4. Toggle E i.e. make E high, wait for some time, make E low.

Another example, if we want to write a command, the steps are:-

1. Set command on the data lines i.e. the 8 bits of data are assigned to each of the 8 pins (DB0-DB7) like LSB -> DB0 and MSB ->DB7.

2. Clear RS pin i.e. make RS pin LOW.

3. Clear RW pin i.e. make RW pin LOW.

4. Toggle E pin i.e. make E high, wait for some time, make E low.

A very important point to note is that the sequence of these steps can be done manually using toggle switches only and the microcontroller is only used because the repetitive steps need not be performed manually again and again.

In the above examples we used 8 data pins and 3 pins for control signal i.e. total 11 pins of the microcontrollers are used. An efficient way is to use 4 data pins instead of 8. In case we are using 4 data lines , the higher nibble is send on these 4 data lines first and then we send the lower nibble on the 4 data lines. In this case we are using 7 lines of the microcontroller. This mode is called the 4-bit transfer mode. By default when we are using 4-bit mode the data transfer happens only through DB4-DB7 (the LCD pins) whereas DB0-DB3 are unconnected.

In the datasheet of LCD module we find a table shown below. This is the Instruction set of the LCD Module JHD 162A.

Let’s look at first row - SCREEN CLEAR. This Instruction tells the LCD module to return the cursor to the starting position i.e. (1, 1) and also to clear the screen of any characters. The code for this instruction is 0x01. If we want the LCD module to clear the screen, then we should write the command 0x01 to the LCD Module.

Similarly we have DISPLAY SWITCH instruction. It selects options for the display like Turning the display on/off, turning the cursor on/off, turn blinking of cursor on/off.

If we want to turn display on we set D (DB2) to 1, to turn cursor on we make C (DB1) 1 and to select blinking cursor B (DB0) is set to 1. Hence the final code of Display switch is 0x0F.

If we write a command 0x0F, then the LCD module will perform the above mentioned 3 actions.

Finally we will look at FUNCTION SET- this Instruction selects the 4-bit/8-bit mode (DL =0 means 4-bit transfer mode selected whereas DL=1 means 8-bit mode selected), N selects the number of lines in LCD (N=1 means a 2-line display), F select font type (in our case we have 5*7 type font which means F=0).

Hence to select a 4-bit mode, 2-line display and 5*7 font the value of FUNCTION SET becomes 0x28.

If Instruction INPUT SET is not given then by default after every character write, the cursor moved to next block. [But this does not implies that after writing to (16, 1) the cursor will automatically come to (1, 2)!!! you will have to set the address of cursor to (1,2) yourself.]

Instruction Set of LCD Module














Memory Address of Display Block on the LCD Module

The Memory addresses of blocks on LCD display are as shown above. So if you send a Command say 0x80, then the cursor will reach to the first block i.e. (1,1) similarly if you send a command 0xC5, then cursor will reach location (5,2) and so on. In this way you can move cursor to any position.

To make the LCD work with microcontroller you will proceed in this way:-

1. All the functions of the LCD will be written in a separate file named lcd.h, so that whenever you need to use the LCD functionalities, you will just include this header file lcd.h, and call the functions written in lcd.h to display or configure LCD module.

2. In the lcd.h you should have the following functions:-

(a) LCD_init(void)

(b) LCD_Send(char c, unsigned char DC)

(c) LCD_Send_String(char *s)

(d) LCD_GotoXY(unsigned int x, unsigned int y)

(e) LCD_Print(int data, unsigned int x, unsigned int y)

LCD_init – This function initializes the LCD module by setting 4-bit data transfer mode, turning the display on, turning the cursor on and setting the cursor to blink.

LCD_Send – This function takes two arguments c, DC. Here c is the data which we want to write and DC identifies this data to be a command or character (data) i.e.

if DC=1 => Data

if DC=0 => Command

LCD_Send_String – This function takes a string as input and after parsing it ,send character by character to LCD_Send() function , to print the character on by one on the display.

LCD_GotoXY – This function takes the cursor to position (X, Y) in the display.

LCD_Print – This function takes 3 argument i.e. data (a numeric value), and x, y co-ordinate of the starting position of the printing of the data. First this function calls LCD_GotoXY to move cursor to (x, y). Then the function calls itoa() function and send the resultant string to LCD_Send_String().

The Pseudo code of the functions are written as follows:-



Clear RS pin, clear RW pin.

Write a command to clear the screen

Write a command to turn display on, turn cursor on, turn blinking of cursor on.

Write a command to select 4-bit mode, 2 line display, 5*7 font.


// when we say write a command it means that the function LCD_Send is called.

LCD_Send(char c, unsigned char DC)


Break the 8 bit value of char c into 2 parts, upper nibble and lower nibble.

If it is command

Write upper nibble on data line

Clear RS pin, clear RW pin

Toggle E pin, put some delay (~1ms)

Write lower nibble on data line

Clear RS, clear RW pin

Toggle E pin, put some delay (~1ms)

If it is Data

Write upper nibble on data line

Set RS pin, Clear RW pin

Toggle E pin, put some delay (~1ms)

Write lower nibble on data line

Set RS pin, Clear RW pin

Toggle E pin, put some delay (~1ms)


// you will need to put delay while toggling E i.e. Set E, put 1 ms delay, Clear E.

LCD_Send_String(char *s)


Break string s into characters, say c1, c2, c3…

LCD_Send(c1), LCD_Send(c2), …..


LCD_GotoXY(unsigned int x, unsigned int y)


If it is line 1, send the command corresponding to address of 1st line.

If it is line 2, send the command corresponding to address of 2nd line


LCD_Print(int data, unsigned int x, unsigned int y)


Call LCD_GotoXY(x,y)

Break integer data into character and call LCD_Send_String().


Saturday, August 15, 2009

Travel - Part4 - Reaching Rameswaram

Somebody had said "Journey is Reward", but when the journey is a continuous 56 hrs , then I do have to think a lot. For the uninitiated ones I measure these travel times as the times between I get an opportunity to bath !!. Reaching Rameswaram was a 3 part journey from Shirdi to Pune, Pune to Chennai and then a link train to Rameswaram.

When our bus started from Shirdi it was around 10am , according to my research and travel agency this bus journey to Pune was supposed to take only 6 hours and we were supposed to catch a train for Chennai at 5:30 pm. There was some small incidence with the travel agency guys and this resulted in a bit of my ego getting hurt and melting away, but that resulted in a comfortable journey for us !!. The weather in Shirdi was wet and it was a very refreshing. Soon
when we got out from Shirdi and the road undoubtedly was good, the bus was smoothly cruising in midst of freshly sown fields and some of them with some greenery. It was raining lightly and the air was quite cool, the experience was just like it was a hill station. Pretty soon far away in the background mountains began to appear. This was the time when I really felt that this vacation was a good idea and I was going all gaga about it.

I was enjoying every moment of the scenery , weather and my state of mind also. What maybe did not cross my mind at that time , but was stinging me like a gadfly before was that I always believe that if we get something easily without struggling then that thing is not really worth it or alternative it is not so productive. Till now things had gone smoothly, it was hard to believe that GOD's were in a mood to play a little Humour with me. Suddenly I saw a bit far away a big mountain coming up and I got a feeling of something going wrong when I saw some vehicles on road of that mountain , pretty soon I could make out that they were actually stationary. Meaning we got a jam on the mountains !!! That's a deadly combo , even then I found I was
not feeling in any hurry. Every minute delay means our tight schedule schedule was getting even tighter. I had got what I wanted. . With the jam not showing any chance of lifting up , since the vehicles from opposite side were just not coming. My brain impulsively went to damage control and alternate planning mode. I thought that I will reach Rameswaram if we missed the train,
by taking bus to Hyderabad , then to Chennai and then to Rameswaram. I was just not willing to bog down and I thought that I will do whatever it takes to reach the destination. Gradually but painfully slowly the bus started moving for a small distance from time to time. Actually this narrow mountain road got this terrible jam because a long trailer (and I guess more than one) got damaged at a sharp turning, resulting in chocking the two lane road to a single lane. Well was that a coincidence that this road which never had a jam , got one on this fateful day, i guess so !. It took us finally 2 hours to get out of this mess, and then came the part which I hate the most , suspense. It was like an IPL match , runs vs deliveries left. Here the case was hours vs Km. I was literally counting every milestone and being totally hopeful that we would make it to the train in time. The suspense were on growing and surprisingly all the way through I still believed we would catch the 5:30 train. So it was already around 5:15 when the bus dropped us
at a bus stop which was also at some distance from the Railway station, we got a 3 wheeler immediately and by the time we reached the Station, it was already around 5:32 and it took some minutes to get to the platform , and then we heard the message that out train is arriving at right time at 6:00 pm. Now that was a real surprise. We checked our ticket and found that it was indeed 6 pm not 5:30. Had it been 5:30 and would the train had been right time, we would have easily missed it. I heaved a long sigh of relief. Soon the train came and I happily boarded it. So even with preety descent planning , it all boiled down to the fancy of GOD.

The Train journey started and it was in general inconsequential. Except one thing, at some station before Ranigutta(where people alight for Tirupti) the train had to slow down and stop at some station for about an hour. When the train started again, we got to know that the the tracks were being repaired hence this delay ,but surprise was the fact that when train reached Ranigutta , but was just 10-15 min late , meaning some smart guy in Railways had anticipated this delay and did some positive correction for it well in advance. So we reached Chennai Central at nearly right time. The next train was from Chennai Egmore Railway station and we had 3 hours before that.

We reached Egmore in a three wheeler, the first task at our hand was to confirm that we had reached the right place and our train will be leaving from here. Next we went to the Reservation counter to get one ticket canceled. I was a bit elated as well as amused to find the total difference in the way the queues were formed . In here there was no queue that I had known earlier, the queue was formed by sitting peoples. When the front chairs became empty ,the peoples in the next row used to come and occupy them and so on. This was a surprise so as to say and I justified the behavior of people because of a mere presence of a policeman. Had he not been there , there wouldn't have been such a civilized show of behavior.
Later we occupied the Waiting room and I went out looking for a shave. While I was roaming outside and around railway station, a boy(visibly poor) aged around 10 stopped and asked me in Hindi, where I was from (in a dialect that seemed like Maharastrian). I thought he would like to ask for way to some place. Then when I replied in Hindi , he told that his father has been lost and he and his mother needs to go to Mumbai , and they have no money for buying a train ticket !! Now as a rule I don't give alms, reason being that I believe that if you give money to a beggar than he may use it for some wrong and probably anti-social activity and you will be a partner in that. But here I don't know why I felt that this was a time I should change my rules. It appeared that those guys were indeed a needy case. So after some waiting(i was pretending to be thinking) I handed over Rs 100 to that boy, then her mother said , we can't do with this only give us more , I was confused and instead of those two I was the one feeling helpless(because I couldn't decide if I was doing right or wrong), I looked up to the sky and said to heavens, I am giving money to these people because of you, now you decide if it goes to good or bad. With that I gave the boy Rs 50 more. It happened just then that a taxi driver intervened, I could barely understand what he wanted to say in Tamil but I got that part that he wanted this women and her child to be taken to police, I went further and grabbed the arm of the boy who was trying to get away with her mother. The taxi driver told me to take them to ticket counter and buy them a ticket. I aggread and asked them to return the money and I offered to buy them tickets instead. They were shocked at the intervention of taxi driver and I realized I was being tricked and had been almost been dumped. So I went ahead with more conviction and got my money back. I later thanked the taxi driver a lot. After that I was really feeling very disappointed , that how I allowed myself to get into such an embarrassing situation . Now after that I did change my rules concerning alms
"Charity is not for people who have not got the time to see through their money being spend well.Never ever give money as alms. It is always better and safe to pay in kind rather than cash to beggars".

Then after having a taste of Chennain food we safely boarded the Rameswaram Express.
When I woke up in the morning , in the far end , I could see tree line meaning we were closing in on to the Pamban Bridge.
I was really exited about Pamban Bridge or Indira Gandhi Bridge. I had read a lot about it and my imagination was that, when the train would be over the bridge it would really be scary with the bridge just like a thin straw , and the train slowly chugging ahead, with the constant feeling that a breeze will plunge the train into the ocean waters.
When the Bridge really came , it was great to see the ocean on both the sides and the narrow bridge with the train slowly moving ahead like a cautious juggler trying to balance itself on the rope.

I really liked the view there , both the rail bridge, the road bridge as well as the ocean. I did clicked a lot of pics. It was a place to visit again and again .

Then in no time the train reached its destination i.e. Rameswaram Station.
At the time of getting down , I had the usual feeling that finally I am in an unknown new place , will I be able to communicate well and go around the town in a normal way .

Tuesday, August 11, 2009

Travel - Part 3 - Shirdi

So here we were at the first stop of our journey at Shirdi. It was around 11 am and as we were starting to hunt for a suitable hotel , it began to rain lightly. Well we actually did not try to get accommodation in any of the Trust Run Buildings because at that time their was quite a long line. When we were still in our room it rained very heavily for half an hour and the whole climate became very cool and totally refreshing when compared to the heat of Delhi. Anyways after taking bath we went in for Darshan in the main temple. It was afternoon and normally at this time of year , there was not much rush and maybe it took us about half an hour to get Darshan at Sai Baba's Samadhi.

After that we were really hungry. So we turned our steps towards the Famous Prasadalay. After walking around 100mtrs from Main temple on the main road, we reached the complex. We purchased the food coupons which were Rs 6 per person(IIRC). Since we had come around 3 pm so here also we didn't encounter any queues. When I entered the main eating area , I was amazed, it was so big , I had somewhere read that NDA(National Defence Academy) had the biggest mess atleast in the whole country, but here this single hall was so big ,a few times bigger than a football field, that I really doubted the accuracy of the NDA mess capacity being the largest !!!. I asked one of the attendants there about the capacity of the Hall and he told 6000, I later found that a similar Hall was also there on the First floor of the complex and so I guess that 6000 figure was the combined capacity of both Floors. But size was not the only thing that was amazing there. The way the people there were serving, the arrangements, cleanliness etc was a sight to see. Everything was running like a clock work , the whole staff knew what to do and how to do. The Prasad was also very good. When we returned back to our room it was already 5. I had decided that it was a good idea to wake up really early the next morning so as to be able to attend "Kakad Aarti" . So I slept very soundly and uninterruptedly from 5 pm to 1:30 am.

When we reached the line , there was a queue , but how long it was , we couldn't make out. After waiting for about half an hour , when the aarti time began, all the people were lead into the main Hall in front of Baba's Samadi. Fortunately we got some place before the Hall was filled up. Then for some time the Holy Chants of Aarti were sang in unison by all the priests, and with this the daily routine of giving Baba a bath from the Holy waters, decorating Baba with fresh attires and later performing Aarti to Baba were performed. During that time a thought came to my mind, "great people or saints spend their whole life in service of others , following routines like rising very early and working very hard for the benefit of others and here I am seeing that even when they are not present with us physically on the earth, they still follow the same routine for the benefit of their devotees". Then slowly but in a well controlled fashion devotees were ushered one by one into the line to have a closer Darshan of Baba. Later we also went to Dwarakamai to see in amazement Baba's kitchen , Dhuni etc. To say that several millennium ago Bhagawan appeared on a place and so we go to visit the temple there is totally different from the fact that there is a place where really in our own time , Baba lived amongst people and the very fact that HE inhabited this soil in not so far a past , is a thought that overpowers you.

It was around 6 am when we were done with the Darshan and so after that we packed our bags and got a seat in a Pune bound bus.

One very important feature of Sai Baba Temples and the other complex managed by Trust was that everywhere I found out that there was no mis-management. Everything was going totally smooth, each security person knew what to do , there was provisions that the devotees face the least inconvinience as long as they are there. At regular interval in the queues , there were LargeScreen TV's so that devotees who are waiting can have a constant virtual Darshan. The main Samadhi Hall of Baba had lots of Gold plating as well as even more silver plating on the pillars and walls. The whole shine of these metals was very beautifully adding to the grandour of Baba's Samadhi and a Life size statue of Sai Baba Himself.
The temple complex had several amenities inside the complex itself, i.e. museum , Bank, ATM, book stalls, eating shops etc etc , I liked these things very much. There were lots of CCTV camera and this implies that the security was quite strict even though to a casual eye it might not be obvious.

Overall I was impressed by the way things were being performed in a clock work fashion.