A little PWM

08/27/08 | by anthony [mail] | Categories: Code, Projects

Now that we have most of the fundamentals down and you understand the basics behind microcontrollers, lets have a little fun.

Today's project is a 3 speed PWM(Pulse Width Modified) fan controller.

In this project the user selects the fan level (low, medium, and high) and the program adjusts the duty cycle (%on vs %off) of a 20KHZ signal accordingly. By adjusting the duty cycle we can control how fast the fan runs by limiting how long it is on vs how long it is off.

The code is fairly simple and very inefficient, but we will be working on it time to time to improve its efficiency and not waste clock cycles or memory.

The general flow of the program is like so:

1 - Set up environmental variables
2 - Set up ports
3 - Goto main loop
4 - Check for button press, increment/decrement COUNT variable depending on button press
5 - Check the count variable to see what "level" it is set at (High, Medium, Low)
6 - Adjust the duty cycle based on the level
7 - Return to main loop
8 - Call the table and output the level to 7 segment display
9 - Reset loop

Its fairly simple and works pretty well. However i think i should break down each part to help you better understand the garble of letters. The source is free to grab and modify at the end of the post.

Part 1:

We set up environmental variables by using the equ function, we set labels to places in the memory that are unoccupied. Thus, they will store a value like a variable and have convenient names. The three main variables are DELAY, COUNT and TEMP. DELAY is used for the delay loop, TEMP is used for temporary storage and COUNT is the variable we use to set the speed level.

Part 2:

We set up the ports by first switching to bank 1. After we do that we send values to the TRISA, TRISB, and TRISC registers which control ports a,b, and c. A 1 makes it an input and a 0 makes it an output. We send vales buy moving a literal value to multipurpose register w and then moving the contents of w to the appropriate register.

Part 3:

We use a simple goto statement to go to the main LOOP

Part 4:

We use the function BTFSS (Check if bit is SET) and BTFSC (Check if bit is CLEAR). We provide it a register location as well as a bit. btfsc PORTA,0 means check PORTA bit 0 if it is clear. If it is, jump over the next line. If not, continue as normal.

Increment routine:

If port a bit 0 is set, the program goes into the increment routine. This routine increments count by 1 and checks to make sure it didn't go past 2. It does this by doing an arithmetic operation with w, in this case, subtraction. If a zero is returned the Z flag of the status register is set. We can use this to advance further into our program. If it is not set (thus it is under 2) we return back to the main loop with count only incremented. If it returns a zero, we clear count, and then return back to the loop.

Decrement routine:

Same as the increment routine except we add zero and decrement count.

Part 5:

We call the check level routine. In this routine we do several arithmetic operations to count to see what value it has in it. Its value send it to the proper routine to adjust the duty cycle.

Part 6:

High: Set the fan constantly on, call no delay (100% duty cycle)

Medium: Make sure fan is off, call a delay, turn fan on, call another delay, turn it off. (50% duty cycle)

Low: turn off fan, call 3 delays, turn fan on, call one delay, turn fan off. (approx 25% duty cycle)

DELAY Routine:

The Delay routine decrements the variable DELAY1 by 1 until it reaches 0, once it does it resets DELAY1 to 100 and exits the loop, this eats up 100 program cycles or roughly 100(micro)s

Part 7:

RETURN brings us back from the subroutines back to the main loop

Part 8:

We move COUNT to w, call the TABLE sub routine and add W to the program counter, this makes the program counter advance over the other values not desired and return a value to w back to the main loop. We send this value to PORTC which our 7 segment display is located.

Part 9:

We use a goto function to begin again at the front of the loop

*QUICK NOTE*

GOTO VS CALL

Goto: Simply GOES TO the part of the code, does not return a value

Call: Goes to a section of code and will return to where it was called from once a value was returned with it.

http://mcuplace.com/mcu/media/blogs/blog/pwm2.asm (SOURCE)
http://mcuplace.com/mcu/media/blogs/blog/pwm2.HEX (HEX)

The Microcontroller

08/24/08 | by anthony [mail] | Categories: Informative

Now that we've covered the basics we can finally get into the main purpose of this blog. From now on we will refer to a microcontroller with the acronym "MCU."

Section 1: The MCU

-So yea, what are they?

A MCU is a small computer on a chip. Most MCUs have RAM ROM and a CPU to process data stored in ROM. When a MCU is turned on, it instantly starts running the code stored in its data banks and executing commands. Most MCUs only have about a small amount of storage (usually a few KB ) but it more than enough to run complex algorithms and even stuff for advanced robotics. Microcontrollers are essential to all electronics they provide the ability to make a device “smart” without using complex analog integrated circuits or expensive computer systems. They are extremely fun for hobbyists as they can replace tons of expensive components with a moderately priced MCU.

-What can I do with them?

You can do almost anything. From dancing LEDS to PWM fan control to driving LCD screen and robotics. If you can code it, a microcontroller will do it. The fundamentals of a MCU are taking inputs and conditioning outputs through the use of code. Depending on the complexity of your code depends how complex the function of your chip can be. With a little creative thinking you can make even the low end chips do some extra ordinary things.

- What so special, I can do all of that with analog circuits!

Well, analog circuits aren’t as modular and expandable as MCUs. As soon as you compile your code your chip has taken on new functionality. Debugging and expanding functionality is extremely easy and efficient. A analog circuit that would take several integrated circuits as well as a dozen passive components can easily be replaced by one chip which does it all. MCUs can even use analog circuits to expand the function of circuits.

-What types of functions do these chips take on a day to day basis?

They're everywhere! Any interactive device uses MCUs. Your microwave, your television, your mouse, your cell phone, and pretty much everything use them.

-I mean with all this functionality, these things must cost a fortune!

Not at all, although high end chips can cost upwards of 20$, most mid range lines go for about 3-4$ each

Section 2: The world of MCUs


-This stuff sounds cool, but where do I start?

Getting into microcontrollers is much easier than it may seem. It’s always good to have a background in passive and analog components but its not necessary (will make things harder if you don't). There are many different types of microcontrollers. Some use proprietary languages some run on common languages like C/C++/Basic. Some require expensive software, some come with free software. For the purpose of this article I am going to be explaining how to work with the PIC series of microcontrollers manufactured by Microchip.

-So why the PIC?

They are low cost microcontrollers which are extremely easy to program for and develop with. They offer the latest support for their devices as well as free development software. PIC microcontrollers are widely used by hobbyists because of their ease of use and their cost effectiveness.

-What do I need to start?

You need a programmer,an actual MCU, and software to develop with. I highly recommend the PICKit2 offered by Microchip. They go for about 50USD and they include a USB programmer, tons of guides, the microchip IDE, and a midrange 20 pin PIC16F690.

http://www.microchip.com/stellent/id...cName=en023805

If you plan on using microchip MCUs you need their IDE (developers suite) offered free on their website (as well as included with PICKit2)

-There are literally thousands of MCUs to choose from! Which one do I use?

I personally like the 20 pin PIC16F690, I use in all my projects and I highly recommend it. It’s an 8-bit microcontroller with a 20MHZ internal clock it has 7KB of internal storage, but it’s more than enough for some basic robotics and any other projects.

You can buy them at http://www.mouser.com/Search/ProductDetail.aspx?qs=fM4xO01eazPcr2WIDQJ1Dg%3d%3d

Section 3: The mindset of a developer.

Rather than continue with my quirky Q&A style I am going to discuss some ideologies and strategies associated with working with MCUs before I get into programming and your first program.
You should have a good idea of how to work with binary numbers as well as hexadecimal. You will need to know them. I recommend you read the blog post before this one to get an idea of working with binary and hex if you haven't.

Every MCU has its own data sheet. They’re about 300 pages long and they contain every nook and cranny of the hardware. They are ESSENTIAL to develop for any MCU. When you get a device, you must understand how to reference data from a data sheet. The data sheet for the PIC16F690 is located below:

http://ww1.microchip.com/downloads/en/DeviceDoc/41262E.pdf

For the most part, you are programming WITH the hardware in mind. You are going to sending data to memory locations to enable functions and check statuses of certain memory locations. This is different than writing a program for windows or programming in C. The main parts of a microcontroller are its registers, registers are spots in the memory that have a function associated with them, and they start at 0x00 and end at 0x1fff. Most of it is empty memory dedicated for storage of your program, however in the beginnings there are dedicated locations for the functions of the MCU. These are where you set up ports and manipulate I/O data. The way Microchip sets up there memory is in two banks. Bank 1 is where you set up information on the ports and bank 0 is where you manipulate data. For the most part, the running part of your program is going to be in bank 0 and you only switch to bank 1 to set up ports.

The basic flow of a program is setting up environmental variables, then setting up ports, then going to a main routine that calls subroutines to analyze data and condition outputs. Programs for MCU tend to be very linear compared to code written for software. One thing to keep in mind is that your code operates very very fast. A PIC operates around 4MHZ and takes 4 clocks to do one instruction, thus an average PIC will operate at about 1 million instructions per second and an average instruction taking only 1 microsecond to complete. This both works with as well as against you. Flashing an LED isn't as simple as doing a loop that turns on and off a LED you have to add a delay routine in between so that the LED being on and off is visible to the naked eye. Considerations like these are learned as you work with your hardware and begin to notice what works and what doesn't work.

The Software

We will mostly be working with Microchip's MPLAB IDE. This software suit includes pretty much everything you need to use to develop for your PIC. It includes many different assemblers, compilers, simulators and programmers to make sure that your code will work flawlessly. Once you setup a new project and set up your hardware you will begin writing your code.

Section 4: The Hardware

Remember how i said how important the data sheet is? We're going to open up the data sheet of the PIC16f690 and explore the insides and learn how to work with this hardware. This data sheet includes data for several MCUs all are fairly similar except they come in different packages. We are going to be looking at the data for the PIC16F690 20pin DIP MCU.

One of the first things we see are the pin outs for our MCU. The first pin is the VDD which is the supply voltage, we always provide a 5v regulated source to our micrcontrollrs for safe operation, however it can accept a wide range of voltages (Try not to go above 9 V). Pin 20 is the ground. These two pins are the only two power pins essential to operation. There are several other pins you should also take into consideration when building circuits outside of the developer. Pin 4 is the MCLR which is a reset pin and also the pin that is used to trigger programming. You usually provide a logic high to this pin if you turn it on in the config word (The configuration file for the MCU set when programming). We also have a Clock in and Clock out on pins 2 and 3 respectively. All microcontrollers need a clock source to increment the code and keep things running. Most microcontrollers have an internal oscillator at 20 MHZ that is more than enough for us. However, you can set the clock manually by providing a clock source to these pins and configuring the config word to not use the internal oscillator.

After that we have our multipurpose input/output(i/o) pins. In the PIC16F690 the i/o pins are separated by ports a b and c. ports a and b arnt full 8 bit i/o ports but port c is. For the most part i use port c for output and a or b for input, in the end its just developers preference.

Different pins will have different functions and can be used for different things. All of that is described in the data sheets. You also want to keep note of what pins are used for external interrupts.

Next on our list is the register block (starts page 29). The next part of the data sheet goes on to explain the general location of all the registers and their hex location. Simple enough.

Our PIC microcontroller is a 8 bit device. Which means most functions can only handle a max of 8 bits. The table after the register block expands the basic registers and explains what each bit does (page 34).

Lets look at the status register. The status register controls the status of the micrcontroller. certain flags are set when certain things happen in the micrcontroller. The status register is also the go to register when you have to change banks. It is located at 03h (same as 0x03) and has 8 bits to it. This table does a basic layout of what functions are located at each bit, but if we want a more in depth explanation we can go look it up further into the data sheet.

The Status Register.

Page 38 explains the status register's bits more in depth. The mains bits were going to be using are 0, 2, and 5.

Bit 0: Bit 0 is the carry bit. It is set when a bit overflows (goes over 255 or below 0)

Bit 2: Bit 2 is the zero bit, it is set when the result of a arithmetic operation is 0 or negative.

Bit 5: Bit 5 is the RP0 bit. We set or clear this bit to change which bank we are in. The design of the PIC microcontroller is that there are two banks, bank 0 and bank 1. As explained earlier, bank 1 is where you set up ports and bank 0 is where you manipulate data.

The data sheet offers explanations for all the registers and everything so if you ever get stumped, go to the data sheet.

Section 5: Your First program

Although you can use C to develop for the PIC1690, I prefer assembly language. It’s much easier to work in assembly than it is with C as assembly is more tied to the hardware than C is. The following code was included in Microchip’s PICKIT2 it is not mine and I am merely including it for Demo purposes.

#include p16f690 .inc
__config (_INTRC_OSC_NOCLKOUT & _WDT_OFF & _PWRTE_OFF & _MCLRE_OFF & _CP_OFF & _BOR_OFF & _IESO_OFF & _FCMEN_OFF)
org 0
Start:
bsf STATUS,RP0 ; select Register Page 1
bcf TRISC,0 ; make IO Pin C0 an output
bcf STATUS,RP0 ; back to Register Page 0
bsf PORTC,0 ; turn on LED C0 (DS1)
goto $ ; wait here
end

The Registers used: STAUS, TRISC and PORTC

STATUS holds information on general MCU info, it has 8 bits to it however, were interested in the RP0 bit which controls what bank we are in.

TRISC is the tri-state register for portc, this also has 8 bits, by setting it high, we make that port an input. By setting it to 0, we make it an output.

PORTC this handles the data on the ports. We can check if inputs are high or low and we can set outputs high or low.

#include p16f690.inc The first line includes a file that has preset names for common register location (Such as STATUS, PORTA/B/C and TRISA/B/C

__config (_INTRC_OSC_NOCLKOUT & _WDT_OFF & _PWRTE_OFF & _MCLRE_OFF & _CP_OFF & _BOR_OFF & _IESO_OFF & _FCMEN_OFF)

This line set the config word for the MCU, this includes information about clock weather to use internal timers or not. For most intensive purposes, this general config can be used which uses the internal oscillator and turns off the MCLR

org 0 Tells the compiler this is the start of the program.

Start:
A label, we uses these to label parts in a program.

bsf STATUS,RP0 BSF, means BIT SET HIGH, the next lines tell it to goto the STATUS register and bit RP0, RP0 sets what bank the program is in, by setting it to 1(high) we are in bank 1 and thus can manipulate port information

bcf TRISC,0 BCF, means BIT CLEAR, The next lines tell it to goto the TRISC register (controlling portc I/O) and set the first bit, bit 0, to low, thus making it an output (1 is input, 0 is output)

bcf STATUS,RP0 This clears RP0 in STATUS, bringing us back to bank 0. Now we can manipulate data.

bsf PORTC,0 Sets the first bit of PORTC to high, enabling the LED

goto $ Stops the program

end Tells the compiler the code is finished.

What you can do with this you should build your code. By building your code you call MPLAB's assembler which takes your code and turns it into a HEX file that the PIC can read natively. After you do that it is highly recommended you run MPLAB's simulator and begin testing your code. You can watch the special registers and see how your code manipulates the registers as well as the I/O.

From here we can begin loading our code onto the actual MCU and set it up in a circuit. The PICKIT already contains a development area and several components to test the function of your code. However, for more complex programs you will be taking your PIC off the programmer and onto a breadboard to build even more sophisticated projects.

If you’ve survived so far, give yourself a pat on the back, for you have entered the world of MCUs. The possibilities are endless and with a little ingenuity the world is yours.

1001001 SOS

08/23/08 | by anthony [mail] | Categories: Informative

Binary, the language of machine, but why? In circuitry we have two things we can represent data as. We can use a "on" and a "off" meaning, weather there is current flowing or there is not. Traditionally 1 represents an on, or a high and 0 represents an off or a low. Because of this we work in binary, because there are only two numbers in that system 0 and 1.

Number systems

We work with the decimal system which has values 0-9. This was primarily done more than likely because we have 10 digits which we've used over the centuries to count :D (now if we only counted fingers and not digits we'd be perfectly happy with octal). Each digit in a number represents the base to a power starting at 0 and ending at infinity. To put this to perspective lets look at the number 142. When we break 142 apart we get:
1 4 2
1x10^2 + 4X10^1 + 2X10^0
100+40+2
142

This works for all number systems from binary to hexadecimal and beyond.

Binary

Lets look at a binary number, 1001001 and break it apart.

1 0 0 1 0 0 1
1*2^6 + 0*2^5 + 0*2^4 + 1*2^3 + 0*2^2 + 0*2^1 + 1*2^0
64+0+0+8+0+0+1
73

1001001 is a binary representation of the decimal number 73. Binary doesn't look so daunting anymore does it?

Bits and Bytes

If you've ever been around computers or anything digital you've heard the terms 8-bit 32-bit 64-bit 100 Gigabyte etc. One bit represents one digit of a binary number, either a 1 or a 0. A byte represents 8-bits or two hexadecimal digits(well get on hexadecimal later). Bits and bytes are the main ways computers handle data. Bits being fundamental and bytes being a way to organize bits in a way that they're useful. You cant hold that much information with a bit, however with a byte you can hold up to 256 values (2^8)

Hexadecimal

Even though bits are fundamental we are going to be working with hexadecimal. As you can see, to represent large numbers in binary can get rather confusing. We use hexadecimal to bring things down to size and make code and large registers more manageable. Hexadecimal is a number system based on base 16. If you noticed, 16 is a power of two thus every 4 digits in binary represent 1 hexadecimal digit. We note that a number is hexadecimal with the prefix "0x" or the suffix "h." One thing you might be wondering is how do you represent numbers greater than 9 without using two digits? Simple, we use letters. In hexadecimal we use the number 0-9 and the letters A-F (10-15). So the hexadecimal number 0xB is 11 in decimal and 1011 in binary.

Expanding Hexadecimal

So lets do a quick exercise to see how hexadecimal truly works. Lets start with 0x5FB

To convert this to binary we break it down digit by digit starting with the first.

0xB in binary is 1011. The second digit 0xF is 1111 in binary and 0x5 is 0101 in binary.

We put this all together and get 01011111011. Because hexadecimal is based on a number that is a power of 2, we can work with numbers like this.

Expanding it to decimal isn't all that hard either, however a calculator would help for those tricky powers of 16.

0x5FB
5*16^2 + 15*16^1 + 11*16^0
1280 + 240 + 11 = 1531

In reality, with a little work and patience working with other number systems will come natural and become easier the more you work with them. With the fundamentals of electronics, semiconductors and these number systems we can finally start looking at the microcontroller.

Truth tables NEVER lie

08/21/08 | by anthony [mail] | Categories: Informative

So we have diodes, resistors, transistors, capacitors, inducers, and whatnot. So how does this all come together to make computers?

At its heart, a transistor takes an input and provides an output. Alone its a fairly simple logic operation and transistors alone are usually used solely for switching current. However, when you combine them in fascinating ways you can create logic gates. Logic gates take inputs and provide outputs based on certain criteria. The simplest gates are NOT, AND, OR.

If you remember from high school mathematics, logic isn't that complicated. For these gates you have two inputs that are compared and an output that is determined by the input. The inputs will be A and B, the output Q and 1 represents high and 0 represents low.

NOT
Not is one of the most simplest gates, it takes the input and reverses it.
A->Q
1 0
0 1

AND
And merely outputs high when both A AND B are high, otherwise it outputs low.
A+B->Q
0 0 0
1 0 0
0 1 0
1 1 1

OR
Or outputs high when either input is high.
A+B->Q
0 0 0
1 0 1
0 1 1
1 1 1

Simple enough. We also have logic operations that are combination of the above. Combining OR and AND with NOT gives us NOR and NAND. This merely reverses the output as follows

NOR
A+B->Q
0 0 1
1 0 0
0 1 0
1 1 0

NAND
A+B->Q
0 0 1
1 0 1
0 1 1
1 1 0

Now ever more complicated we have logic gates that are slightly more complex. These are the Exclusive OR(XOR) and the Exclusive NOR(XNOR) gates.

XOR
The idea behind the XOR gate is that the inputs can be either or, but not BOTH. Hence it is exclusive to the OR function.
A+B->Q
0 0 0
1 0 1
0 1 1
1 1 0

XNOR
Reverse it.
A+B->Q
0 0 1
1 0 0
0 1 0
1 1 1

There we go, the simplest logic gates. With these logic gates we can make things like adders, flip flops and memory. We'll save the explanation of those for another day since it can get quite tedious.

Since the first post of this blog we've done a crash course in electronics, semiconductors and logic. Now that we understand the basics behind circuitry and electronics we can go ahead and start playing with our microcontrollers and begin learning how to make them do our bidding. Stay tuned as i go into the Binary and Hexadecimal number system and as we begin looking at assembly.

Semiconduct THIS

08/20/08 | by anthony [mail] | Categories: Informative

Even with the fundamentals laid down, electronics had little place to move in terms of computing. Vacuum tubes were very bulky and ate a lot of electricity to do simple tasks. Early computers took up whole rooms and had the computing power of most modern microcontrollers but, they did their job. It wasn't until the advancement of semi-conductors that we truly saw the miniaturization of electronics. With the semiconductor came the transistor and with the transistor and the advent of advanced photo etching processes we eventually got the integrated circuit and the microprocessor. This paved the way for modern electronics that now work on a scale of about 45 nanometers (a lone Si atom is .1 nanometers wide)

So what is so special about semiconductors? Silicon is the most famous semiconductor. Silicon in its natural state makes a nice lattice because it has 4 valance electrons and wants 8, so it bond with 4 other Si and makes a lattice. A lattice is very strong atomic structure and does not conduct electricity, thus making pure Silicon a insulator. However you can add impurities to silicon to change the way it conducts electricity. This is called doping. If you dope silicon with something like gallium(Ga)which has 3 valance electrons, you end up having a spare electron on the silicon that has no where to go. This lone electron is free to flow and thus, current flows. This type of silicon is called N-type and is a decent conductor. You can also dope silicon with something such as arsenic, which has 5 valance electrons. This creates a positive "hole" where a absence of electrons exists. Flowing electrons can take up this space and move the hole, this allows current to flow. This is called P-type and is also a decent conductor.

This is why silicon is a "Semiconductor" it will not conduct electricity in one state but will in another. Its not the states alone that are fascinating, but its what happens when you put them together.

The Diode

The diode is another fundamental component. Its basic function is to allow current in only one direction. This is crucial as it protects components and makes sure current only goes one way. It accomplishes this by creating a junction of P-type and N-Type silicon like so:
------------[(P-Type)|(N-Type)]------------

When you hook up a battery backwards like this:
(-)------------[(P-Type)|(N-Type)]------------(+)

The holes in the P-type are attracted to the negative terminal and the electrons are attracted to the positive terminal. No current is allowed to flow.

When you hook up a batter the correct way:
(+)------------[(P-Type)|(N-Type)]------------(-)

The electrons are repealed by the negative terminal as the holes are to the positive terminal. At the junction the electrons meet with holes and begin filling them. Current flows across the junction.

The diode only allows current to flow when it is properly placed in a circuit. However it isn't nearly as significant as the next component.

The Transitor

Without the transistor, none of this would be possible. The transistor is the modern computer. A transistor is merely a diode, but going one step further. A transistor features 3 layers of doped silicon usually arranged as PNP or NPN (hence NPN And PNP transistors) by adding this third layer, you can create a switching effect. In a PNP transistor by supplying current to the middle layer you allow current to flow throughout the device. This fundamentally allows a small current to switch a large one.

By having this ability you can begin to build Boolean gates out of arrangements of transistors. If you have logic you can make computers.

This is the story of the semiconductor! After it was born it was a mad dash to implement complicated logic gates as well as the race to make the transistor smaller and smaller. This race lead us to our faithful component, the Microcontroller.

Pages: << 1 2 3 4 5 >>

September 2010
Sun Mon Tue Wed Thu Fri Sat
 << <   > >>
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    

Ads by Google

This blog is dedicated to working with digital circuitry and the use of microcontrollers, small compact computers on a chip. I will be encompassing many techniques to develop projects, tools to use to write and assemble code and i will be sharing any projects i am currently working on. User feedback is a must! I do not know it all, hell im not even that experienced, but without a general place to get all the info needed i find it very hard to get into the world of microcontrollers without pursing a CE degree. So come one come all and enter the world of mystery and creativity!

Search

XML Feeds

multiblog engine