Thursday, December 6, 2007

PIC programming?....you got it! (tutorial)

Microcontrollers
and PIC
Programming
(tutorial)

Microcontrollers:

The microcontroller is an entire computer on a single chip. The
advantage of designing around a microcontroller is that a large
amount of electronics needed for certain applications can be eliminated.
This makes it the ideal device for use with mobile robots
and other applications where computing power is needed. The
microcontroller is popular because the chip can be reprogrammed
easily to perform different functions, and is very inexpensive. The
microcontroller contains all the basic components that make up a
computer. It contains a central processing unit (CPU), read-only
memory, random-access memory (RAM), arithmetic logic unit,
input and output lines, timers, serial and parallel ports, digital-toanalog
converters, and analog-to-digital converters. The scope of
this book is to discuss the specifics of how the microcontroller can
be used as the processor for the various robots that will be built.

PIC 16F84 MCU

Microchip technology has developed a line of reduced instruction
set computer (RISC) microprocessors called the programmable
interface controller (PIC). The PIC uses what is known as “Harvard
architecture.” Harvard uses two memories and separate busses.
The first memory is used to store the program, and the other is to
store data. The advantage of this design is that instructions can be
fetched by the CPU at the same time that RAM is being accessed.
This greatly speeds up execution time. The architecture commonly
used for most computers today is known as Von Neumann
architecture. This design uses the same memory for control and
RAM storage, and slows down processing time.
We will be using the PIC 16F84, shown in Figure 3.1, as the
processor for the robots in the book. This device can be reprogrammed
over and over because it uses flash read-only memory
for program storage. This makes it ideal for experimenting because
the chip does not need to be erased with an ultraviolet light source
every time you need to tweak the code or try something new.
The PIC 16F84 is an 18-pin device with an 8-bit data bus and registers.
We will be using a 4-MHz crystal for the clock speed. This
is very fast for our application when you consider that it is running
machine code at 4 million cycles per second. The PIC 16F84
is equipped with two input/output (I/O) ports, port A and port B.
Each port has two registers associated with it. The first register is
the TRIS (Tri State) register. The value loaded into this register
determines if the individual pins of the port are treated as inputs
or outputs. The other register is the address of the port itself. Once
the ports have been configured using the TRIS register, data can
then be written or read to the port using the port register address.
Port B has eight I/O lines available and Port A has five I/O lines.



PicBasic Pro Compiler

MicroEngineering Labs developed the PicBasic Pro Compiler, shown
in Figure 3.3. It is a programming language that makes it quick and
easy to program Microchip Technology’s powerful PICmicro micro-
controllers. It can be purchased from microEngineering Labs,
whose Web site is located at www.microengineeringlabs.com.
The BASIC language is much easier to read and write than
Microchip assembly language, and will be used to program the
robots in this book. The PicBasic Pro Compiler is “BASIC Stamp IIlike,”
and has most of the libraries and functions of both the BASIC
Stamp I and II. Because it is a true compiler, programs execute
much faster, and may be longer than their Stamp equivalents.
One of the advantages of the PicBasic Pro Compiler is that it uses
a real IF..THEN..ELSE..ENDIF, instead of the IF..THEN(GOTO) of
the Stamps. These and other differences are spelled out in the PBP
manual.
PicBasic Pro (PBP) defaults to create files that run on a PIC 16F84-
04/P clocked at 4 MHz. Only a minimum of other parts are necessary:
two 22pf capacitors for the 4-MHz crystal, a 4.7K pull-upresistor tied to the /MCLR pin, and a suitable 5-volt power supply.
Many PICmicros other than the 16F84, as well as oscillators of frequencies
other than 4 MHz, may be used with the PicBasic Pro
Compiler.
The PicBasic Pro Compiler produces code that may be programmed
into a wide variety of PICmicro microcontrollers having
from 8 to 84 pins and various on-chip features, including A/D converters,
hardware timers, and serial ports. For general purpose
PICmicro development using the PicBasic Pro Compiler, the PIC
16F84, 16F876, and 16F877 are the current PICmicros of choice.
These microcontrollers use flash technology to allow rapid erasing
and reprogramming to speed program debugging. With the click of
the mouse in the programming software, the flash PICmicro can be
instantly erased and then reprogrammed again and again. Other
PICmicros in the 12C67x, 14C000, 16C55x, 16C6xx, 16C7xx,
16C9xx, 17Cxxx, and 18Cxxx series are either one-time programmable
(OTP) or have a quartz window in the top (JW) to allow erasure
by exposure to ultraviolet light for several minutes. The PIC
16F84 and 16F87x devices also contain between 64 and 256 bytes
of nonvolatile data memory that can be used to store program data
and other parameters, even when the power is turned off. This
data area can be accessed simply by using the PicBasic Pro
Compiler’s READ and WRITE commands. (Program code is always
permanently stored in the PICmicro’s code space, whether the
power is on or off.)
By using a flash PICmicro for initial program testing, the debugging
process may be sped along. Once the main routines of a program
are operating satisfactorily, a PICmicro with more capabilities
or expanded features of the compiler may be utilized.
Software Installation
The PicBasic Pro files are compressed into a self-extracting file on
the diskette. They must be uncompressed to your hard drive before
use. To uncompress the files, create a subdirectory on your hard
drive called PBP or another name of your choosing by typing:
md PBP
at the DOS prompt. Change to the directory:
cd PBP
Assuming the distribution diskette is in drive a:, uncompress the
files into the PBP subdirectory:
a:\pbpxxx -d
where xxx is the version number of the compiler on the disk. Don’t
forget the -d option on the end of the command. This ensures that
the proper subdirectories within PBP are created.
Make sure that FILES and BUFFERS are set to at least 50 in your
CONFIG.SYS file. Depending on how many FILES and BUFFERS are
already in use by your system, allocating an even larger number
may be necessary.
See the README.TXT file on the diskette for more information on
uncompressing the files. Also, read the READ.ME file that is
uncompressed to the PBP subdirectory on your hard drive for the
latest PicBasic Pro Compiler information. Table 3.2 lists the different
PicBasic Pro Compiler statements that are available to the
PICmicro software developer.
Statement Description
@ Insert one line of assembly language code.



  1. ADCIN Read on-chip analog to digital converter.
  2. ASM..ENDASM Insert assembly language code section.
  3. BRANCH Computed GOTO (equiv. to ON..GOTO).
  4. BRANCHL BRANCH Out of page (long BRANCH).
  5. BUTTON Debounce and auto-repeat input on specified pin.
  6. CALL Call assembly language subroutine.
  7. CLEAR Zero all variables.
  8. CLEARWDT Clear (tickle) Watchdog Timer.
  9. COUNT Count number of pulses on a pin.
  10. DATA Define initial contents of on-chip EEPROM.
  11. DEBUG Asynchronous serial output to fixed pin and baud.
  12. DEBUGIN Asynchronous serial input from fixed pin and baud.
  13. DISABLE Disable ON DEBUG and ON INTERRUPT processing.
  14. DISABLE DEBUG Disable ON DEBUG processing.
  15. DISABLE INTERRUPT Disable ON INTERRUPT processing.
  16. DTMFOUT Produce touch-tones on a pin.
  17. EEPROM Define initial contents of on-chip EEPROM.
  18. ENABLE Enable ON DEBUG and ON INTERRUPT processing.
  19. ENABLE DEBUG Enable ON DEBUG processing.
  20. ENABLE INTERRUPT Enable ON INTERRUPT processing.
  21. END FOR..NEXT Stop execution and enter low power mode.
  22. FOR..NEXT Repeatedly execute statements.
  23. FREQOUT Produce up to 2 frequencies on a pin.
  24. GOSUB Call BASIC subroutine at specified label.
  25. GOTO Continue execution at specified label.
  26. HIGH Make pin output high.
  27. HSERIN Hardware asynchronous serial input.
  28. HSEROUT Hardware asynchronous serial output.
  29. I2CREAD Read bytes from I2C device.
  30. I2CWRITEW rite bytes to I2C device.
  31. IF..THEN..ELSE..ENDIF Conditionally execute statements.
  32. INPUT Make pin an input.
  33. LCDIN Read from LCD RAM.
  34. LCDOUT Display characters on LCD.
  35. {LET} Assign result of an expression to a variable.
  36. LOOKDOWN Search constant table for value.
  37. LOOKDOWN2 Search constant/variable table for value.
  38. LOOKUP Fetch constant value from table.
  39. LOOKUP2 Fetch constant/variable value from table.
  40. LOW Make pin output low.
  41. NAP Power down processor for short period of time.
  42. ON DEBUG Execute BASIC debug monitor.
  43. ON INTERRUPT Execute BASIC subroutine on an interrupt.
  44. OUTPUT Make pin an output.
  45. PAUSEDelay (1mSec resolution).
  46. PAUSEUS Delay (1uSec resolution).
  47. PEEK Read byte from register. (Do not use.)
  48. POKEW rite byte to register. (Do not use.)
  49. POT Read potentiometer on specified pin.
  50. PULSIN Measure pulse width on a pin.
  51. PULSOUT Generate pulse to a pin.
  52. PWM Output pulse width modulated pulse train to pin.
  53. RANDOM Generate pseudo-random number.
  54. RCTIMEMeasur e pulse width on a pin.
  55. READ Read byte from on-chip EEPROM.
  56. READCODE Read word from code memory
  57. RESUME Continue execution after interrupt handling.
  58. RETURN Continue at statement following last GOSUB.
  59. REVERSE Make output pin an input or an input pin an output.
  60. SERIN Asynchronous serial input (BS1 style).
  61. SERIN2 Asynchronous serial input (BS2 style).
  62. SEROUT Asynchronous serial output (BS1 style).
  63. SEROUT2 Asynchronous serial output (BS2 style).
  64. SHIFTIN Synchronous serial input.
  65. SHIFTOUT Synchronous serial output.
  66. SLEEP Power down processor for a period of time.
  67. SOUND Generate tone or white-noise on specified pin.
  68. SWAP Exchange the values of two variables.
  69. TOGGLEMake pin output and toggle state.
  70. WHILE..WEND Execute statements while condition is true.
  71. WRITE Write byte to on-chip EEPROM.
  72. WRITECODE Write word to code memory.
  73. XIN X-10 input.
  74. XOUT X-10 output.

Compiling A Program

For operation of the PicBasic Pro Compiler, you will need a text
editor or word processor for creation of your program source file,
some sort of PICmicro programmer such as the EPIC Plus Pocket
PICmicro Programmer, and the PicBasic Pro Compiler itself. Of
course you also need a PC to run it.
Follow this sequence of events:
First, create the BASIC source file for the program, using your favorite
text editor or word processor. If you don’t have a favorite, DOS EDIT
(included with MS-DOS) or Windows NOTEPAD (included with
Windows and Windows 95/98) may be substituted. A great text editor
called Ultraedit is available at: www.ultraedit.com. It is geared
towards the software developer and does not add any undesirable
formatting characters that will cause the compiler to error out.
The source file name should (but is not required to) end with the
extension .BAS. The text file that is created must be pure ASCII
text. It must not contain any special codes that might be inserted
by word processors for their own purposes. You are usually given
the option of saving the file as pure DOS or ASCII text by most
word processors.

Once you are satisfied that the program you have written will work
flawlessly, you can execute the PicBasic Pro Compiler by entering
PBP, followed by the name of your text file at a DOS prompt. For
example, if the text file you created is named frog-test.bas, at the
DOS command prompt, enter:
PBP example.bas
The compiler will display an initialization (copyright) message and
process your file. If it likes your file, it will create an assembler
source code file (in this case, named example.asm) and automatically
invoke its assembler to complete the task. If all goes well, the
final PICmicro code file will be created (in this case, example.hex).
If you have made the compiler unhappy, it will issue a string of
errors that will need to be corrected in your BASIC source file
before you try compilation again.
To help ensure that your original file is flawless, it is best to start
by writing and testing a short piece of your program, rather than
writing an entire 100,000-line monolith all at once and then trying
to debug it from end to end.
If you don’t tell it otherwise, the PicBasic Pro Compiler defaults to
creating code for the PIC 16F84. To compile code for PICmicros.other than the F84, just use the -P command line option, described
later in the manual, to specify a different target processor. For
example, if you intend to run the above program, example.bas, on
a PIC 16C74, compile it using the command:
PBP -p16c74 example.bas

An assembler source code file for example.bas is also generated.
It is called example.asm. The assembler source code can be used
as a guide if you want to explore assembly language programming
because the listing shows the PicBasic Pro statement and
the corresponding assembly code on the next line. The rest of the
chapters discussing software will not be addressing assembly
code. All we really need to be concerned with is the PicBasic
source code and the generated .HEX machine code.

IMPORTANT:
If you do not have the resources to buy the PicBasic Pro compiler,
simply type the listings of the .HEX files that i provide, into a text editor and save
the file with the program name and .HEX extension.

example of a hex file content:
:100000007B28A0003B200C080D04031976287020E3
:1000100084132008800664000D280E288C0A03191A
:100020008D0F0B28800676288F0022088400200977
:100030003C2084138F0803197628F03091000E08B5
:1000400080389000F03091030319910003198F0359
:10005000031976282B283F2003010C1820088E1F37
:1000600020088E0803190301900F382880061F28E6s
:10007000392800002228FF3A8417800576280D08C9


Using the EPIC Programmer
to Program the PIC

The two steps left are putting your compiled program into the
PICmicro microcontroller and testing it. The PicBasic Pro Compiler
generates standard 8-bit Merged Intel HEX (.HEX) files that may
be used with any PICmicro Programmer, including the EPIC Plus
Pocket PICmicro Programmer, shown in Figure 3.4. PICmicros
cannot be programmed with BASIC Stamp programming cables.
An example of how a PICmicro is programmed using the EPIC
Programmer with the DOS programming software follows. If
Windows 95/98/NT is available, using the Windows version of
EPIC Programmer software is recommended.
Make sure there are no PICmicros installed in the EPIC
Programmer programming socket or any attached adapters. Hook
the EPIC Programmer to the PC parallel printer port using a DB25
male-to-DB25 female printer extension cable. Plug the AC adapter
into the wall and then into the EPIC Programmer (or attach two
fresh 9-volt batteries to the programmer and connect the “Batt
ON” jumper). The light-emitting diode (LED) on the EPIC
Programmer may be on or off at this point. Do not insert a
PICmicro into the programming socket when the LED is on or
before the programming software has been started.
Enter:
EPIC
at the DOS command prompt to start the programming software.
The EPIC software should be run from a pure DOS session or from
a full-screen DOS session under Windows or OS/2. (Running
under Windows is discouraged. Windows [all varieties] alters the
system timing and plays with the port when you are not looking,
which may cause programming errors.)
The EPIC software will look around to find where the EPIC
Programmer is attached and get it ready to program a PICmicro. If
the EPIC Programmer is not found, check all the above connections
and verify that there is not a PICmicro or any adapter connected
to the programmer.
Typing:
EPIC /?
at the DOS command prompt will display a list of available options
for the EPIC software.
Once the programming screen is displayed, use the mouse to click
on Open file or press Alt-O on your keyboard. Use the mouse (or
keyboard) to select frog-test.hex or any other file you would like to
program into the PICmicro from the dialog box. The file will load
and you should see a list of numbers in the window at the left.
This is your program in PICmicro code. At the right of the screen
is a display of the configuration information that will be programmed
into the PICmicro. Verify that it is correct before proceeding.
In general, the oscillator should be set to XT for a 4-MHz
crystal, and the Watchdog Timer should be set to ON for PicBasic
Pro programs. Most important, Code Protect must be OFF when
programming any windowed (JW) PICmicro. You may not be able
to erase a windowed PICmicro that has been code protected.
Figure 3.5 shows the EPIC MS-DOS interface.
Insert a PIC 16F84 into the programming socket and click on
Program or press Alt-P on the keyboard. The PICmicro will first be
checked to make sure it is blank, and then your code will be programmed
into it. If the PICmicro is not blank and it is a flash
device, you can simply choose to program over it without erasing
first. Once the programming is complete and the LED is off, it is
time to test your program.

Testing the Controller Board
Later in Chapter 4, when the controller board is finished and the
PIC 16F84 is programmed with the frog-test.hex program, insert
the PIC into the socket on the controller board. Place the PIC into
the 18-pin I.C. socket, with the notch and pin 1 facing toward the
LEDs as shown in Figure 3.6.
Place four AA batteries in the 6-volt battery pack and secure it in
position in the holder at the back of the robot. Make sure that the
battery clip is attached, and then turn the power switch to the on
position. If all is well, then the left and right LEDs should be alternatively
flashing on and off, while the piezo element is producing
robotic frog noises. When the flashing is finished, the servos
should start rotating in a forward direction. This ensures that the
16F84 was programmed and that the controller board is functioning
properly.
If nothing is happening when the power is switched on, try going
through the process of programming the PIC again, and choose the
verify option from the EPIC user interface. If the chip fails verifica-tion, check the RS-232 cable and power supply to the programmer.
If that does not work, try using a different 16F84 chip.
If there was no error when programming the PIC, insert it back into
the controller board and make sure that pin 1 is facing toward the
LEDs. Check the battery wiring and verify that the 6-V DC polarity
is not reversed to the power connectors. Check the controller board
for any missed components or cold solder connections.
MicroCode Studio Visual Integrated
Development Environment
Mecanique’s MicroCode Studio is a powerful, visual Integrated
Development Environment (IDE), with an In Circuit Debugging
(ICD) capability designed specifically for microEngineering Labs’
PICBasic Pro Compiler. The MicroCode Studio user interface is
shown in Figure 3.7.
This studio makes programming PIC microcontrollers very easy
with a one-button process of compiling, assembling, and programming.
MicroCode Studio is completely free for noncommercial use
and can be downloaded at www.mecanique.co.uk/code-studio/. It
is not time-limited in any way, and does not have any nag screens.
However, you can only use one ICD model with MicroCode Studio.
MicroCode Studio is not copyright-free. If you wish to redistribute
MicroCode Studio, or make it available on another server, you must
contact Mecanique and obtain permission first.
The main editor provides full syntax highlighting of your code,
with context-sensitive keyword help and syntax hints. The code
explorer allows you to automatically jump to include files,
defines, constants, variables, aliases and modifiers, symbols, and
labels that are contained within your source code. Full cut, copy,
paste, and undo is provided, together with search and replace
features. It also gives you the ability to identify and correct com-pilation and assembler errors. MicroCode Studio lets you view
serial output from your microcontroller. It includes keywordbased
context-sensitive help, and also supports MPASM and
MPLAB.
It is easy to set up your compiler, assembler, and programmer
options, or you can let MicroCode Studio do it for you with its
built-in autosearch feature, as shown in Figure 3.8.
MicroCode Studio has support for MPLAB-dependent programmers
such as PICStart Plus. Compilation and assembler errors can
be easily identified and corrected using the error results window.
Just click on a compilation error and MicroCode Studio will automatically
take you to the error line. MicroCode Studio even comes
with a serial communications window, allowing you to debug and
view serial output from your microcontroller.With MicroCode Studio, you can start your preferred programming
software from within the IDE. This enables you to compile and
then program your microcontroller with just a few mouse clicks (or
keyboard strokes, if you prefer). MicroCode Studio also supports
MPLAB dependant programmers.

Summary
Now that the concept of programming and compiling code for
micro controllers has been covered, it will be easy to program the
robots in the comming posts. Using MicroCode Studio for creating
your source code, compiling the code, and programming PIC
micro controllers makes development much faster.

Assembling your own PIC programmer!

PIC Programmer



Description:
This is bobblick.com's version of the classic PIC 16C84/16F84 programmer. The design is originally by David Tait.

Application:
PICs are small microprocessors containing RAM, ROM, and some peripherals. Almost no other parts are required to make a complete “embedded system”. They are readily available and well supported by the manufacturer, third party developers, and most importantly, users. This has led to their immense popularity.

Assembly:
The PC board design is fairly straightforward and can be made by laser printing to special paper or a page from TIME magazine, then ironing the image onto copper-clad board, then etching with ferric chloride. There are a few jumper wires. The power source needs to be at least 15 volts. A 12 volt DC adapter usually produces about 17 volts, so that's a good choice. Two 9-volt batteries in series will work too. Solder directly to the PC board or use a connector that mates with your power source. Pay attention to the direction of the voltage regulators because the plastic regulators are backward from the tab type. Substitute Japanese or European generic equivalents for the transistors and diodes, but remember that the pinouts will be different. A right angle PC mount DB-25M connector is specified, but a conventional solder-cup DB-25M connector works.

Operation:
The programmer connects to the parallel printer port of your computer and requires external power. If you want to program a PIC you'll have a hex file created by your assembler or created by someone else. You will also need to drive the programmer with some software. Here are programs that run under DOS and Windows. Linux software for Intel-based computers is available elsewhere. Macintoshes do not have parallel ports and can't use this programmer. Do not insert the PIC to be programmed until you have power applied and have run the software, and the programming LED is not lit. The DOS software requires command line switches for fuse settings(unless in the chip's hex file)and also the environmental variable "set ppsetup=3" to be typed before running the program. The Windows software requires the driver "dtait.drv" to be in the \windows\system directory and also the line "PINAPI=DTAIT.DRV" added to the system.ini file. Tell the software you have 7407 chip and PNP transistors. These details are explained in the text files included with the software.


Here's the required parts list: http://www.bobblick.com/techref/projects/picprog/f84pgm.txt

The schematic: http://www.bobblick.com/techref/projects/picprog/f84pgmsc.gif

Download the DOS software: http://www.bobblick.com/techref/projects/picprog/pic84v05.zip

The windows software: http://www.bobblick.com/techref/projects/picprog/picser.zip

Please note: the PC board layout has been updated January 29, 2002 to give more space between pins and traces around the two transistors, and adding R11, required for programming 16F628 and others.

Programming newer PICs:
The whole “F” series can be programmed. You need to use newer software, like this cool software. The PIC16F627 and PIC16F628 are 18 pin devices and fit right in the socket, but you must make a ground connection to pin 10 to prevent LVP programming, a new feature this programmer does not use. Some people suggest using a 10K resistor to ground, if you are doing in-circuit programming that probably makes sense. Programming the bigger PICs, including the PIC16F872 through 16F877 requires fitting the correct(28 or 40 pin) socket and wiring the pins to the corresponding function. Remember to ground the LVP pin on these, too. The bigger PICs also have extra power and ground pins. These must all be used.
You must select the port your computer is using(usually 0378) and the type of programmer (P16PRO) and the type of buffers the programmer uses (non-inverting). The software is beta, but I have tested it and can testify it working on the 16F84 and 16F628 I tried. It only programs locations used in the hex file, so it is very fast. If your program is 250 bytes, only 250 bytes get programmed, but when I used my PicstartPlus to verify the chips I tried, it would show a verify error unless I blanked the chip first, although the chip functioned fine. Leaving those unused areas in the previously programmed state shouldn’t be a problem.
Propic2 keeps the power to the chip on while idle. This can be useful for “burn and crash” in-circuit programming. You’ll see the LED is lit. I don’t like to insert or remove the PIC when power is present, so I pull the power cord before I insert or remove the PIC.
propic2 software, in case the above link is broken.

Warranty:
None.


(OR),
you can order a PIC burner kit(you have to assemble it all,.... pcb will be provided with all the components) for low cost, at kits n spares-
Details: s.no. 64,
PIC Burner:-The Programmer for PIC16X8X Micro-controllers (With Sample Project of Melody Generator): (Sept. 2002):
This kit contains all the necessary items to build a programmer for PIC16X8X series of micro-controllers. PIC16F83, PIC16C84, PIC16F84 and PIC16F84A are some of the many micro-controller ICs from Microchip technology Inc. For demo purpose, one sample project “PIC16F84 Based Melody Generator” is also included here. The programmer and sample project details are explained separately. The programmer software, assembler and general details pertaining to PIC are included in CD. Number of ICs used: 4
Price: 1000INR
http://www.kitsnspares.com/user/default.asp

http://www.kitsnspares.com/user/index.asp?currentpage=1&var=50
(check out s.no. 64)

Wednesday, December 5, 2007

Controlling servos?

PLEASE NOTE:
When it comes to controlling a servo, there are many ways by which you you can control it, but in most cases you'll be using PIC microcontrollers.

If y'r a beginer or a novice with PIC microcontrollers, their programmers, compilers and the softwares used to burn the code on to the PIC's, please check out my other posts in this blog.I will try to post all the possible stuff for newbies.

In fact, handling PIC's, writing code, burninig the code onto the PIC's, and most important of all.....assembling y'r own PIC programmer!!!.......all this's not that difficult as it might sound!
It's just a matter of having a little prerequisite electronics knowledge(i'll cover even that), and above all, y'r passion and interest.

If y'r aware of PIC programming and all, check these links.

(there's code provided, which you need to compile in picBasic compiler(from Microchip technologies) or any other appropriate compiler, to convert the code into a HEX file( .HEX is a format that the pic's understand and execute, which is something like machine code) .More on programming stuff in the tutorials post.)

(The below links correspond to basic control of servos)

http://www.imagesco.com/articles/picservo/02.html
(first servo motor control program and the circuit)

http://www.imagesco.com/articles/picservo/03.html
(manual servo motor control)

http://www.imagesco.com/articles/picservo/04.html
(multiple servo motors)

http://www.newcircuits.com/circuit.php?id=uct001
(servo motor control with pic 16f84)

http://www.uashem.com/pageid-459.html
(another neat and simple link for controlling servos with pic 16f84 micro controllers)

PicBasic program and cicuit to center a servomotor:

The following program is for the PicBasic Pro compiler .

‘PicBasic Pro program to center a servomotor
start:
pulsout portb.0, 150 ‘Send pulse out on rb0
pause 18 ‘Delay needed to send pulse at 55 Hz
goto start ‘Repeat


Required parts list:
(2) 22pF capacitors
(1) Solderless breadboard RadioShack PN# 276175
(1) 0.1 mF capacitor RadioShack PN# 2721069
(2) Red LEDs RadioShack PN# 276208
(2) 470 V resistors* RadioShack PN# 2701115
(1) 4.7k V resistor RadioShack PN# 2711126
(1) Voltage regulator (7805) RadioShack PN# 2761770
(1) 9V battery clip RadioShack PN# 270325


What's a servo motor?

Whats a Servo?

A Servo is a small device that has an output shaft. This shaft can be positioned to specific angular positions by sending the servo a coded signal. As long as the coded signal exists on the input line, the servo will maintain the angular position of the shaft. As the coded signal changes, the angular position of the shaft changes. In practice, servos are used in radio controlled airplanes to position control surfaces like the elevators and rudders. They are also used in radio controlled cars, puppets, and of course, robots.

Picture of a servo


A Futaba S-148 Servo

Servos are extremely useful in robotics. The motors are small, as you can see by the picture above, have built in control circuitry, and are extremely powerful for thier size. A standard servo such as the Futaba S-148 has 42 oz/inches of torque, which is pretty strong for its size. It also draws power proportional to the mechanical load. A lightly loaded servo, therefore, doesn't consume much energy. The guts of a servo motor are shown in the picture below. You can see the control circuitry, the motor, a set of gears, and the case. You can also see the 3 wires that connect to the outside world. One is for power (+5volts), ground, and the white wire is the control wire.

Picture of servo guts


A servo disassembled.

So, how does a servo work? The servo motor has some control circuits and a potentiometer (a variable resistor, aka pot) that is connected to the output shaft. In the picture above, the pot can be seen on the right side of the circuit board. This pot allows the control circuitry to monitor the current angle of the servo motor. If the shaft is at the correct angle, then the motor shuts off. If the circuit finds that the angle is not correct, it will turn the motor the correct direction until the angle is correct. The output shaft of the servo is capable of travelling somewhere around 180 degrees. Usually, its somewhere in the 210 degree range, but it varies by manufacturer. A normal servo is used to control an angular motion of between 0 and 180 degrees. A normal servo is mechanically not capable of turning any farther due to a mechanical stop built on to the main output gear.

The amount of power applied to the motor is proportional to the distance it needs to travel. So, if the shaft needs to turn a large distance, the motor will run at full speed. If it needs to turn only a small amount, the motor will run at a slower speed. This is called proportional control.

How do you communicate the angle at which the servo should turn? The control wire is used to communicate the angle. The angle is determined by the duration of a pulse that is applied to the control wire. This is called Pulse Coded Modulation. The servo expects to see a pulse every 20 milliseconds (.02 seconds). The length of the pulse will determine how far the motor turns. A 1.5 millisecond pulse, for example, will make the motor turn to the 90 degree position (often called the neutral position). If the pulse is shorter than 1.5 ms, then the motor will turn the shaft to closer to 0 degress. If the pulse is longer than 1.5ms, the shaft turns closer to 180 degress.

Pulse Coded Modulation Picture

As you can see in the picture, the duration of the pulse dictates the angle of the output shaft (shown as the green circle with the arrow). Note that the times here are illustrative, and the actual timings depend on the motor manufacturer. The principle, however, is the same.



Servomechanism



Small R/C servo mechanism 1. electric motor 2. position feedback potentiometer 3. reduction gear 4. actuator arm
Small R/C servo mechanism
1. electric motor
2. position feedback potentiometer
3. reduction gear
4. actuator arm

A servomechanism, or servo is an automatic device which uses error-sensing feedback to correct the performance of a mechanism. The term correctly applies only to systems where the feedback or error-correction signals help control mechanical position or other parameters. For example an automotive power window control is not a servomechanism, as there is no automatic feedback which controls position -- the operator does this by observation. By contrast the car's cruise control uses closed loop feedback, which classifies it as a servomechanism.

Servomechanisms may or may not use a servomotor. For example a household furnace controlled by thermostat is a servomechanism, yet there is no closed-loop control of a servomotor.

A common type of servo provides position control. Servos are commonly electrical or partially electronic in nature, using an electric motor as the primary means of creating mechanical force. Other types of servos use hydraulics, pneumatics, or magnetic principles. Usually, servos operate on the principle of negative feedback, where the control input is compared to the actual position of the mechanical system as measured by some sort of transducer at the output. Any difference between the actual and wanted values (an "error signal") is amplified and used to drive the system in the direction necessary to reduce or eliminate the error. An entire science known as control theory has been developed on this type of system.

Servomechanisms were first used in military fire-control and marine navigation equipment. Today servomechanisms are used in automatic machine tools, satellite-tracking antennas, automatic navigation systems on boats and planes, and antiaircraft-gun control systems. Other examples are fly-by-wire systems in aircraft which use servos to actuate the aircraft's control surfaces, and radio-controlled models which use RC servos for the same purpose. Many autofocus cameras also use a servomechanism to accurately move the lens, and thus adjust the focus.

Typical servos give a rotary (angular) output. Linear types are common as well, using a screw thread or a linear motor to give linear motion.

Another device commonly referred to as a servo is used in automobiles to amplify the steering or braking force applied by the driver. In this form this device is not a true servo, but rather a mechanical amplifier.

In industrial machines, servos are used to perform complex motion.

RC servos

RC servos are servos typically employed in industrial robotics, automation, and radio-controlled models. They are also used to provide actuation for various mechanical systems such as the steering of a car, the flaps on a plane, or the rudder of a boat.

RC servos are comprised of a DC motor mechanically linked to a potentiometer. Pulse-width modulation (PWM) signals sent to the servo are translated into position commands by electronics inside the servo. When the servo is commanded to rotate, the DC motor is powered until the potentiometer reaches the value corresponding to the commanded position that it's ordered.

Due to their affordability, reliability, and simplicity of control by modern microprocessors, servo motors are often used in small-scale robotics applications.

The servo is controlled by three wires: ground (black/orange), power (red) and control (brown/other colour) and will move based on the pulses sent over the control wire. This wiring sequence is not true for all servos, for example the S03NXF Std. Servo is wired as brown(negative), red (positive) and orange (signal). The pulses sent over the control wire set the angle of the servo horn. The servo expects a pulse every 20 ms in order to gain correct information about the angle. The width of the servo pulse dictates the range of the servo's angular motion.


A servo pulse of 1.5 ms width will set the servo to its "neutral" position, or 90°. For example a servo pulse of 1.25 ms could set the servo to 0° and a pulse of 1.75 ms could set the servo to 180°. The physical limits and timings of the servo hardware varies between brands and models, but a general servo's angular motion will travel somewhere in the range of 180° - 210° and the neutral position is almost always at 1.5ms.

Servo motors are often powered from nickel-cadmium battery packs common to most RC devices. Voltage ratings vary from product to product, but most servos are operated at 4.8 V DC or 6.0 V DC (a 4 or 5 cell battery).

Servo Wiring
All servos have three wires:
Black or Brown is for ground.
Red is for power (~4.8-6V).
Yellow, Orange, or White is the signal wire (3-5V).

Servo Voltage (Red and Black/Brown wires)
Servos can operate under a range of voltages. Typical operation is from 4.8V to 6V. There are a few micro sized servos that can operate at less, and now a few Hitec servos that operate at much more. The reason for this standard range is because most microcontrollers and RC receivers operate near this voltage. So what voltage should you operate at? Well, unless you have a
battery voltage/current/power limitation, you should operate at 6V. This is simply because DC motors have higher torque at higher voltages.


Signal Wire (Yellow/Orange/White wire)
While the black and red wires provide power to the motor, the signal wire is what you use to command the servo. The general concept is to simply send an ordinary logic square wave to your servo at a specific wave length, and your servo goes to a particular angle (or velocity if your servo is modified). The wavelength directly maps to servo angle.

Hitec Servo Connector Futaba Servo Connector