Read Chip Huyen's answer to Who do you think is the best professor in the world and why? on Quora

Monday 30 September 2013

Microcontroller - A Beginners Guide - Writing the First Program to Display on LCD "Microncontroller-Made-Easy"

I know that you are ready to write the first program. You have been through a lot so far! While we are on the subject, let's recap the events. You went out and purchased th PIC microcontroller of your choice. I chose the PIC16F877A for my uses. You were introduced to the concept of microcontrollers how they work; and were also introduced to the programmer, the device that helps transfer the program into the microcontroller.
I write a program in C using mikroC PRO for PIC v5.6.1 compiler. I know its difficult to work with but it’s time that matters. Now I’m successfully write a program and below is the program:
//---------------------------------------------------------------------------------------------------------
//Programmer: Qamar Ul Islam
//Compiler: mikroC PRO for PIC v.5.6.1
//Target PIC: PIC16F877A
//Program for Display on LCD
//---------------------------------------------------------------------------------------------------------
#include<pic.h>
__CONFIG(WDTDIS & XT & UNPROTECT);       
char name1[40]={"  Microcontroller-Made-Easy  "};

void delay(int x)
{
         int d,l;
        for(l=0;l<x;l++)
         {
        for(d=0;d<4000;d++);
        }
}

void instwrt(void)
        {
       
        RC0=0;
        RC1=0;
        RC2=1;
        delay(1);
        RC2=0;
        delay(1);       
}

void datawrt(void)
        {
        RC0=1;
        RC1=0;
        RC2=1;
        delay(1);
        RC2=0;
        delay(1);
        }
void lcdin()
        {
        PORTD=0x38;
        instwrt();
        PORTD=0x0c;
        instwrt();
        PORTD=0x01;
        instwrt();
        PORTD=0x06;
        instwrt();
        PORTD=0x80;
        instwrt();
        }
void main(void)
        {
        int a;
        TRISD=0x00;
        TRISC=0X00;
        lcdin();
        for(a=0;a<32;a++)
        {
                   PORTD=name1[a];
                datawrt();
        }
while(1)
{
        PORTD=0x18;
        instwrt();
        delay(50);
}
}
And Here is a snapshot of the experimental setup shown below:


Hope you’ll find interesting as your hobbyist project.
Don’t forget to write us.

Saturday 28 September 2013

Microcontroller - A Beginners Guide - Writing the First Program to Turn On an LED


I know that you are ready to write the first program. You have been through a lot so far! While we are on the subject, let's recap the events. You went out and purchased the AVR Atmel Microcontroller of your choice. I chose the ATMega32 for my uses. You were introduced to the concept of microcontrollers how they work; and were also introduced to the programmer, the device that helps transfer the program into the microcontroller. You built a convenient interface that is used to connect the SPI pins to the correct pins of the microcontroller. You verified that the programmer (USBTinyISP) drivers were installed correctly for the 32-bit and 64-bit versions of Windows (XP, 7 and Vista). You also installed the programming environment installed the "Programming Environment" called WinAVR so that you can have an environment in which to write your program, and then transfer it into the microcontroller. And to make sure that everything functions correctly, you used avrdude totested the programmer while plugged into the computer and the microcontroller. Recall that this program is the program transfer utility to move our compiled program into the memory on the microcontroller. Finally, you built the first circuit so that we could have something to write a program for. Whew... that was a lot! But since you jumped through all of those hurdles, the hard work is over and it's smooth sailing from here on. Hopefully you were able to get through the previous steps without any problems--so now let's get on with our first program.
For the sake of simplification, let's categorize the function of the microcontroller into three categories: Control, sensing and communication. We'll leave the details of how to develop each of these functions, and delve into these details as we write the various programs. Note that there are many ways to program these functions. For the first program, we'll make the microcontroller "control" something. And as you know from the previous post, we'll be using an LED for this purpose. Basically, we will turn the LED on. Yes I know... boring, right? Well I need to start somewhere! As I take you through the experience of programming, I will add more complexity a little at a time so you are easily able to wrap your head around these important concepts.


So at this point you're probably asking...how do we make a program to control an LED? Well, it's really easy: We will simply tell Pin0 on PORTB to output 5 volts. Remember that this is the pin to which the positive lead (anode) is connected. The first key in this scenario is "output, " and the next is "5 volts." There is a way we can tell a particular pin to be set to be an output from the MCU. Once a pin has been set to provide output, you will then be able to control that pin and make it either high (5 volts) or make it low (zero voltage). And since there are only two states for this pin in the output mode (5v or 0v), and only two states for the mode itself (input or output), you only need to set the value to either logical 1 or a 0. Note that this must be accomplished for each pin we wish to use in our circuit. But before we get to plugging in a 1 or 0, let's talk about input versus output. When a pin is in input mode, it is listening for a voltage. When the pin is in output mode, the it can be charged at 5v, or not charged at 0v. That's it!
There are many ways to do this. This is not to confuse you, but rather to make things simpler. I will be introducing you to one of the many ways to accomplish this task, and later I will explain some other methods while writing other programs. Note however that while this first method is great for introducing the concept, it's probably not as good in practice. Therefore you will see other methods in future programs that will leave contextual pins (those pins on either side of the pin of interest) unaffected, as they may very well have been previously set in the program. But since we're writing a simple program, we won't worry about this complexity at this time.
To pick the output mode for a pin, you will use the Data Direction Register (DDR). Oh man! What is a register?!? Don't let this worry you. A register is simply a memory location that makes the microcontroller react in some way. We use a register to set a state for the microcontroller, or make the microcontroller do something. It's like reflexes, or tickles. When a person tickles another person, it invokes laughter. We can make the MCU do something by setting a specific value in a register. That's all you need to know at the moment.
So when you use the DDR register, you are able to set the pin to either output data, or accept data input. But we said input or output, now you're saying data also. The term "data" used here simply just adds another dimension to this idea in the form of "time." If you make a pin 5 volts, then zero volts, and then 5 volts again...you are actually sending 1s and 0s. To the pin, this is nothing more than a high (5 volts) state, and then a low (zero volts) state: The MCU sees this high/low logic. And you can also receive data in the same way.
There are several ways to set pin0 for port B to output. One way to do this is to write:
DDRB = 0b00000001;
Let me explain. "DDRB" refers to the Data Direction Register for port B; "0b" is to tell the compiler that what follows is the binary expression of a number; and the "1" on the end denotes the pin 0 position (the first pin in port B). Recall that there are 8 pins for port B; pins 0 though 7. There are also 8 digits in our line of code. So each digit represents a pin on the port, and we can use the individual digits to specifically refer to any one of the pins in port B. So the '1' at the end of our code statement refers to the first pin in port B, which in this case is pin 0. (Recall that C and C++ are zero-based languages, so the first index of a data structure refers to is the zero'th element; the second index refers to the first element, etc.) We really don't need to get any more complex at this point, as this will be covered in much more detail in future tutorials. However if you would like to know more about the binary system, check here.


Now we need to apply 5v to the pin. This works just like the DDR code statement we used above. We will use a binary number to put 5v on that pin (pin 0) using this statement:
PORTB = 0b00000001;
The only difference between this and the previous statement is that we are now using the PORT register. This register knows the pins of that specific port, and gives us access to specify the actual data value (logical 0 or 1) for these pins.
Now we need to talk a bit about the overall structure of our program. All programs need a specified place to start the execution. It's like giving someone a set of instructions on how to make a cake without telling them which step to start on. The "main" function is the place where all C/C++ programs start execution. So we will create a main function.
int main(void)
{
}
In order for the program to understand the DDR and PORT register information and how these work within the microcontroller, an include statement must be added that contains all of the information about the AVR microcontrollers. This include statement will probably be in all of your programs.
#include <avr/io.h>
int main(void)
{
}
When the compilation process starts, the pre-processor portion of the compiler looks in the "avr" directory for the "io.h" file. The ".h" extension here indicates that this is a header file, and (as its name implies) the code within that file will be inserted at the beginning (head) of the source file you are creating. Now we can insert the DDR and PORT statements into our code, since the inclusion of the io.h header file has informed the compiler about them.
#include <avr/io.h>
int main(void)
{
DDRB = 0b00000001; //Data Direction Register setting pin0 to output and the remaining pins as input
PORTB = 0b00000001; //Set pin0 to 5 volts
}
Now the direction of the pin0 is set to output, with a value set at 5v. But we are still not finished. We need to keep the microcontroller running indefinitely, so we need a routine to do this. This is called an endless (or infinite) loop. The infinite loop makes sure that the microcontroller does not stop performing its operations. I will explain this in more detail when we have stuff to do within this loop. There are several types of loops we can use for this purpose, but for this demonstration I will use the while loop. It means the same in English as it does in code: For instance, "while" I have my hand up, you should keep clapping.
#include <avr/io.h>
int main(void)
{
DDRB = 0b00000001; //Data Direction Register setting pin0 to output and the remaining pins as input
PORTB = 0b00000001; //Set pin0 to 5 volts
while(1)
{
//Code would be in here if it needed to execute over and over and over ... endlessly
}
}

Note that we use a '1' as the argument to the while loop, because anything other than '0' is a logical true. Therefore the while loop condition will never be anything other than logically true, and the program will continue to execute indefinitely (i.e.; I keep my hand raised).
So, here is the fruit of our labor. It was a long ride so far, but I promise, everything from here on will be gratifying and far less time consuming. In the next video and instruction, we will make the LED blink. We will investigate how to create a delay so the LED does not blink so fast that it looks like it's not blinking.
Reference:
newbiehack.com

Microcontroller - A Beginners Guide - Transferring a Program into the Microcontroller Part 2 (Drivers)


By now, you should have constructed the SPI interface. If not, you can either review the previous tutorial, or live with the flimsy wires. If you have read the first sentence more than two times after constructing the device I presented in the last tutorial, don't worry...the thing you made is the SPI interface! It's simply the 6-pin cable, wired to a straight set of 6 pins that match the proper pin arrangement on the microcontroller.
At this point though, we need to make sure the computer will recognize the programmer. This is the USBTinyISP device from sparkfun or adafruit industries, that connects the computer to the microcontroller. Like everything in this universe that plugs into a computer loaded with the Windows operating system, there is a need for drivers--and this programmer is no exception. However my video will provide you with instructions for the complete installation of these drivers, so there is no more guessing!
Since I am installing the driver on my computer running the Windows 7 64-bit operating system, the installation is somewhat different than the procedure for the 32-bit operating system. No need to worry though--if you can click and drag files from one folder to another, you will not have a problem. Apparently, the drivers from sparkfun.com do not contain the latest version of the 64-bit drivers. This is completely explained in the video however, so you should have no problem installing the driver if you are running a 64-bit system.
Here are the general steps to get the drivers on the system, and the programmer recognized by either a 32-bit or 64-bit Windows operating system.
  • Go to sparkfun.com and navigate to the Pocket AVR Programmer page (left pane under "Programmers - AVR") . The link is supplied so you don't need to pay attention to my overly verbose description.
  • Enjoy the beautiful red, black and white color scheme.
  • Scroll down and find the Windows Driver link under Documents. Or, ahem, just click the link.
  • Now you have the pocketprog-driver.zip file on your computer somewhere. Let's hope you know where it downloaded! If you do, whew...! Unzip the file into another folder for which you know the location.
  • Before you fiddle with the contents or try to install it for some reason, a couple of files need to be revised for the 64-bit version of Windows 7 or Vista. However, if you are using a 32-bit version of Windows, go ahead and start the installation. You can simply disregard the following explanation for the 64-bit procedure.
  • Now, go to the libusb sourceforge page and click on the latest release.
  • You will see a few or more files listed. You want the bin file (i.e. libusb-win32-bin-#.#.#.#.zip).
  • Now you have another .zip file to find on your computer. Go ahead and unzip it into a known location.
  • Go into that folder and navigate to the bin folder, then into the amd64 folder. There will be two files there ghcalled libusb0.dll and libusb0.sys. Rename these files to libusb0_x64.dll and libusb0_x64.sys.
  • Copy these files into the pocketprog-driver folder, overwriting the existing version of these files.
  • For installation of the newly downloaded drivers, I will show a rather non-traditional method which I like very much. This is the "add legacy hardware" mode. Yes, there is such an animal in Windows!
  • Click on the Start menu.
  • Right-click on "Computer"
  • You will see a menu... select the "Manage" option. It will probably have a yellow and blue shield next to it.
  • Click on "Device Manager". Yes, I know you know of a different way to get to the device manager. Well, now you know another way.
  • Right-click on the top of the list (the computer name, typically ends with a "-PC." Mine is patrick-PC). You guessed it, my name is Patrick.
  • On the menu, select "Add Legacy Hardware." If you are wondering, "Legacy" means hardware that is still in use and has been for a while; or hardware that Windows does not have on their all-powerful hardware list. Well, that's my definition for it anyway...
  • Press "Next" when the wizard is introduced.
  • On the next screen, select "Install the hardware that I manually select from a list (Advanced)," so the radio button is changed to that selection. A radio button is a windows control that looks like a circle with a small blue spherical dot in the center.
  • Click Next
  • The "Show All Devices" option should be highlighted. Make sure of this and click next.
  • Click on the "Have Disk" button.
  • Using the "Browse" button, navigate to where the pocketprog-driver folder is located. If you selected the correct folder, you will see the pocketprog.inf file located in that folder. Double-click this file and the driver should start to install.
  • Review this procedure again, or watch the video a second time if the installation doesn't seem to go as planned.
Reference:
newbiehack.com

Microcontrollers - Creating an SPI Interface from the Programmer to the Microcontroller



So, at this point, you should be familiar with the concept of the microcontroller (MCU). You should also have an appreciation for the general uses of the microcontroller. You have a basic understanding of the pin assignment and the Ports. And, hopefully, you are excited with what a microcontroller can do, like sensing and controlling the environment. Finally, you know that we will get into the programming side of things--given the title of this page, and the fact that we touched on it in the introduction).
Now we will need to get more in-depth with the programming. However before we can get a program loaded onto the chip, we need a good way to connect the SPI (Serial Peripheral Interface) connector to the chip. We couldn't very well shove the connector into the pins of the microcontroller, now could we? And sticking wires in the end of the connector and into the breadboard is flimsy, unattractive, and possibly harmful to the MCU if a wire carrying voltage is accidentally applied to the wrong pin.
Therefore to maximize our chance of success and standardize each and every connection attempt, we will construct a small board that contains a header (little metal pins that stick up) that the SPI connector can use, and also a header that will correspond to the appropriate pins on the microcontroller. The latter can simply be a single row of six pins since the makers of the Atmel AVR Atmega32 microcontroller so thoughtfully located these pins together. This will allow us to make our MCU interface board with a very narrow size, which will reduce the area covered on the breadboard (as can be seen in the video). Oh yeah, the video contains a bit of soldering, so you can learn that too!

Ok, so to reiterate from the last tutorial, there is a programmer that is needed between the computer and the microcontroller. It should be noted that there are several different programmers that can be used, and a suitable model can be had from either Adafruit Industries (USBTinyISP) or Sparkfun (Pocket AVR). Some of these programmers look totally different from others, but all of them basically do the same thing--provide an interface between the computer and the AVR microcontroller. That's it! Note that if you are not using the AVR Atmega32 microcontroller, then you must check the compatibility of the programmer you choose to use. Also note that many of these programmers use the same drivers, an issue which we will get to in the next tutorial.
The connection between the computer and the MCU is really quite simple, so there should be no reason to be afraid of (or timid with) doing these steps to get a program into the microcontroller. So, let's get to it! Remember that the purpose of making such an interface board, is to insure a proper connection each and every time we need to load our program into the MCU. So if you want to make a board like I've shown in the video, then just get out your soldering iron. Don't be afraid, get it out! Well, you should be careful, as it gets hot. But don't let that get in your way. Just make sure to read all of the manufacturer's instructions on the proper operation of the soldering iron. Also, don't forget to wear goggles; and don't breath the solder fumes. Some people use a suction fan to get the fumes away from the workspace.
Check out the diagram above. Yes, it's a bit messy, but I drew this while caffeine was flowing through my system! The SPI connector pin-out is to the left. There are arrows from this SPI interface block to the corresponding pins on the AVR Atmega32 microcontroller. There will be no need for fancy components to complicated this process, so don't worry--we are only connecting wires from the SPI device to the pins of the microcontroller.
Let's run through the connections between the SPI device and the MCU:
  • Top left SPI pin is connected to the MISO (Master In Slave Out)
  • Middle Left SPI pin is connected to the SCK (the clock pin)
  • Bottom Left SPI pin is connected to the Reset (Reset just does exactly what is says, and you can be sure we will talk about this pin later!)
  • Bottom Right SPI pin is connected to the GND (Ground, or zero volts)
  • Middle Right SPI pin is connected to the MOSI (Master Out Slave In)
  • Top Right SPI pin is connected to the VCC (+5 Volts, if you want, you can go check voltage requirements in the summary, or the HUGE manual, and trust me, this is not an easy read!).
That's it!! All you need to do now is solder the wires between the two sets of headers (remember this term? They're just pins that stick up and insert into a female header). Note that the picture near the top of this page shows the female header plugged into the male header. Once these wires are all connected and soldered-up, it should look something like these pictures. However, if you want to get crazy and do it differently, please go for it!! I encourage creativity.

As can be seen in the pictures, the connections from the wires to the headers are made using solder bridges. A solder bridge is just solder that "blobs" together to connect two locations. These blobs sort of look like little figure 8's, or infinity symbols. And, it's not too hard to create these bridges. All you need to do is solder the two wire/pin connections like normal, and then add just a little more solder while holding the iron over both of the connections. This will provide enough solder to create the bridge. However, there is the possibility that they won't bridge. Ah, the bane of existence for most solderers...! The bridge is generally not advised in most applications; but in this case, it's simply the easiest way to make the connections between the SPI and MCU pins, and the corresponding wires that connect them. Once you have enough solder applied, and the hot iron is over the two connection, pull the iron straight up along the pin and the bridge should be maintained. Otherwise you may destroy the bridge if the hot iron is allowed to once again make contact with the main body of the bridge. Don't worry--the video shows this very nicely, and you should get the hang of it pretty quickly.
So, wasn't that easy? Now, we will get into the software part of it in the next tutorial. We will find the software on the internet to: First, recognize and drive the USBTinyISP programmer (or, if you choose, the Pocket AVR Programmer); and second, install the development environment. Note that by "driver," I mean to install a driver under the Windows OS, and the "development environment" is simply the application you will use to write the programs that will later be transferred to the chip. If you are using installing this program on another OS, like Linux or the Mac, you will still be able to follow along. Here and there, I may speak of those other wonderful operating systems and how to do things (or find the resources that will help). The programming is the same, but the development environment will probably be slightly different.
Reference:

Microcontrollers - A Beginner's Guide - Intro to the AVR Atmega32


This is the first in a long line of tutorials aimed to provide a beginners guide and tutorial based around the Atmel AVR Atmega32 microncontroller. I will show you, through examples and projects, how to program and provide functions for this microcontroller and what the uses and applications are.


With microcontrollers in general, it is good to know that these little chips are found everywhere. You can find them in microwaves ovens, new applicances, automobiles, televisions, etc. These microcontrollers control and sense the surrounding electronics and environment. For example, microcontrollers can provide output to a display, motor, LEDS, etc., sensing the environment, such as tilt using an accellerometer, light, angular velocity using a MEMS (Microelectromechanical System) gyroscope, sound, encoders for movement, temperature, and button or keyboard input.
To give you a basic understanding of the microcontroller, the AVR Atmega32 microcontroller is considered to be a computer on a chip. The microcontroller is able to execute a set of instructions in the form of a program. The program language that I will be using for theseprojects is C++. To giv ethe usersof this website the best opportunity to learn, the C++ programs will be explained is great detail.
The really cool thing about microcontrollers is that you have control over all the pins. For a beginner, this can be a difficult concept to understand, especially having no experience with electronics. Don't fret, I will walk you through each tiny detail. Each pin has a special assignment, or can be used as an input or output feature, with a few exceptions, the power pins.


On the left hand side of the chip, looking at it form the top and the little triangle is at the top left, there are 20 pins (this is a 40 pin microcontroller). The first starting from the top left are the PB0-7 pins. That's a total of 8 pins as the index of these pins and most everything in the program starts with an index at 0. This set of pins are called "Port B" and there are 3 other ports labeled from A to D. These ports can be set to receive information and is called INPUT and they can be set to send voltage out in some form called OUTPUT. General power pins to receive the power for the chip called VCC and GND. All but one pin of Port D (PD0-6) is also located on the left side (lower section). PD7 (Pin 7 of Port D) is all alone starting the right hand side of the microcontroller.
Continuing on the right side, and the ending of Port D, Port C continued from the lower corner up. From there on, may favorite pins continue, the analog to digital pins. These pins have the capability to sense the environment with the help of components that feed these pins an analog voltage. Dopn't worry about not understanding analog or even digita at this point, it will be explained in greter detail later. These analog to digidal converter pins compose Port A.
One example of the use of the analong to digital conversion would be, say, sensing the temperature. You can connect a component that converts temperature to a level of voltage called a thermistor to one of the Port A pins and the microcontroller will convert this voltage to a number from 0 to 255 (an 8-bit number - higher resolution is possible at 10-bits). The program that is written and stored into the microcontroller can use this temperature and respond in a specific way. For example, if you have the thermistor against a boiling pot, the microcontroller can respond and provide an output to another pin that beeps, or flashes a light.
Other features of this and other microcontrollers, other than the actual programming is the programming space (where the program is stored in the chip and how much space you have), memory, or space for data and variables that the program will use, and finally, there is a clock built into the chip that counts. The counting can be in many different speeds depending on the speed of the chip and the divisor that is selected for the speed. This is starting to get complicated, so I will back up. The counting can be in seconds, miliseconds, microseconds, or whatever you determine for the program and application that you select.
As this tutorial series is based on examples, I will provide a great deal of detail. Of course, the detail for the introduction would be impossible, and if you are very adventureous, you can take a look at the datasheet and manual for this microprocessor, but don't let that huge document sway you from wanting to learn this most incredible technology. Once you lear, there is no limit to the application, from tiny robots, to extremely large scaled architectural wonders that move and give off spectacular lighting effects, sometimes that interact with the environment.

Reference:


Microcontrollers - Introduction to PWM (Pulse Width Modulation)


In this video, I introduce the concept of PWM and provide a few examples of how PWM works.

Thursday 26 September 2013

About the Author:

Qamar Ul Islam                                                           
Assistant Professor
School of Engineering & Technology 
BGSB University (State University)


      
Profile:                                                                                           
Qamar Ul Islam received his Master of Technology (Instrumentation & Control Engineering) Degree (First Division with Honours) in 2013, Bachelor of Technology  (Electrical Engineering) Degree (First Division) in 2011 from Zakir Hussain College of Engineering and Technology, Aligarh Muslim University (AMU) and Diploma in Engineering (Instrumentation & Control) Certificate in 2007 from University Polytechnic, AMU, Aligarh. Currently He is working  as an Assistant Professor at BGSB University (State University) in Jammu & Kashmir, India since September 2016 and He is also former Assistant Professor at Vishveshwarya Institute of Engineering & Technology since March 2014. He is the first position rank holder in his batch of Diploma in Engineering (Instrumentation & Control). He is an alumni of Aligarh Muslim University and designed many blogs for the department. His teaching and research interests lie mainly in the area of Smart Sensing & Measurement, Instrumentation & Control and Control System. He has also attended following workshops and receives following certificates:
  • PLC/SCADA training “Siemens S7-1200, S7-300, TIA, WinCC Flexible HMI and Janitza Power Monitoring” from 01.02.2013 to 30.04.2013 organized at Deptt. Of Electrical Engineering,A.M.U, Aligarh, India.
  • Attended short term course on Development in Instrumentation and Control Engg under TEQIP-II program 2012 at Electrical Engineering department, A.M.U, Aligarh.
  • Attended short term course on Future of Electrical Engineering (Trends & Innovations)-2012 organized by Zakir Hussain College of Engineering & Technology, Department of Electrical Engineering, Aligarh Muslim University, Aligarh, India.
  • Securing First Place in Wizard Search Contest 2003 conducted by NIT @ School.
  • Attended workshop on “Advances in Gas Insulated Systems” held on 28-29 Jan, 2013 at Deptt. Of Electrical Engineering, A.M.U, Aligarh.

Follow me on:

google                                          
tumblr                                              
quora