Sie sind auf Seite 1von 149

UNIT-II Microcontrollers

INTRODUCTION TO PIC. Microcontroller is a single chip micro computer made through VLSI fabrication. A microcontroller also called an embedded controller because the microcontroller and its support circuits are often built into, or embedded in, the devices they control. A microcontroller is available in different word lengths like microprocessors (4bit,8bit,16bit,32bit,64bit and 128 bit microcontrollers are available today).

Microcontroller Chip You can find microcontrollers in all kinds of electronic devices these days. Any device that measures, stores, controls, calculates, or displays information must have a microcontroller chip inside. The largest single use for microcontrollers is in automobile industry (microcontrollers widely used for controlling engines and power controls in automobiles). You can also find microcontrollers inside keyboards, mouse, modems, printers, and other peripherals. In test equipments, microcontrollers make it easy to add features such as the ability to store measurements, to create and store user routines, and to display messages and waveforms. Consumer products that use microcontrollers include digital camcorders, optical players, LCD/LED display units, etc. And these are just a few examples. 1) A microcontroller basically contains one or more following components:

Central processing unit(CPU) Random Access Memory)(RAM) Read Only Memory(ROM) Input/output ports Timers and Counters Interrupt Controls Analog to digital converters

Digital analog converters Serial interfacing ports Oscillatory circuits

2) A microcontroller internally consists of all features required for a computing system and functions as a computer without adding any external digital parts in it. 3) Most of the pins in the microcontroller chip can be made programmable by the user. 4) A microcontroller has many bit handling instructions that can be easily understood by the programmer. 5) A microcontroller is capable of handling Boolean functions. 6) Higher speed and performance. 7) On-chip ROM structure in a microcontroller provides better firmware security. 8 ) Easy to design with low cost and small size.

Microcontroller structure
The basic structure and block diagram of a microcontroller is shown in the fig (1.1).

Microcontroller Structure Image Taken From

CPU

CPU is the brain of a microcontroller .CPU is responsible for fetching the instruction, decodes it, then finally executed. CPU connects every part of a microcontroller into a single system. The primary function of CPU is fetching and decoding instructions. Instruction fetched from program memory must be decoded by the CPU.

Memory

The function of memory in a microcontroller is same as microprocessor. It is used to store data and program. A microcontroller usually has a certain amount of RAM and ROM (EEPROM, EPROM, etc) or flash memories for storing program source codes.

Parallel input/output ports

Parallel input/output ports are mainly used to drive/interface various devices such as LCDS, LEDS, printers, memories, etc to a microcontroller.

Serial ports

Serial ports provide various serial interfaces between microcontroller and other peripherals like parallel ports.

Timers/counters

This is the one of the useful function of a microcontroller. A microcontroller may have more than one timer and counters. The timers and counters provide all timing and counting functions inside the microcontroller. The major operations of this section are perform clock functions, modulations, pulse generations, frequency measuring, making oscillations, etc. This also can be used for counting external pulses.

Analog to Digital Converter (ADC)

ADC converters are used for converting the analog signal to digital form. The input signal in this converter should be in analog form (e.g. sensor output) and the output from this unit is in digital form. The digital output can be use for various digital applications (e.g. measurement devices).

Digital to Analog Converter (DAC)

DAC perform reversal operation of ADC conversion.DAC convert the digital signal into analog format. It usually used for controlling analog devices like DC motors, various drives, etc.

Interrupt control

The interrupt control used for providing interrupt (delay) for a working program .The interrupt may be external (activated by using interrupt pin) or internal (by using interrupt instruction during programming).

Special functioning block

Some microcontrollers used only for some special applications (e.g. space systems and robotics) these controllers containing additional ports to perform such special operations. This considered as special functioning block.

Comparison between Microprocessor and Microcontroller

The main comparison between microprocessor and microcontroller shown in fig (1.2)

Comparison of Micrprocessor and Microcontroller Source Of Image Microprocessors Microcontrollers 1 It is only a general purpose computer It is a micro computer itself CPU 2 Memory, I/O ports, timers, interrupts All are integrated inside the microcontroller chip are not available inside the chip 3 This must have many additional digital Can function as a micro computer without any components to perform its operation additional components. 4 Systems become bulkier and Make the system simple, economic and compact

5 6 7 8 9 E.g.

expensive. Not capable for handling Boolean Handling Boolean functions functions Higher accessing time required Low accessing time Very few pins are programmable Most of the pins are programmable Very few number of bit handling Many bit handling instructions instructions Widely Used in modern PC and widely in small control systems laptops INTEL 8086,INTEL Pentium series INTEL8051,89960,PIC16F877

Advantages of Microcontrollers
The main advantages of microcontrollers are given. a) b) c) d) e) f) Microcontrollers act as a microcomputer without any digital parts. As the higher integration inside microcontroller reduce cost and size of the system. Usage of microcontroller is simple, easy for troubleshoot and system maintaining. Most of the pins are programmable by the user for performing different functions. Easily interface additional RAM, ROM,I/O ports. Low time required for performing operations.

Disadvantages of Microcontrollers
a) b) c) d) Microcontrollers have got more complex architecture than that of microprocessors. Only perform limited number of executions simultaneously. Mostly used in micro-equipments. Cannot interface high power devices directly.

Applications
Microcontrollers are widely used in modern electronics equipments. Some basic applications of microcontroller is given below. a) b) Used in biomedical instruments. Widely used in communication systems.

c) d) e)

Used as peripheral controller in PC. Used in robotics. Used in automobile fields.

Introduction to Peripheral Interface Controllers (PIC)


Peripheral Interface Controllers (PIC) is one of the advanced microcontrollers developed by microchip technologies. These microcontrollers are widely used in modern electronics applications. A PIC controller integrates all type of advanced interfacing ports and memory modules. These controllers are more advanced than normal microcontroller like INTEL 8051. The first PIC chip was announced in 1975 (PIC1650). As like normal microcontroller, the PIC chip also combines a microprocessor unit called CPU and is integrated with various types of memory modules (RAM, ROM, EEPROM ,etc), I/O ports, timers/counters, communication ports, etc.

PIC Chip Image From All PIC microcontroller family uses Harvard architecture. This architecture has the program and data accessed from separate memories so the device has a program memory bus and a data memory bus (more than 8 lines in a normal bus). This improves the bandwidth (data throughput) over traditional von Neumann architecture where program and data are fetched from the same memory (accesses over the same bus). Separating program and data memory further allows instructions to be sized differently than the 8-bit wide data word. Basic structure of a modern Peripheral interface controller chip is show in the picture below.

PIC Structure CPU


The function of CPU in PIC is same as a normal microcontroller CPU. A PIC CPU consists of several sub units such as instruction decoder, ALU, accumulator, control unit, etc. The CPU in PIC normally supports Reduced Instruction Set Computer (RISC) architecture (Reduced Instruction Set Computer (RISC), a type of microprocessor that focuses on rapid and efficient processing of a relatively small set of instructions. RISC design is based on the premise that most of the instructions a computer decodes and executes are simple. As a result, RISC architecture limits the number of instructions that are built into the microcontroller but optimizes each so it can be carried out very rapidly (usually within a single clock cycle.) . These RISC structure gives the following advantages.

The RISC structure only has 35 simple instructions as compared to others The execution time is same for most of the instructions (except very few numbers). The execution time required is very less (5 million instructions/second (approximately).

Memory
The memory in a PIC chip used to store the data and programs temporary or permanently. As like normal microcontrollers, the PIC chip also has certain amount of RAM, ROM, EEPROM, other flash memory, etc. ROM memory is used for permanent storage. The ROM memory also called as n program memory. A PI chip has certain amount of ROM memory. EEPROM memory is another category of ROM memory. The contents in the EEPROM changes during run time and at that time it acts like a RAM memory. But the difference is after the power goes off , the data remains in this ROM chip. This is the one of the special advantages of EEPROM. In the PIC chip the function of EPROM is to store the values created during the runtime. RAM memory is the one of the complex memory module in a PIC chip. This memory associated with various type of registers (special function registers and general purpose registers) and memory BANK modules (BANK 0, BANK 1, etc.). Once the power goes off, the contents in the RAM will be cleared. As like normal microcontrollers, the RAM memory is used to store temporary data and provide immediate results.

Flash memory
This is a special type of memory where READ, WRITE, and ERASE operations can be done many times. This type of memory was invented by INTEL corporation in 1980. A PIC Chip normally contains a certain amount of flash memory.

Registers
Information is stored in a CPU memory location called a register. Registers can be thought of as the CPUs tiny scratchpad, temporarily storing instructions or data. Registers basically classified into the following. 1) General Purpose Register (GPR) A general purpose register (or processor register) is a small storage area available on a CPU whose contents can be accessed more quickly than other storage that available on PIC. A general purpose register can store both data addresses simultaneously. 2) Special Function registers (SFR) These are also a part of RAM memory locations. As compared to GPR, their purpose is predetermined during the manufacturing time and cannot be changed by the user. It is only for special dedicated functions.

Interrupts

Interrupt is the temporary delay in a running program. These delays stop the current execution for a particular interval. This interval/delay is usually called as interrupt. When an interrupt request arrives into a current execution program, then it stops its regular execution. Interrupt can be performed by externally (hardware interrupt) or internally (by using software).

Bus
BUS is the communication or data transmission/reception path in a microcontroller unit. In a normal microcontroller chip, two types of buses are normally available. 1) Data bus Data bus is used for memory addressing. The function of data bus is interfacing all the circuitry components inside the PIC chip. 2) Address bus Address bus mostly used for memory addressing. The function of address bus is to transmit the address from the CPU to memory locations.

USART or UART
These ports are used for the transmission (TX) and reception (RX) of data. These transmissions possible with help of various digital data transceiver modules like RF, IR, Bluetooth, etc. This is the one of the simplest way to communicate the PIC chip with other devices.

Oscillators
Oscillator unit basically an oscillation/clock generating circuit which is used for providing proper clock pulses to the PIC chip. This clock pulses also helps the timing and counting applications . A PIC chip normally use various types of clock generators. According to the application and the type of PIC used, the oscillators and its frequencies may vary. RC (Resistor-Capacitor), LC (Inductor-Capacitor), RLC (Resistor-Inductor-capacitor), crystal oscillators, etc are the normal oscillators used with A PIC chip.

STACK
The entire PIC chip has an area for storing the return addresses. This area or unit called Stack is used in some Peripheral interface controllers. The hardware stack is not accessible by software. But for most of the controllers, it can be easily accessible.

Input/output ports
These ports are used for the interfacing various input/output devices and memories. According to the type of PIC, the number of ports may change.

Advanced functioning blocks

These sections include various advanced features of a PIC chip. According to the type of PIC, these features may change. Various advanced features in a peripheral interface controller are power up timer, oscillator start up timer, power on reset, watch dog timer, brown out reset, in circuit debugger, low voltage programming, voltage comparator, CCP modules etc.

Limitations of PIC Architecture


Interface Controller Small Register banking switch required to Operations and registers Program memory is not accessible. Peripheral has only one accumulator. instruction set. access RAM of other devices. are not orthogonal.

Advantages of PIC Controlled System


Reliability The PIC controlled system often resides machines that are expected to run continuously for many years without any error and in some cases recover by themselves if an error occurs(with help of supporting firmware). Performance Many of the PIC based embedded system use a simple pipelined RISC processor for computation and most of them provide on-chip SRAM for data storage to improve the performance. Power consumption A PIC controlled system operates with minimal power consumption without sacrificing performance. Power consumption can be reduced by independently and dynamically controlling multiple power platforms. Memory Most of the PIC based systems are memory expandable and will help in easily adding more and more memory according to the usage and type of application. In small applications the inbuilt memory can be used

Architecture and Memory Organization of PIC 16F877


The basic building block of PIC 16F877 is based on Harvard architecture. This microcontroller also has many advanced features as mentioned in the previous post. Here you can see the basic internal architecture and memory organisation of PIC16F877.

Architecture of PIC16F877
The figure below shows the internal architecture of a PIC16F877A chip.

Internal Architecture of PIC16F877A Chip The use of each functional block inside this controller has already been explained in the previous post. Now let us look in to the detailed explanation about each sections inside the PIC 16F877.

Memory Organization of PIC16F877


The memory of a PIC 16F877 chip is divided into 3 sections. They are 1. Program memory 2. Data memory and

3. Data EEPROM 1. Program memory Program memory contains the programs that are written by the user. The program counter (PC) executes these stored commands one by one. Usually PIC16F877 devices have a 13 bit wide program counter that is capable of addressing 8K14 bit program memory space. This memory is primarily used for storing the programs that are written (burned) to be used by the PIC. These devices also have 8K*14 bits of flash memory that can be electrically erasable /reprogrammed. Each time we write a new program to the controller, we must delete the old one at that time. The figure below shows the program memory map and stack.

PIC16f877 Program Memory

Program counters (PC) is used to keep the track of the program execution by holding the address of the current instruction. The counter is automatically incremented to the next instruction during the current instruction execution. The PIC16F87XA family has an 8-level deep x 13-bit wide hardware stack. The stack space is not a part of either program or data space and the stack pointers are not readable or writable. In the PIC microcontrollers, this is a special block of RAM memory used only for this purpose. Each time the main program execution starts at address 0000 Reset Vector. The address 0004 is reserved for the interrupt service routine (ISR). 2. PIC16F87XA Data Memory Organization The data memory of PIC16F877 is separated into multiple banks which contain the general purpose registers (GPR) and special function registers (SPR). According to the type of the microcontroller, these banks may vary. The PIC16F877 chip only has four banks (BANK 0, BANK 1, BANK 2, and BANK4). Each bank holds 128 bytes of addressable memory.

Data Memory Organization

IMAGE TAKEN FROM The banked arrangement is necessary because there are only 7 bits are available in the instruction word for the addressing of a register, which gives only 128 addresses. The selection of the banks are determined by control bits RP1, RP0 in the STATUS registers Together the RP1, RP0 and the specified 7 bits effectively form a 9 bit address. The first 32 locations of Banks 1 and 2, and the first 16 locations of Banks2 and 3 are reserved for the mapping of the Special Function Registers (SFRs). BANK 0 1 2 3 RP0 0 1 0 1 RP1 0 0 1 1

A bit of RP1 & RP0 of the STATUS register selects the bank access. 3. Data EEPROM and FLASH The data EEPROM and Flash program memory is readable and writable during normal operation (over the full VDD range). This memory is not directly mapped in the register file space. Instead, it is indirectly addressed through the Special Function Registers. There are six SFRs used to read and write this memory: EECON1 EECON2 EEDATA EEDATH EEADR EEADRH The EEPROM data memory allows single-byte read and writes. The Flash program memory allows single-word reads and four-word block writes. Program memory write operations automatically perform an erase-before write on blocks of four words. A byte write in data EEPROM memory automatically erases the location and writes the new data (erase-beforewrite). The write time is controlled by an on-chip timer. The write/erase voltages are generated by an on-chip charge pump, rated to operate over the voltage range of the device for byte or word operations.

Register Memory Organization in PIC 16F877

A register is a place inside the PIC which used to read or write the data/program. The memory of the PIC is divided into a series of registers. Each of the registers has its own address and memory locations. These addresses are normally denoted by using hexadecimal numbers. According to the type of working and usage, the registers in PIC are classified into two categories. General Purpose Registers (GPR) GPR is a small amount of storage that can be accessible more quickly than any other memory. These register files can be accessed either directly, or indirectly, through the File Select Register (FSR). The General Purpose Register (GPR) memory map (PIC16F877A) is shown in the figure below.

General Purpose Register - PIC 16F877 Special Function Registers (SFR) The special function registers are also memory registers which is used for special dedicated functions. These registers perform various dedicated functions inside the PIC chip. Each special

function inside this PIC chip is controlled by using these registers. These registers are used by the CPU and peripheral modules for controlling the desired operation of the device. These registers are normally implemented as in the form of static RAM memory. A list of these registers is given in the tables below. The Special Function Registers can be classified into two sets: core (CPU) and peripheral. Those registers associated with the core functions are described in detail in this section. The figures below shows SFR memory map of PIC16F877.

Special Function Registers (SFR) - PIC 16F877

Special Function Registers (SFR) - PIC 16F877 Status Register Status register is an eight bit register that contains the arithmetic status of the arithmetic logic unit (ALU), the reset status and the bank select bits for the data memory. The detailed explanation of status register is given below. Status registers (address 03h, 83h, 103h, and 183h) R/W*-0 IRP Bit7 Bit 0 (*R/W-readable/writable, **x-unknown bit)

R/W-0 RP1

R/W-0 RP0

R-1 TO

R-1 PD

R/W-x** Z

R/W-x DC

R/W-x C

Bit 7 (IRP): this is a Register Bank Select Bit usually used for indirect addressing mode. Bit 6-5 (RP1:RP0): these bits are Register Bank Select bits commonly used for direct addressing mode (each banks in this mode carry 128 byes)

(11 = Bank 3 (180h-1FFh) 10 = Bank 2 (100h-17Fh) 01 = Bank 1 (80h-FFh) 00 = Bank 0 (00h-7Fh))

Bit 4, (TO): this is a time-out bit used for timing and counting, sleep and reset functions.

(1 = after power-up, CLRWDT instruction or SLEEP instruction 0 = A WDT time-out occurred)

Bit 3, (PD): Power-down bit

(1 = after power-up or by the CLRWDT instruction 0 = by execution of the SLEEP instruction)

Bit 2, (Z): Zero bit

(1 = the result of an arithmetic or logic operation is zero 0 = the result of an arithmetic or logic operation is not zero.)

Bit 1 DC: Digit carry/borrow bit (ADDWF, ADDLW, SUBLW, SUBWF instructions)

(For borrow, the polarity is reversed) (1 = A carry-out from the 4th low order bit of the result occurred 0 = No carry-out from the 4th low order bit of the result.)

Bit 0 (C): Carry/borrow bit (ADDWF, ADDLW, SUBLW, SUBWF instructions)

(1 = A carry-out from the Most Significant bit of the result occurred 0 = No carry-out from the Most Significant bit of the result occurred.) Option Register The option Register is a readable and writable register, which contains various control bits to configure the TMR0 prescaler/WDT postscaler (single assignable register known also as the prescaler), the external INT interrupt andTMR0 and the weak pull-ups on PORTB. Structure of option register is shown below. R/W-1 R/W-1 RBPU(inverting) INTEDG 7 0

R/W-1 T0CS

R/W-1 T0SE

R/W-1 PSA

R/W-1 PS2

R/W-1 PS1

R/W-1 PS0

Bit 7 (RBPU): This is a PORTB Pull-up Enable bit. If this bit is 1 then PORTB pullup function disabled. If this bit is 0, it enabled the pull-up function by individual portlatch values.

(1 = PORTB pull-ups are disabled. 0 = PORTB pull-ups are enabled by individual port latch values.)

Bit 6 (INTEDG): This is an Interrupt Edge Select bit. This bit decided if the interrupt is on either raisin edge or falling edge. The function of this bit is given below.

(1 = Interrupt on rising edge of RB0/INT pin.

0 = Interrupt on falling edge of RB0/INT pin.)

Bit 5 (T0CS): this is a timer-0(TMR0) Clock Source Select bit and its function is given below.

(1 = Transition on RA4/T0CKI pin. 0 = Internal instruction cycle clock (CLKO).)

Bit 4 (T0SE): TMR0 Source Edge Select bit which select the timer 0 source edge.

(1 = Increment on high-to-low transition on RA4/T0CKI pin. 0 = Increment on low-to-high transition on RA4/T0CKI pin.)

Bit 3 (PSA): Prescaler Assignment bit.

(1 = Prescaler is assigned to the Watch Dog Timer (WDT). 0 = Prescaler is assigned to the Timer0 module.)

Bit 2-0 (PS2:PS0): Prescaler Rate Select bits.

INTCON Register The INTCON register is a readable and writable register, which contains various enable and flag bits for the TMR0 register overflow, RB port change and external RB0/INT pin interrupts. The architecture of this register is given below. R/W-0 GIE

R/W-0 PEIE

R/W-0 TMR0IE

R/W-0 INTE

R/W-0 RBIE

R/W-0 TMR0IF

R/W-0 INTF

R/W-x RBIF

Bit 7 GIE: Global Interrupt Enable bit. If this bit is enable (1), which also enable all unmasked interrupts and if it is zero (0), which disable all interrupts.

(1 = Enables all unmasked interrupts. 0 = Disables all interrupts.)

Bit 6 (PEIE): this is a Peripheral Interrupt Enable bit which used for controlling peripheral interrupts. If this bit is enable(1), also enable all unmasked peripheral interrupts and if it is disable(0), also disable all active peripheral interrupt actions.

(1 = Enables all unmasked peripheral interrupts

0 = Disables all peripheral interrupts)

Bit 5 (TMR0IE): This is timer 0(TMR0) Overflow Interrupt Enable bit which control the overflow interrupt in timer 0.

(1 = Enables the TMR0 interrupt 0 = Disables the TMR0 interrupt)

Bit 4 (INTE): This is an RB0/INT External Interrupt Enable bit which used for enable/disable external interrupts.

(1 = Enables the RB0/INT external interrupt 0 = Disables the RB0/INT external interrupt)

Bit 3 (RBIE): RB Port Change Interrupt Enable bit which control PORTB change interrupt.

(1 = Enables the RB port change interrupt. 0 = Disables the RB port change interrupt.)

Bit 2 (TMR0IF): TMR0 Overflow Interrupt Flag bit which controls the overflow of timer 0.

(1 = TMR0 register has overflowed [must be cleared in software] 0 = TMR0 register did not overflow)

Bit 1 (INTF): RB0/INT External Interrupt Flag control bit.

(1 = The RB0/INT external interrupt occurred (must be cleared in software) 0 = The RB0/INT external interrupt did not occur).

Bit 0 (RBIF): RB Port Change Interrupt Flag bit.

(1 = At least one of the RB7:RB4 pins changed state; a mismatch condition will continue to set that bit. Reading PORTB will end the mismatch condition and allow the bit to be cleared [Must be cleared in software] ). PIE1 Register

The PIE1 register contains the individual enable bits for the peripheral interrupts. The structure of this register is shown below. R/W-0 PSPIE

R/W-0 ADIE

R/W-0 RCIE

R/W-0 TXIE

R/W-0 SSPIE

R/W-0 CCP1IE

R/W-0 TMR2IE

R/W-0 TMR1IE

Bit 7 (PSPIE): this bit is the Parallel Slave Port Read/Write Interrupt Enable bit

(1 = Enables the PSP read/write interrupt 0 = Disables the PSP read/write interrupt)

Bit 6 (ADIE): A/D Converter Interrupt Enable bit which control the analog to digital converter interrupt.

(1 = Enables the A/D converter interrupt 0 = Disables the A/D converter interrupt)

Bit 5 (RCIE): USART Receive Interrupt Enable bit which control the USART data reception interrupt.

(1 = Enables the USART receive interrupt 0 = Disables the USART receive interrupt)

Bit 4 (TXIE): USART Transmit Interrupt Enable bit that control USART data transmission.

(1 = Enables the USART transmit interrupt 0 = Disables the USART transmit interrupt)

Bit 3 (SSPIE): Synchronous Serial Port Interrupt Enable bit that control SSP data interrupt.

(1 = Enables the SSP interrupt 0 = Disables the SSP interrupt)

Bit 2 (CCP1IE): CCP1 Interrupt Enable bit which control the capture-compare-pulse width modulation interrupt.

(1 = Enables the CCP1 interrupt 0 = Disables the CCP1 interrupt)

Bit 1 (TMR2IE): TMR2 to PR2 Match Interrupt Enable bit.

(1 = Enables the TMR2 to PR2 match interrupt 0 = Disables the TMR2 to PR2 match interrupt)

Bit 0 (TMR1IE): TMR1 Overflow Interrupt Enable bit that control the overflow interrupt of timer 1 module.

(1 = Enables the TMR1 overflow interrupt 0 = Disables the TMR1 overflow interrupt) PIR1 Register The PIR1 register contains the individual flag bits for the peripheral interrupt. The structure of PIR1 register is given below. R/W-0 PSPIF

R/W-0 ADIF

R-0 RCIF

R-0 TXIF

R/W-0 SSPIF

R/W-0 CCP1IF

R/W-0 TMR2IF

R/W-0 TMR1IF

Bit 7 (PSPIF): Parallel Slave Port Read/Write Interrupt Flag bit.

(1 = A read or a write operation has taken place (must be cleared in software) 0 = No read or write has occurred)

Bit 6 (ADIF): A/D Converter Interrupt Flag bit that control the interrupt flag for that analog to digital converter.

(1 = An A/D conversion completed 0 = The A/D conversion is not complete)

Bit 5 (RCIF): USART Receive Interrupt Flag bit.

(1 = The USART receive buffer is full 0 = The USART receive buffer is empty)

Bit 4 (TXIF): USART Transmit Interrupt Flag bit.

(1 = The USART transmit buffer is empty 0 = The USART transmit buffer is full)

Bit 3 (SSPIF): Synchronous Serial Port (SSP) Interrupt Flag bit that control the SSP interrupt flag in a PIC.

(1 = The SSP interrupt condition has occurred and must be cleared in software before returning from the Interrupt Service Routine. The conditions that will set this bit are: SPI A transmission/reception has taken place. I2C Slave A transmission/reception has taken place. I2C Master - A transmission/reception has taken place. - The initiated Start condition was completed by the SSP module. - The initiated Stop condition was completed by the SSP module. - The initiated Restart condition was completed by the SSP module. - The initiated Acknowledge condition was completed by the SSP module. - A Start condition occurred while the SSP module was Idle (multi-master system). - A Stop condition occurred while the SSP module was Idle (multi-master system). 0 = No SSP interrupt condition has occurred)

Bit 2 (CCP1IF): CCP1 Interrupt Flag bit that control capture-compare-pulse width modulation interrupt flag. It works in three modes. They are given below. Capture mode:

1.

1 = A TMR1 register capture occurred (must be cleared in software) 0 = No TMR1 register capture occurred 2. Compare mode:

1 = A TMR1 register compare match occurred (must be cleared in software) 0 = No TMR1 register compare match occurred 3.

PWM mode: Bit 1 (TMR2IF): TMR2 to PR2 Match Interrupt Flag bit

(1 = TMR2 to PR2 match occurred (must be cleared in software) 0 = No TMR2 to PR2 match occurred)

Bit 0 (TMR1IF): TMR1 Overflow Interrupt Flag bit.

(1 = TMR1 register overflowed (must be cleared in software) 0 = TMR1 register did not overflow) PIE2 Register The PIE2 register contains the individual enable bits for the CCP2 peripheral interrupt, the SSP bus collision Interrupt, EEPROM write operation interrupt and the comparator interrupt. The structure of this register is given below. U-0 R/W-0 CMIE U-0 R/W-0 EEIE R/W-0 BCLIE U-0 U-0 R/W-0 CCP2IE -

Bit 7 Unimplemented: Read as 0 Bit 6 (CMIE): Comparator Interrupt Enable bit

(1 = Enables the comparator interrupt 0 = Disable the comparator interrupt)

Bit 5 Unimplemented: Read as 0

Bit 4 (EEIE): EEPROM Write Operation Interrupt Enable bit (1 = Enable EEPROM write interrupt 0 = Disable EEPROM write interrupt)

Bit 3 (BCLIE): Bus Collision Interrupt Enable bit.

(1 = Enable bus collision interrupt 0 = Disable bus collision interrupt)


Bit 2-1 Unimplemented: Read as 0 Bit 0 (CCP2IE): CCP2 Interrupt Enable bit.

(1 = Enables the CCP2 interrupt 0 = Disables the CCP2 interrupt) PIR2 Register The PIR2 register contains the flag bits for the CCP2 interrupt, the SSP bus collision interrupt, EEPROM write operation interrupt and the comparator interrupt. The structure of this register is given below. U-0 R/W-0 CMIF U-0 R/W-0 EEIF R/W-0 BCLIF U-0 U-0 R/W-0 CCP2IF -

Bit 7 Unimplemented: Read as 0 Bit 6 (CMIF): Comparator Interrupt Flag bit

(1 = the comparator input has changed (must be cleared in software) 0 = the comparator input has not changed)

Bit 5 Unimplemented: Read as 0 Bit 4 (EEIF): EEPROM Write Operation Interrupt Flag bit.

(1 = the write operation completed (must be cleared in software) 0 = the write operation is not complete or has not been started)

Bit 3 (BCLIF): Bus Collision Interrupt Flag bit.

(1 = A bus collision has occurred in the SSP when configured for I2C Master Mode 0 = No bus collision has occurred)

Bit 2-1 Unimplemented: Read as 0 Bit 0 (CCP2IF): CCP2 Interrupt Flag bit. This also works in three modes. They ere Capture mode:

1.

1 = A TMR1 register capture occurred (must be cleared in software) 0 = No TMR1 register capture occurred Compare mode: 1 = A TMR1 register compare match occurred (must be cleared in software)

0 = No TMR1 register compare match occurred 2. PWM mode:

This mode is not used. PCON Register The Power Control (PCON) register contains flag bits to allow differentiation between a Poweron Reset (POR), a Brown-out Reset (BOR), a Watchdog Reset (WDT) and an external MCLR Reset. The structure of this register is given below. U-0

U-0 -

U-0 -

U-0 -

U-0 -

U-0

R/W-0 R/W-1 POR(inverting) BOR(inverting)

Bit 7-2 Unimplemented: Read as 0 Bit 1 (POR): Power-on Reset Status bit

(1 = No Power-on Reset occurred 0 = A Power-on Reset occurred (must be set in software after a Power-on Reset occurs)

Bit 0(BOR): Brown-out Reset Status bit

(1 = No Brown-out Reset occurred 0 = A Brown-out Reset occurred (must be set in software after a Brown-out Reset occurs).

ADDRESSING MODES:
There are 3 types of addressing modes in PIC Immediate Addressing Movlw H0F Direct Addressing Uses 7 bits of 14 bit instruction to identify a register file address 8th and 9th bit comes from RP0 and RP1 bits of STATUS register. Exp: Z equ D2

btfss

STATUS, Z

Indirect Addressing Full 8 bit register address is written the special function register FSR INDF is used to get the content of the address pointed by FSR Exp : A sample program to clear RAM locations H20 H2F .

Instruction Sets in PIC


Instruction sets are the source codes that are written by the programmer for performing the desired operations in a PIC chip. These codes can be usually written in any of the programming languages such as C, C++, assembly languages, and so on. The instruction set commands are pre-determined for each and every function with its own command syntaxes and are executed by the PIC chip. PIC chips are normally use Reduced Instruction Set Programming that only contain 35 simple instruction sets that are much easier to learn by the programmer as compared to CISC instruction set. According to the type of instruction, the instruction sets can be classified into 5 groups. Here in this first section you can get the basics of computer programming by using various instruction sets The instruction sets in PIC is developed by the basis of RISC structure. The instruction sets can be classified into 5 separate categories (depends on the basis of type of operation). They are 1) DATA TRANSFER GROUP 2) ARITHMETIC AND LOGIC OPERATIONS GROUP 3) BIT OPERATION GROUP INSTRUCTIONS 4) PROGRAM FLOW CONTROL

Data Transfer Group Instructions in PIC

Data transfer group instructions are one of the major instructions widely used in PIC programming for data transfer purposes. By using these types of instructions, we can move or change the value (bits) from one location to another. Data Transfer Instructions with Syntaxes

1. MOVLW
MOVLW instruction is used to write constant in W register (move the value from literal to W register).

Syntax:

Label MOVLW k

Description:

8 bit constant is written in W reg.

Operation:

k to (W)

Operand:

0 < k < 255


No. of words: 1 No. cycles: 1 Flags: Nil

2. MOVWF
MOVWF instruction is used to move the data (bits) from W register to flag register F (copy/move the value from W register to F register).

Syntax:

Label MOVWF f

Description:

Content of W is copied into f register (flag register).

Operation:

W to (f) (W register to Flag register)

Operand:

0 < f < 127


No. of words: 1 No. cycles: 1 Flags: Nil

3. MOVF
MOVF command is used for copy/move the contents (bits) in the flag register to D register (Copy f to d register). D register (destination register) is a special register which can be switchable in its destination according to its status. If the status of D register is 0, the destination is W register and if the status is 1, the destination of D register became F register (flag)

Syntax:

Label MOVF f, d

Description:

Content of f is copied into destination. If d = 0, the destination is W register If d = 1, the destination is f register

Operation:

F to (D)

Operand:

0 < k < 127


No. of words: 1 No. cycles: 1 Flags: Z

4. CLRW

CLRW is a clearing instruction that helps to reset the values of W register to 0 (write 0 in W register).

Syntax:

Label CLRW

Description:

Zero is copied into W register Z flag in status register is set to one

Operation:

0 to (W)

Operand: nil No. of words: 1 No. cycles: 1 Flags: Z

5. CLRF f
CLRF f Write 0 in F register that helps to reset the current status to 0

Syntax:

Label CLRF f

Description:

Zero is copied into f register Z flag in status register is set to one

Operation:

0 to (f)

Operand: nil No. of words: 1 No. cycles: 1 Flags: Z

6. SWAPF

SWAPF used for swap (interchanging functions) functions which Swap the nibbles (4bits).The destination of this function depends on the destination register status.

Syntax:

Label SWAPF f, d

Description:

Upper, Lower nibbles are exchanged If d = 0, the destination is W register If d = 1, the destination is f register

Operation:

f (0:3) to d(4:7) and f(4:7) to d(0:3)

Operand:

0 < f < 127


No. of words: 1 No. cycles: 1 Flags:

ARITHMETICAL GROUP

AND

LOGICAL

OPERATIONS

In this article, the basic arithmetic and loguc operations that are carried out by a PIC is explained in detail. Arithmetic and logic operation group instructions are used for performing all arithmetic operations and logic operations. By using these types of instructions, the PIC chip can easily perform all arithmetic and logic operations inside the micro controller (PIC). The arithmetic operations are addition (ADD), subtraction (SUB), multiplication (MUL), division (DIV) and logical operations are AND, OR, NOT, XOR, and so on. The basic Arithmetical and Logical operations that are performed by a PIC is given below.

1) ADDLW
ADDLW instruction is used for performing addition operation (adding a constant with W register). By using this instruction, we can add two bits easily and the result value can be stored in another register or memory location.

Syntax: Label ADDLW k Description: Given constant is added with W reg. Operation: (w) + k to w Operand: 0 < k < 255 No. of words: 1 No. cycles: 1 Flags: C, DC, Z

2) ADDWF
ADDWF is also used for performing the addition operation. This ADDWF instruction adds the constant with W register.

Syntax: Label ADDWF f, d Description: Add W reg. content with f register Operation: (w) + (f) to w if d = 0 and (w) + (f) to f if d = 1 Operand: 0 < f < 127 No. of words: 1 No. cycles: 1 Flags: C, DC, Z

3) SUBLW
SUBLW used for performing subtraction function which can be subtracting two values and can be stored to another memory location. This instruction helps to Subtract W content from given constant.

Syntax: Label SUBLW k Description: W reg. content is subtracted from k Operation: k (w) to w Operand: 0 < k < 255 No. of words: 1 No. cycles: 1 Flags: C, DC, Z

4) SUBWF
SUBWF is used for performing subtraction operation. In SUBLW, this instruction Subtracts W content from f register.

Syntax: Label SUBWF f Description: W reg. content is subtracted from f Operation: f (w) to w if d = 0 and f (w) to f if d = 1 Operand: 0 < f < 127 No. of words: 1 No. cycles: 1 Flags: C, DC, Z

5) ANDLW
ANDLW is a logical instruction which used for performing Logic AND. By using this instruction helps AND the constant with W.

Syntax: Label ANDLW k Description: Given constant is .and. with W reg. Operation: (w) .and. k to w Operand: 0 < k < 255 No. of words: 1 No. cycles: 1 Flags: Z

6) IORLW
This command is used for performing logical OR operation. By using this instruction, it will perform Logical OR operation with W register.

Syntax: Label IORLW k Description: Given constant is .or. with W reg. Operation: (w) .or. k to w Operand: 0 < k < 255

No. of words: 1 No. cycles: 1 Flags: Z

7) IORWF
Logic OR the W reg. with f

Syntax: Label IORWF f, d Description: W reg. is .or. with f reg. Operation: (w) .and. f to w, if d = 0 and (w) .and. f to f, if d = 1 Operand: 0 < f < 127 No. of words: 1 No. cycles: 1 Flags: Z

8 ) XORLW
This command is used for performing logical XOR operation. By using this command, it will perform logical XOR with Logic constant and W register.

Syntax: Label XORLW k Description: Given constant is .XOR. with W reg. Operation: (w) .xor. k to w Operand: 0 < k < 255 No. of words: 1 No. cycles: 1 Flags: Z

9) XORWF
This command used to perform Logic XOR the W reg. with f

Syntax: Label XORWF f, d Description: W reg. is .xor. with f reg. Operation: (w) .and. f to w, if d = 0 and (w) .and. f to f, if d = 1

Operand: 0 < f < 127 No. of words: 1 No. cycles: 1 Flags: Z

10) INCF
INCF command used for performing increment operations.(Increment f registers content)

Syntax: Label INCF f, d Description: Increment the content of f register Operation: (f) + 1 to w, if d = 0 and (f) + 1 to f, if d = 1 Operand: 0 < f < 127 No. of words: 1 No. cycles: 1 Flags: Z

11) DECF
DECF command used for performing Decrement f register content

Syntax: Label DECF f, d Description: Decrement the content of f register Operation: (f) 1 to w, if d = 0 and (f) 1 to f, if d = 1 Operand: 0 < f < 127 No. of words: 1 No. cycles: 1 Flags: Z

12) RLF
RLF command is used for performing rotate register content left through Carry

Syntax: Label RLF f, d Description: Rotate f content left through Carry

Operation: Result to w, if d = 0 and Result to f, if d = 1 Operand: 0 < f < 127 No. of words: 1 No. cycles: 1 Flags: C

13) RRF
RRF command used for perform Rotate register content right through Carry

Syntax: Label RRF f, d Description: Rotate f content right through Carry Operation: Result to w, if d = 0 and Result to f, if d = 1 Operand: 0 < f < 127 No. of words: 1 No. cycles: 1 Flags: C

14) COMF
COMF command for perform Complement f registers content

Syntax: Label COMF f, d Description: Complement the register content Operation: Result to w, if d = 0 and Result to f, if d = 1 Operand: 0 < f < 127 No. of words: 1 No. cycles: 1 Flags: Z

Bit Operation Group


1) BCF

BCF is a resetting command instruction used for performing reset operations for a specified bit or specified register (simply called bit clearing flag or bit clearing command). Normally BCF resets the specified bit in f registers content.

Syntax: Label BCF f, b Description: Reset the specified bit of register f Operation: Result to f Operand: 0 < f < 127 and 0 < b < 7 No. of words: 1 No. cycles: 1 Flags: nil

2 ) BSF
BSF is the inversing operation of BCF. This is also a bitwise operation. The BSF instruction will set the specified bit in the f register (simply called Bit Set Flag or Bit Set command).

Syntax: Label BSF f, b Description: Set the specified bit of register f Operation: Result to f Operand: 0 < f < 127 and 0 < b < 7 No. of words: 1 No. cycles: 1 Flags: nil

PROGRAM FLOW CONTROL

1) BTFSC
BTFSC is a special type program flow instruction which control the current program flow. Normally BTFSC Test the bit in f, skip if it is zero.

Syntax: Label BTFSC f, b Description: Test the specified bit of register f, skip the next instruction if it is zero Operation: Skip the next instruction if f (b) = 0 Operand: 0 < f < 127 and 0 < b < 7 No. of words: 1 No. cycles: 1 or 2 depends on bit value Flags: NIL

2) BTFSS
BTFSS also program flow control instruction. This instruction Test the bit in f, skip if it is one

Syntax: Label BTFSS f, b Description: Test the specified bit of register f, skip the next instruction if it is one Operation: Skip the next instruction if f (b) = 1 Operand: 0 < f < 127 and 0 < b < 7 No. of words: 1 No. cycles: 1 or 2 depends on bit value Flags: nil

3) INCFSZ
INCFSZ is a content increment command which Increment f content, skip if it is zero

Syntax: Label INCFSZ f, d Description: Increment the f content, skip the next instruction if f is zero Operation: Skip the next instruction if f = zero Operand: (f) + 1 = w if d = 0 and (f) + 1 = f if d = 1 No. of words: 1 No. cycles: 1 or 2 depends on bit value Flags: nil

4) DECFSZ
DECFSZ command Decrement f content, skip if it is zero

Syntax: Label DECFSZ f, d Description: Decrement the f content, skip the next instruction if f is zero Operation: Skip the next instruction if f = zero Operand: (f) 1 = w if d = 0 and (f) 1 = f if d = 1 No. of words: 1 No. cycles: 1 or 2 depends on bit value Flags: nil

5) GOTO
GOTO instruction is used for Jump to specified address locations.

Syntax: Label GOTO Label Description: Unconditional jump to specified label Operation: k to PC(10:0), PCLATH(4:3) to PC(12:11) Operand: 0 < k < 2048 No. of words: 1 No. cycles: 2 Flags: nil

6) CALL

CALL command is used for Call the required sub-program or other values.

Syntax: Label CALL Label Description: Unconditional call the label Operation: (PC) + 1 to Top of stack, k to PC(10:0), PCLATH(4:3) to PC(12:11) Operand: 0 < k < 2048 No. of words: 1 No. cycles: 2 Flags: nil

7) RETURN
RETURN command is used for Return to main program from any other sub programs

Syntax: Label RETURN Description: Unconditional return from subroutine Operation: Top of stack to (PC) Operand: nil No. of words: 1 No. cycles: 2 Flags: nil

8 )RETLW
RETLW is also a return command. By using this command, Return to main program with k in w reg .

Syntax: Label RETLW k Description: Unconditional return from subroutine Operation: Top of stack to (PC) and k loaded in w register Operand: 0 < k < 255 No. of words: 1 No. cycles: 2 Flags: nil

9) RETFIE
RETFIE used to return from interrupt routine

Syntax: Label RETFIE Description: Unconditional return from subroutine Operation: Top of stack to (PC) and Global Interrupt bit is enabled Operand: nil No. of words: 1 No. cycles: 2 Flags: nil

Other Instructions in PIC


1) NOP

NOP command used for denoting No Operation


Syntax: Label NOP Description: No operation Operation: nil Operand: nil No. of words: 1 No. cycles: 1 Flags: nil

2)

CLRWDT

CLRWDT command used for Initialize watchdog time feature .


Syntax: Label CLRWDT Description: Watchdog timer and pre-scalar is reset and TO and PD are set Operation: 0 to WDT, 0 to pre-scalar and Status bits TO and PD are set Operand: TO and PD No. of words: 1 No. cycles: 1 Flags: nil

3)

SLEEP

SLEEP command used for initialize Standby mode.


Syntax: Label SLEEP Description: Goes into low consumption, OSC is stopped, Watchdog timer and prescalar is reset and TO and PD bits are set Operation: 0 to WDT, 0 to pre-scalar and Status bits, TO is set and PD is reset Operand: TO and PD No. of words: 1 No. cycles: 1 Flags: nil

PROGRANMMING IN PIC
1.To write a C program to perform the arithmetic operations addition, subtraction, multiplication, division in 8051.

ALGORITHM:

Step 1: Start the program. Step 2: Declare the header file. Step 3: Initializing port0 for addition and the output is stored in P0. Step 4: Initializing port1 for subtraction and the output is stored in P1. Step 5: Initializing port2 for multiplication and the output is stored in P2. Step 6: Initializing port3 for division and the output is stored in P3. Step 7: Stop the program.

PROGRAM:

#include <reg51.h> void main(void) { P0=0x35 + 0x0F; P1=0x04 - 0x68; P2=0x54 / 0x78; P3=0x55*0x10; } 2.To write a C program to convert hexadecimal number into a decimal number in 8051.

ALGORITHM:

Step 1: Start the program.

Step 2: Declare the header file. Step 3: Declare the variables. Step 4: perform division & modulus operations. Step 5: store the values in ports P0, P1, P2. Step 6: Stop the program.

PROGRAM:

#include <reg51.h> Unsigned char w, x, y, z; Unsigned char HD=0x96; void main() { w=HD/10; x=HD%10; y=w%10; z=w/10; P0=x; P1=y; P2=z } 3.To write a C program to perform the logical operations AND, OR, EX-OR and SHIFT operations in 8051. ALGORITHM: Step 1: Start the program. Step 2: Declare the header file.

Step 3: Initializing port0 for AND operation and the output is stored in P0. Step 4: Initializing port1 for OR operation and the output is stored in P1. Step 5: Initializing port2 for EX-OR operation and the output is stored in P2. Step 6: Giving an input in port0 and inverting it and storing the output in P0. Step 7: Giving an input in port1 and shifting it right three times and storing the output in P1. Step 8: Giving an input in port2 and shifting it right four times and storing the output in P2. Step 9: Giving an input in port0 and shifting it left four times and storing the output in P0. Step 10: Stop the program.

PROGRAM: #include <reg51.h> void main(void) { P0=0x35 & 0x0F; P1=0x04 | 0x68; P2=0x54 ^ 0x78; P0=~0x55; P1=0x9A >> 3; P2=0x77 >> 4; P0=0x6 << 4; } 4. To write a C program to perform the 2s complement operation in 8051.

ALGORITHM:

Step 1: Start the program. Step 2: Declare the header file. Step 3: declare the variable x. Step 4: perform ones complement and add one and store the result in P0. Step 5: Stop the program

PROGRAM:

#include <reg51.h> Unsigned char x=oxFE void main() { x=~x; x=x+1; P0=x; } RAM AND ROM ALLOCATION MEMORY
The PIC16F887 has three types of memory ROM, RAM and EEPROM. All of them will be separately discussed since each has specific functions, features and organization.

ROM MEMORY
ROM memory is used to permanently save the program being executed. This is why it is often called program memory. The PIC16F887 has 8Kb of ROM (in total of 8192 locations). Since the ROM memory is made with FLASH technology, its contents can be changed by providing a special programming voltage (13V).

However, it is not necessary to explain it in detail as being automatically performed by means of a special program on the PC and a simple electronic device called the programmer.

EEPROM MEMORY

Similar to program memory, the contents of EEPROM is permanently saved, even when the power goes off. However, unlike ROM, the contents of EEPROM can be changed during the operation of the microcontroller. This is why this memory (256 locations) is perfect for permanently saving some of the results created and used during the operation.

RAM MEMORY

This is the third and the most complex part of microcontroller memory. In this case, it consists of two parts: generalpurpose registers and special-function registers (SFR). All these registers are divided in four memory banks to be explained later in the chapter.

Even though both groups of registers are cleared when power goes off and even though they are manufactured in the same manner and act in a similar way, their functions do not have many things in common.

Timer
Many times, we plan and build systems that perform various processes that depend on time. Simple example of this process is the digital wristwatch. The role of this electronic system is to display time in a very precise manner and change the display every second (for seconds), every minute (for minutes) and so on. To perform the steps we've listed, the system must use a timer, which needs to be very accurate in order to take necessary actions.The clock is actually a core of any electronic system. In this PIC timer module tutorial we will study the existing PIC timer modules. The microcontroller PIC16F877 has 3 different timers:

PIC Timer0 PIC Timer1 PIC Timer2

We can use these timers for various important purposes. So far we used delay procedure to implement some delay in the program, that was counting up to a specific value, before the program could be continued. "Delay procedure" had two disadvantages:

we could not say exactly how long the Delay procedure was in progress we could not perform any further steps while the program executes the "delay procedure"

Now, using Timers we can build a very precise time delays which will be based on the system clock and allow us to achieve our desired time delay well-known in advance. In order for us to know how to work with these timers, we need to learn some things about each one of them. We will study each one separately.

PIC Timer0
The Timer0 module timer/counter has the following features:

8-bit timer/counter Readable and writable 8-bit software programmable prescaler Internal (4 Mhz) or external clock select Interrupt on overflow from FFh to 00h Edge select (rising or falling) for external clock

Lets explain the features of PIC Timer0 we have listed above: Timer0 has a register called TMR0 Register, which is 8 bits of size. We can write the desired value into the register which will be increment as the program progresses. Frequency varies depending on the Prescaler. Maximum value that can be assigned to this register is 255. TMR0IF - TMR0 Overflow Interrupt Flag bit. The TMR0 interrupt is generated when the TMR0 register overflows from FFh to 00h. This overflow sets bit TMR0IF (INTCON<2>). You can initialize the value of this register to what ever you want (not necessarily "0"). We can read the value of the register TMR0 and write into. We can reset its value at any given moment (write) or we can check if there is a certain numeric value that we need (read). Prescaler - Frequency divider. We can use Prescaler for further division of the system clock. The options are:

1:2 1:4 1:8 1:16 1:32 1:64 1:128 1:256

The structure of the OPTION_REG register

We perform all the necessary settings with OPTION_REG Register. The size of the register is 8 bits. Click the link to explore the relevant bits of OPTION_REG Register

Initializing the OPTION_REG register The following is an example how we can initialize the OPTION_REG: 1. 2. 3. 4. 5. 6. PSA=0; // Prescaler is assigned to the Timer0 module PS0=1; // Prescaler rate bits PS1=1; // are set to 111 PS2=1; // which means divide by 256 TOSE=0; // rising edge TOCS=0; // Internal instruction cycle clock

Block diagram of the PIC Timer0 / WDT prescaler

PIC TIMER0 block diagram Calculating Count, Fout, and TMR0 values If using INTERNAL crystal as clock, the division is performed as follow:

PIC TIMER0 formula for internal clock Fout The output frequency after the division. Tout The Cycle Time after the division. 4 - The division of the original clock (4 MHz) by 4, when using internal crystal as clock (and not external oscillator). Count - A numeric value to be placed to obtain the desired output frequency - Fout. (256 - TMR0) - The number of times in the timer will count based on the register TMR0. An example of INTERNAL crystal as clock Suppose we want to create a delay of 0.5 second in the our program using Timer0. What is the value of Count? Calculation: First, lets assume that the frequency division by the Prescaler will be 1:256. Second, lets set TMR0=0. Thus:

Formula to calculate Cout using Timer0 If using EXTERNAL clock source (oscillator), the division is performed as follow:

PIC TIMER0 formula for external clock

In this case there is no division by 4 of the original clock. We use the external frequency as it is. An example of EXTERNAL clock source (oscillator): What is the output frequency - Fout, when the external oscillator is 100kHz and Count=8? Calculation: First, lets assume that the frequency division by the Prescaler will be 1:256. Second, lets set TMR0=0. Thus:

Formula to calculate Fout for Timer0 Delay of 1 sec using Timer0 The following simple program creates a delay of 1 sec using Timer0:

PIC Timer1 tutorial


The Timer1 module, timer/counter, has the following features:

16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L) readable and writable 8-bit software programmable prescaler Internal (4 Mhz) or external clock select Interrupt on overflow from FFFFh to 0000h

Lets explain the features of PIC Timer1 we have listed above: Timer1 has a register called TMR1 register, which is 16 bits of size. Actually, the TMR1 consists of two 8-bits registers:

TMR1H TMR1L

It increments from 0000h to the maximum value of 0xFFFFh (or 0 b1111 1111 1111 1111 or 65,535 decimal). The TMR1 interrupt, if enabled, is generated on overflow which is latched in interrupt flag bit, TMR1IF (PIR1<0>). This interrupt can be enabled/disabled by setting/clearing TMR1 interrupt enable bit, TMR1IE (PIE1<0>). You can initialize the value of this register to what ever you want (not necessarily "0"). TMR1IF TMR1 overflow Interrupt Flag bit. This flag marks the end of ONE cycle count. The flag need to be reset in the software if you want to do another cycle count. We can read the value of the register TMR1 and write into. We can reset its value at any given moment (write) or we can check if there is a certain numeric value that we need (read). Prescaler Frequency divider. We can use Prescaler for further division of the system clock. The size of the register is 2-bit only, so you can make four different division. The options are:

1:1 1:2 1:4 1:8

You can choose whether to use an internal system clock (crystal) or external oscillator that can be connected to a pin RC0.

The structure of the T1CON register

We perform all the necessary settings with T1CON register. As we can see, the size of the register is 8 bits. Lets explore the relevant bits:

Initializing the T1CON register


The following is an example how we can initialize the T1CON register: 1. 2. 3. 4. TMR1ON=1; // the timer is enable TMR1CS=0; // internal clock source T1CKPS0=0; // Prescaler value set to 00 T1CKPS1=0; // which means 1:1 (no division)

Or you can set all the T1CON register at once as follows: T1CON=0b00000001; CLICK here for more information about PIC TIMER 1 Module

Block diagram of the PIC Timer1

PIC TIMER1 block diagram

Calculating Count, Fout, and Timer1 values

If using INTERNAL crystal as clock, the division is performed as follow:

PIC TIMER1 formula for internal clock Fout The output frequency after the division. Tout The Cycle Time after the division. 4 - The division of the original clock (4 MHz) by 4, when using internal crystal as clock (and not external oscillator). Count - A numeric value to be placed to obtain the desired output frequency - Fout. (256 - TMR1) - The number of times in the timer will count based on the register TMR0. If using EXTERNAL clock source (oscillator), the division is performed as follow:

PIC TIMER1 formula for external clock

Simple example and calculation of how to use TIMER1:


Suppose we want to create a delay of 2 second in the our program using Timer1. What is the value of Count? Calculation: First, lets assume that the frequency division by the Prescaler will be 1:1. Second, lets set TMR1=0, which means the TMR1 will count 65,536 times. Thus:

Formula to calculate Cout for Timer1

Delay of 1 sec using Timer1


The following simple program creates a delay of 1 sec using TIMER1:

#include<pic.h> int Count = 0; void main (void) { T1CON = 0b00000001; while (1) { while (! TMR1IF); TMR1IF = 0; Count ++; if (Count == 15) { Count = 0; } } }

PIC Timer2 tutorial


The Timer2 module, timer/counter, has the following features:

two 8-bit registers (TMR2 and PR2) readable and writable a prescaler and a postscaler connected only to an internal clock - 4 MHz crystal Interrupt on overflow

Lets explain the features of PIC Timer2 we have listed above: Timer2 has 2 count registers: TMR2 and PR2. The size of each registers is 8-bit in which we can write numbers from 0 to 255. The TMR2 register is readable and writable and is cleared on any device Reset. PR2 is a readable and writable register and initialized to FFh upon Reset. Register TMR2 is used to store the "initial" count value (the value from which it begins to count). Register PR2 is used to store the "ending" count value (the maximum value we need/want to reach). ie: using Timer2 we can determine the started count value, the final count value, and the count will be between these two values. The Timer2 increments from 00h until it matches PR2 and then resets to 00h on the next increment cycle. Prescaler and Postscaler - Timer2 is an 8-bit timer with a prescaler and a postscaler. Each allows to make additional division of the frequency clock source. Prescaler divides the frequency clock source BEFORE the counting take place at the register TMR2, thus the counting inside the TMR2 register is performed based on the divided frequency clock source by the Prescaler The match output of TMR2 goes through a 4-bit postscaler (which gives a 1:1 to 1:16 scaling inclusive) to generate a TMR2 interrupt (latched in flag bit, TMR2IF (PIR1<1>)). Postscaler divides the frequency that comes out of the Comparator again for the last time.

TIMER2 Prescaler and Postscaler

TMR2IF - TMR2 to PR2 Match Interrupt Flag bit. Comparator Compares the value of the register TMR2 and the maximum value of the register PR2. TMR2 The register in which the "initial" count value is written. PR2 The register in which the final or the maximum count value is written. We perform all the necessary settings with T2CON Register The structure of the T2CON register:

As we can see, the size of the register is 8 bits. Let's explore the relevant bits: T2CKPS1:T2CKPS0: Timer2 Clock Prescale Select bits The input clock (FOSC/4) has a prescale option of 1:1, 1:4 or 1:16, selected by control bits T2CKPS1:T2CKPS0 (T2CON<1:0>). 00 = Prescaler is 1 01 = Prescaler is 4 1x = Prescaler is 16

TMR2ON: Timer2 On bit Timer2 can be shut-off by clearing control bit, TMR2ON (T2CON<2>), to minimize power consumption. 1 = Timer2 is on 0 = Timer2 is off TOUTPS3:TOUTPS0: Timer2 Output Postscale Select bits The match output of TMR2 goes through a 4-bit postscaler (which gives a 1:1 to 1:16 scaling inclusive selected by control bits TOUTPS3:TOUTPS0 (T2CON<6:3>). 0000 = 1:1 postscale 0001 = 1:2 postscale 0010 = 1:3 postscale 1111 = 1:16 postscale The following is an example how we can initialize the T2CON register: 1. TMR2ON=1; // the timer is enable 2. T2CKPS0=0; // Prescaler 1:1 3. T2CKPS1=0; 4. TOUTPS0=1; // Postscaler 1:16 5. TOUTPS0=1; 6. TOUTPS0=1; 7. TOUTPS0=1; Or you can set all the T2CON register at once as follows: T2CON=0b01111100; CLICK here for more information about PIC TIMER 2 Module TIMER2 BLOCK DIAGRAM

How to calculate the required values of the TIMER2:

Fout The output frequency after the division. Tout The Cycle Time after the division. 4 - The division of the original clock (4 MHz) by 4, when using internal crystal as clock (and not external oscillator). Count - A numeric value to be placed to obtain the desired output frequency - fout. (PR2 TMR2) - The number of times the counter will count. Simple example and calculation of how to use TIMER2: Suppose we want to create a delay of 1 second in the our program using Timer2. What is the value of Count? Calculation: First, let's assume that the frequency division by the Prescaler will be 1:1 and Postscaler will be 1:16. Second, let's set TMR1=0 and PR2=255. Thus:

The following simple C language program creates a delay of 1 sec using TIMER2:

MP LAB MPLAB Integrated Development Environment (IDE) is a free, integrated toolset for the development of embedded applications on Microchip's PIC and dsPIC microcontrollers.

Versions
MPLAB IDE v8
The current version of MPLAB IDE is version 8.63. It is a 32-bit application on Microsoft Windows and includes several free software components for application development, hardware emulation and debugging. MPLAB IDE also serves as a single, unified graphical user interface for additional Microchip and third-party software and hardware development tools.

Both Assembly and C programming languages can be used with MPLAB IDE v8. Others may be supported through the use of third-party programs. Support for MPLAB IDE, along with sample code, tutorials, and drivers can be found on Microchip's website. MPLAB IDE v8 does not support Linux, Unix or Macintosh operating systems.

MPLAB X IDE
MPLAB X is not a new version of the current MPLAB IDE v8 framework but is instead based on Oracle's open-source NetBeans platform. In addition to its predecessor's functionalities and compatibility with Microchip's existing development tools, the new IDE utilises many NetBeans features allowing for user-interface improvements and performance upgrades. This also includes highly-anticipated cross-platform support in MPLAB IDE, allowing development for PIC microcontrollers on Mac OS X and Linux operating systems, in addition to Windows. This IDE also support the SDCC open source compiler on the three major OS: Mac, Linux and Windows. By using the MPLABX with SDCC one may be able to set up a complete free suite for programming Microchip PIC's in C language.

UNIT III Peripheral Of PIC Microcontroller


TIMER

Overview of Timer Modules : PIC 16C74A has three modules, viz., Timer-0, Timer-1 and Timer-2. Timer-0 and Timer-2 are 8-bit timers. Timer-1 is a 16-bit timer. Each timer module can generate an interrupt on timer overflow. Timer-0 Overview: The timer-0 module is a simple 8-bit UP counter. The clock source can be either the internal clock (fosc /4) or an external clock. When the clock source is external, the Timer-0 module can be programmed to increment on either the rising or falling clock edge. Timer-0 module has a programmable pre-scaler option. This prescaler can be assigned either to Timer-0 or the Watch dog timer, but not to both. The Timer-0 Counter sets a flag T0IF (Timer-0 Interrupt Flag) when it overflows and can cause an interrupt at that time if that interrupt source has been enabled, (T0IE = 1), i.e., timer-0 interrupt enable bit = 1. OPTION Register Configuration : Option Register (Addr: 81H) Controls the prescaler and Timer -0 clock source. The following OPTION register configuration is for clock source = fosc /4 and no Watchdog timer.

Timer-0 use without pre-scalar Internal clock source of f osc /4. (External clock source, if selected, can be applied at RA4/TOCKI input at PORTA). The following diagram shows the timer use without the prescaler.

Fig 20.1 Timer - 0 operation without prescaler Timer-0 use with pre-scalar: The pre-scalar can be used either with the Timer-0 module or with the Watchdog timer. The pre-scalar is available for Timer-0 if the pre-scalar assignment bit PSA in the OPTION register is 0. Pre-scalar is a programmable divide by n counter that divides the available clock by a pre-specified number before applying to the Timer-0 counter.

Fig 20.2 Timer - 0 with prescaler

Timer - 1 Module Timer 1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L) which are readable and writable. The TMR1 register pair (TMR1H:TMR1L) increments from 0000H to FFFFH and rolls over to 0000H. The TMR1 interrupt, if enabled, is generated on overflow, which sets the interrupt flag bit TMR1IF (bit-0 of PIR1 register). This interrupt can be enabled/disabled by setting/clearing TMR1 interrupt enable bit TMR1IE (bit-0 of the PIE1 register). The operating and control modes of Timer1 are determined by the special purpose register T1CON. Various bits of T1CON register are given as follows:-

Fig 21.1 T1CON Register TMR1 ON : Timer1 ON bit 0 = stops Timer 1; 1 = Enables Timer 1 TMR1CS : Timer 1 Clock source Select Bit 1 = External Clock (RCO/T1OSO/T1CKI) 0 = Internal Clock ( : ) Timer 1 External Clock Input Synchronization Bit (Valid if TMR1CS = 1) 1 - Do not synchronize 0 - Synchronize T1OSCEN: Oscillator enable control bit 1 = Oscillator is enabled 0 = Oscillator is shut off Timer 1 Input Clock Prescaler Select bits T1CKPS1 T1CKPS0 1 1 1 0 Prescaler Value 1:8 1:4

0 0

1 0

1:2 1:1

Fig 21.2

Operation of Timer 1

Timer 1 can operate in one of the two modes As a timer (TMR1CS = 0). In the timer mode, Timer 1 increments in every instruction cycle. The timer 1 clock source is . Since the internal clock is selected, the timer is always synchronized and there is no further need of synchronization. As a counter (TMR1CS = 1). In the counter mode, external clock input from the pin RCO/T1CKI is selected.

Reading and writing Timer 1 Reading TMR1H and TMR1L from Timer 1, when it is running from an external clock source, have to be done with care. Reading TMR1H or TMR1L for independent 8 - bit values does not pose any problem. When the 16-bit value of the Timer is required, the high byte (TMR1H) is read first followed by the low byte (THR1lL). It should be ensured that TMR1L does not overflow (that is goes from FFH to 00H) since THR1H was read. This condition is verified by reading TMR1H once again and comparing with previous value of TMR1H. Example Program Reading 16bit of free running Timer 1 movf TMR1H ; read high byte movwf TMPH ; store in TMPH movf TMR1L ; read low byte movwf TMPL ; store in TMPL movf TMR1H, W ; read high byte in W subwf TMPH, W ; subtract 1 st read with 2 nd read btfsc STATUS, Z ; and check for equality goto next ; ; if the high bytes differ, then there is an overflow

; read the high byte again followed by the low byte movf TMR1H, W ; read high byte movwf TMPH movf TMR1L, W ; read low byte movwf TMPL next : nop Timer 2 Overview

Fig 21.3 Schematic diagram showing operation of Timer 2 Timer 2 is an 8 - bit timer with a pre-scaler and a post-scaler. It can be used as the PWM time base for PWM mode of capture compare PWM (CCP) modules. The TMR2 register is readable and writable and is cleared on device reset. The input clock ( ) has a pre-scaler option of 1:1, 1:4 or 1:16 which is selected by bit 0 and bit 1 of T2CON register respectively. The Timer 2 module has an 8bit period register (PR2). Timer-2 increments from 00H until it is equal to PR2 and then resets to 00H on the next clock cycle. PR2 is a readable and writable register. PR2 is initailised to FFH on reset. The output of TMR2 goes through a 4bit post-scaler (1:1, 1:2, to 1:16) to generate a TMR2 interrupt by setting TMR2IF.

Fig 21.4 The T2CON Register Interrupt Logic in PIC 16C74A PIC 16C74A microcontroller has one vectored interrupt location (i.e., 0004H) but has 12 interrupt sources. There is no interrupt priority. Only one interrupt is served at a time. However interrupts can be masked. The interrupt logic is shown below :

Fig 21.5 Schematic diagram showing the interrupt logic for PIC

Capture / Compare /PWM (CCP) :

PIC16C74A has two CCP Modules. Each CCP module contains a 16 bit register (two 8-bit registers) and can operate in one of the three modes, viz., 16-bit capture, 16-bit compare, or up to 10-bit Pulse Width Modulation (PWM). The details of the two modules (CCP1 and CCp2) are given as follows. CCP1 Module: CCP1 Module consists of two 8-bit registers, viz., CCPR1L (low byte) and CCPR1H (high byte). The CCP1CON register controls the operation of CCP1 Module. CCP2 Module: CCP2 Module consists of two 8 bit registers, viz., CCPR2L (Low byte) and CCPR2H (high byte). The CCP1CON register controls the operation of CCP2 Module. Both CCP1 and CCP2 modules are identical in operation with the exception of the operation of special event trigger. The following table shows the timer resources for the CCP Mode. CCP Mode Timer Used Capture Timer 1 Compare Timer 1

PWM Timer 2 CCP1CON Register (Address 17H ) CCP2CON Register is exactly similar to CCP1CON register. CCP2CON Register address is 1DH. CCP1CON controls CCP module1 where as CCP2CON controls CCP Module2.

Bit 5-4: CCP1X CCP1Y: PWM least significant bits. These bits are of no use in Capture mode. In PWM Mode, these bits are the two Lsbs of the PWM duty cycle. The eight Msbs are found in CCPR1L. Thus the PWM mode operates in 10-bit mode. Bit 3-0: CCP1M3:CCP1MO (CCP1 Mode select bits) 0000=Capture/Compare/PWM Mode off 0100=Capture mode, every falling edge 0101=Capture mode, every rising edge 0110=Capture mode, every 4 th rising edge 0111=Capture mode, every 16 th rising edge 1000=Compare mode, set output on match (CCP1IF bit is set) 1001=Compare mode, clear output on match (CCP1IF bit is set) 1010=Compare mode, generate software interrupt on match (CCP1IF bit is set, CCP1 pin unaffected)

1011=Compare mode, trigger special event (CCP1IF bit is set;CCP1 resets Tmr1; CCP2 resets TMR1 and starts A/D conversion if A/D module is Enabled) 11XX=PWM mode. Capture Mode (CCP1): Capture Mode captures the 16-bit value of TMR1 into CCPR1H:CCPR1L register pair in response to an event occurring on RC2/CCP1 pin. Capture Mode for CCP2 is exactly similar to that of CCP1. An event on RC2/CCP1 pin is defined as follows: Every falling edge Every rising edge. Every 4 th rising edge. Every 16 th rising edge. As mentioned earlier, this event is decided by bit 3-0 of CCP1CON register. Schematic diagram for capture mode of operation

Fig 22.1 Capture operation Required condition for capture mode: 1. RC2/CCP1 pin should be configured as an input by setting TRISC (bit 2). 2. Timer 1 should be operated from the internal clock (fosc/4), i.e., timer mode or in synchronized counter mode. Compare Mode (CCP1) Compare mode for CCP2 is similar to that of CCP1, except that in special event trigger mode, CCP1 resets TMR1 only, whereas CCP2 resets TMR1 and starts A/D conversion if A/D module is enabled. In compare mode, the 16-bit CCPR1 register value is compared against TMR1 register pair (TMR1H and TMR1L) value. When a match occurs, the RC2/CCP1 pin is driven high or driven low or remains unchanged as decided by CCP1CON<3:0> bits.

Fig 22.2 Compare Operation Required conditions for compare mode 1. RC2/CCP1 pin must be configured as an output by clearing TRISC<2> bit. 2. Timer-1 should be operated in timer mode (i.e., internal clock source of fosc/4) or in synchronized counter mode. In software interrupt mode, CCP1IF bit is set but CCP1 pin in unaffected. As shown in the figure, in special event trigger mode, both CCP1 and CCP2 intiates an A/D conversion. PWM mode (CCP1) Both CCP1 and CCP2 have similar operation in PWM mode. Here we will discuss PWM with respect to CCP1. In PWM mode, the CCP1 pin produces upto a 10-bit resolution Pulse Width Modulation (PWM) output. RC2/CCP1 pin should be configured in the uotput mode by clearing TRISC<2> bit. The schematic block diagram of CCP1 module in PWM mode is shown in the figure.

Fig 22.3 PWM Operation It can be noted that PR2 (Period Register, 8 bit) decides the PWM period where CCPR1L (8-bits) and CCP1CON <5:4> (2-bits) decide the PWM duty cycle. When TMR2 equals PR2, the SR latch is set and RC2/CCP1 pin is pulled high. In the same time, TMR2 is cleared and the duty cycle value available in CCPR1L is latched to CCPR1H. CCPR1H, CCP1CON <5:4> decide the duty cycle and when this 10-bit ewquals the TMR2+2 prescaler or Q-bits, the SR latch is set and RC2/CCP1 pin is driven low.

A PWM output as shown has a time period. The time for which the output stays high is called duty cycle. PWM Period The PWM period is specified by writing to PR2 register. The PWM period can be calculated using the following formula: PWM period = [( PR 2) + 1] 4 T osc (TMR2 prescale value) PWM frequency = 1/ PWM period When TMR2 is equal to PR2, the following events occur on the next increment cycle. TMR2 is cleared the CCP1 pin is set (if PWM duty cycle is 0 The PWM duty cycle is latched from CCPR1L into CCPR1H PWM duty cycle The PWM duty cycle is specified by writing to the CCPR1L register and to CCP1CON < 5 : 4 > bits. Up to 10-bit resolution is available where CCPR1L contains the eight MSBs and CCP1CON < 5 : 4 > contains the two LSB's. The 10-bit value is represented by CCPR1L : CCP1CON < 5 : 4 >. The PWM duty cycle is given by PWM duty cycle = (CCPR1L : CCP1CON < 5 : 4 > ). T osc . (TMR2 prescale value) To understand the 10-bit counter configuration from Timer-2, let us first see the counting mechanism of Timer-2, as shown in Fig 22.4.

Fig 22.4 Counting mechanism in Timer - 2 If the prescaler is 1, the 10-bit counter is configured as follows

Fig 22.5 Prescaler set to divide by one If the prescaler is 4, the 10-bit counter is configured as follows.

Fig 22.6 Prescaler programed to divide by four If the prescaler is 16, the 10-bit counter is realized as follows.

Fig 22.7 Prescaler programed to divide by 16 Although CCPR1L and CCP1CON < 5 : 4 > can be written to at anytime, the duty cycle value is not latched into CCPR1H until a match between PR2 and TMR2 occurs. In PWM mode, CCPR1H is a read-only register. The CCPR1H register and a 2-bit internal latch are used to double buffer the PWM duty cycle. This double buffering is essential for glitchless PWM operation. When the CCPR1H and 2-bit latch match TMR2 concatenated with an internal 2-bit Q clock or 2-bits of prescaler, the CCP1 pin is cleared. Maximum PWM resolution (bits) for a given PWM frequency can be calculated as

If the PWM duty cycle is longer than the PWM period, then the CCP1 pin will not be cleared. PWM Period and duty cycle calculation Example: Desired PWM frequency = 78.125 kHz f osc = 20MHz TMR2 Prescalar = 1

Find the maximum resolution of duty cycle that can be used with a 78.124 kHz frequency and 20 MHz oscillator.

256 = 2PWM Resolution At most, an 8-bit resolution duty cycle can be obtained from a 78.125 kHz frequency and 20 MHz oscillator ie, 0 CCPR1L : CCP1CON <5 : 4> 255 . Any value greater than 255 will result in a 100 % duty cycle. The following table gives the PWM frequency fPWM if fosc = 20MHz Duty cycle resolution 10-Bit counter scale PR2 value Prescaler 1 Prescaler 4 Prescaler 16 10 bit 10 bit 8 bit 6 bit 1024 1000 256 64 255 249 63 15 19.53 KHz 20kHz 4.88 kHz 5kHz 1.22 kHz 1.25kHz 4.88kHz 19.53kHz

78.125kHz 19.53kHz 312.5kHz 78.125kHz

ADC
An analog-to-digital converter (ADC) converts an analog signal into an equivalent digital number. PIC 16C74A has an inbuilt ADC with the following features 8-bit conversion 8 analog input channels An analog multiplexer A sample and hold circuit for signal on the selected input channel Alternative clock sources for carrying out conversion Adjustable sampling rate Choice of an internal or external reference voltage Interrupt to microcontroller on end of conversion Port A and Port E pins are used for analog inputs/reference voltage for ADC. In A/D conversion, the input analog voltage is digitized and an equivalent digital output is generated as shown in the figure.

Fig 23.1 Digital output versus analog input Port-A pins (Alternate functions) RA0/AN0 can be used as analog input-0 RA1/AN1 can be used as analog input-1 RA2/AN2 can be used as analog input-2 RA3/AN3/Vref can be used as analog input-3 or analog reference voltage RA4/TOCKI clock input to Timer-0 RA5/ /AN4 can be used for analog input 4 or slave select for the synchronized serial port. Port-E pins (Alternate functions) RE0/ /AN5 - can be used as analog input-5 RE1/ /AN6 - can be used as analog input-6 RE2/ /AN7 - can be used as analog input-7 PIC microcontroller has internal sample and hold circuit. The input signal should be stable across the capacitor before the conversion is initiated.

Fig 23.2 Sample and Hold Circuit After waiting for the sampling time, a conversion can be initiated. The ADC Circuit will open the sampling switch and carry out the conversion of the input voltage as it was at the moment of opening of the switch. Upon completion of the conversion, the sampling switch is again closed and VHold once again tracks VSource.

Using the A/D Converter Registers ADCON1, TRISA, and TRISE must be initialized to select the reference voltage and input channels. The first step selects the ADC clock from among the four choices (fosc/2, fosc/8, fosc/32, and RC). The constraint for selcting clock frequency is that the ADC clock period must be 1.6micro seconds or greater. The A/D module has 3registers. These registers are: A/D result register (ADRES) A/D control register 0 (ADCON 0) A/D control register 1 (ADCON 1) The ADCON0 register, which is shown below, controls the operation of A/D module.

Fig 23.3 ADCON0 register Bit 7-6 - A/D Clock select bits ADCS1:ADCS0 00 = fosc/2 01 = fosc/8 10 = fosc/32 11 = fRC- clock derived from an internal RC oscillator Bit 5-3 - A/D Channel Select CHS2:CHS0 000 - Channel 0 - AN0 001 - Channel 1 - AN1 010 - Channel 2 - AN2 011 - Channel 3 - AN3 100 - Channel 4 - AN4 101 - Channel 5 - AN5 110 - Channel 6 - AN6 111 - Channel 7 - AN7 Bit 2 - A/D conversion status bit GO / if A/D Converter is enabled (ie. ADON = 1) then If GO / = 1, A/D conversion is in progress (setting this bit starts A/D conversion) If GO / = 0, A/D conversion is not in progress (This bit is automatically cleared by hardware when A/D conversion is complete) Bit1 - Unimplemented Bit 0 - ADON: A/D On bit 1. A/D Converter module is ON 2. A/D Converter module is OFF ADCON1 Register

This register specifies the analog inputs

Fig 23.4 ADCON1 register PCFG2:PCFG0 000 001 010 011 100 101 11X A = Analog input D = Digital I/O RA0 A A A A A A D RA1 A A A A A A D RA2 A A A A D D D RA5 A A A A D D D RA3 A VREF A VREF A VREF D RE0 A A D D D D D RE1 A A D D D D D RE2 A A D D D D D VREF VDD RA3 VDD RA3 VDD RA3 -

Fig 23.5 PCFG2:PCFG0 = A/D Port configuration control bits

Fig 23.6 Schematic diagram of A/D convertor analog inputs and reference voltage Steps for A/D conversion 1. Configure A/D module Configure analog inputs/voltage reference and digital I/O (ADCON1) Select A/D Channel (ADCON0) Select A/D Conversion Clock (ADCON0) Turn on A/D Module (ADCON0) 2. Configure A/D Interrupt (Optional)

Clear ADIF bit in PIR1 register Set ADIE bit in PIE1 register Set GIE bit 3. Wait for required acquisition time 4. Start Conversion - set GO/ bit (ADCON0) 5. Wait for A/D conversion to complete, by either polling GO/ interrupt 6. Read A/D result registers (ADRES). Clear ADIF if required. bit or by waiting for the A/D

Example Program A/D conversion with interrupt org 000H goto Mainline org 020H bsf STATUS, RP0 ; Select Bank 1 clrf ADCON 1 ; Configure A/D inputs bsf PIE1, ADIE ; Enable A/D interrupt bcf STATUS, RP0 ; Select Bank 0 movlw 081H ; Select fosc/32, channel 0, A/D on movwf ADCON0 bcf PIR1, ADIF bsf INTCON, PEIE ; Enable peripheral and global interrupt bits bsf INTCON, GIE ; interrupt bits ; Ensure that the required sampling time of the selected input channel has been elapsed. ; Then conversion may be started. ; bsf ADCON0, GO ; Start A/D conversion. ; ADIF bit will be set and GO/ ; bit is cleared upon completion of A/D conversion. Interrupt Service Routine Org 004H Movf ADRES, W ; Result of A/D conversion in W Consideration of Sampling Time When a channel is selected (writing to ADCON0), the switch 'SW' in Fig 23.8 is closed, changing CHOLD to VSource . When A/D conversion is started (setting Go bit in ADCON0), SW is opened. The time from the closure of 'SW' till the voltage across CHOLD (Vo) reaches VSource is the minimum sampling time Ts . The actual sampling time can be higher than Ts . The graph between Ts and source resistance RSource is shown in Fig 23.7.+

Fig 23.7 Relation between sampling time and source resistance

Fig 23.8 Sampling circuit in the PIC C Rss is the resistance of the sampling switch 'SW' and CHold is the charge holding capacitance. CHold is nearly 50pF. RSource is the impedance of the external analog source Vsource. Once the switch 'SW' is closed, the capacitor Chold takes some time to charge up. This time it is called the sampling time (Ts). This time varies linearly with RSource as shown. The recommended value of impedance of the external analog source, Vsource, is less than 10k. The circuit in Fig 23.8 is a first order RC circuit. When SW is closed, Vo varies as shown in Fig 23.9.

Fig 23.9 From Fig 23.9, Ts = 5 = 5 ( Rsource + Rss) CHOLD = 5 Rss CHOLD + 5 Rsource CHOLD Hence sampling time Ts varies linearly with RSource as shown

Most of mid range PIC microcontrollers include a Synchronous Serial Port (SSP) Module. The discussion in this section is relevant to PIC16C74A only. SSP Module section can be configured in either of the following two modes.

Serial Peripheral Interface (SPI) Inter Integrated Circuit (I2C)

Either of these modes can be used to interconnect two or more PIC chips to each other using a minimal number of wires for communication. Alternatively, either can be used to connect a PIC microcontroller to a peripheral chip. When I 2C mode is selected, the peripheral chip must also have an I 2C interface. On the other hand, the SPI mode provides the clock and serial data lines for direct connection to shift registers. This leads to increased I/O interface capability and an arbitrary number of I/O devices can be connected to a PIC microcontroller. SPI can also achieve data rate significantly higher than I2C. Both the communication methods are synchronous, i.e., the data transfer is synchronized with an explicit clock signal. Two special purpose registers control the synchronous serial port (SSP) operations. These registers are: SSPCON (Synchronous Serial Port Control Register), Address: 14H SSPSTAT(Synchronous Serial Port status Register), Address: 94H Serial Peripheral Interface (SPI) Port-C three pins, viz., RC5/SDO, RC4/SDI and RC3/SCK/SCL are mainly used for SPI mode. In addition, one Port-A pin, viz., RA5/ /AN4 is used for slave select. The schematic block diagram of SPI is shown in the figure

Fig 24.1 Schematic diagram under SPI Mode The SPI port requires RC3/SCK pin to be an output that generates the clock signal used by the external shift registers. When SPI is configured in the slave mode, RC3/SCK pin works as the input for the clock. When a byte is written to SSPBUF register, it is shifted out of RC5/SDO pin in synchronous with the emitted clock pulses on RC3/SCK pin. The MSB of SSPBUF is the first bit to appear on RC5/SDO pin. Simultaneously, the same write to SSPBUF also initiates the 8 bit data reception into SSPBUF of whatever

appears on RC4/SDI pin at the time of rising edges of the clock on SCK pin. Hence shifting-in and shiftingout of data occur simultaneously.

Fig 24.2 SPI Master / Slave Connection The schematic diagram of SPI Master/Slave connection is shown in the figure. Timing diagram for data transfer in 'Master mode' : SSPIF interrupt flag is cleared by the user software if already in the set mode. The interrupt is enabled. Any write to SSPBUF initiates the data transfer, i.e., transmission and reception. The clock pulses (8 clock pulses) are output through SCK pin. The data is received through SDI. When CKP=1 (SSPCON<4>), data changes at SDO at negative clock transition and is read through SDI at positive clock transition. The idle state of clock is high. If CKP=0, data appears at SDO at positive clock transition and is read through SDI at negative clock transition. The idle state of the clock is low. These are shown in the following diagrams.

(i) Timing diagram for CKP=1

(ii) Timing diagram for CKP=0 Fig 24.3 Timing Diagram under SPI mode

hough SPI is a serial communication interface, it can be used to realize multiple output parallel ports and multiple input parallel ports. We will consider this realization of an output parallel port and an input port separately. Parallel Output Port Realization

A parallel 8-bit output port can be realized through SPI with the help of a shift register chip (74HC595) as shown in Fig 25.1. RC5/SD0 pin outputs serial data while RC3/SCK oin outputs the serial clock. Since input data transfer is not required, port pin RC4/SDI is used to latch the shift register data to the output pins of the shift register. Hence RC4 is configured as an output pin.

Fig 25.1 PIC connection (in SPI mode) with a shift register When an 8-bit data is written to SSPBUF, the data is shifted out of RC5/SD0 pin. With CKP = 1, the data is stable at the positive transition but changes at the negative transition. The shift shifts the data at the positive clock transition. After 8 clock pulses, all 8-bits are shifted in the shift register. The completion of data transfer is indicated by SSPIF interrupt flag becoming ' 1' . The interrupt service routine make RC4 ' 1' , thus latching the 8-bit data to the output of the shift register. The configuration of various registers are shown in Fig 25.2 Port configurations

Fig 25.2 Various Register Configurations Parallel Input Port Realization A shift register (74HC165) is connected to the PIC microcontroller as shown in Fig 25.3. Pin RD7 is configured as an output and is used to load 8-bit data to the shift register. A dummy write to SSPBUF initiates data transfer. Data bit is read into RC4/SDI at the negative clock transition (CKP = 0) where the data bit is stable. Data is shifted in the shift register at the position clock transition as shown in the timing diagram. After the completion of data transfer, SSPIF interrupt flag goes high. Therafter the 8-bit data can be read by reading SSPBUF.

Fig 25.3 Realization of an 8-bit parallel input port with PIC in SPI mode. Port configurations Fig 25.4 gives the configurations various registers for inputs parallel port realization.

Fig 25.4 Configurations of various registers for parallel input port

I2C Communication in PIC Microcontroller I 2C stands for Inter-Integrated circuit. I 2C communication is a two wire bi-directional interface for connecting one or more master processors with one or more slave devices, such as an EEPROM, ADC, RAM, LCD display, DAC, etc. I 2C interface requires two open drain I/O pins, viz. SDA (Serial Data) and SCL (Serial Clock). The reason for open drain connection is that the data transfer is bi-directional and any of the devices connected to the I 2C bus can drive the data line (SDA). The serial clock line (SCL) is usually driven by the master. Since SDA and SCL pins are open drain pins, external pull-up resistances are required for operation of I 2C bus. A typical I2C bus showing the connection of multi-master and multi-slave configuration is shown in the following figure.

Fig 26.1 Multimaster Multislave Connection Some conventions are followed in I2C communication. Let us assume that there is one master and one slave and 8-data bits are sent. We will initially assume that the master is the transmitter and the slave is the receiver. The clock is driven by the master. On receiving 8-bits, an acknowledgement bit is driven by the receiver on SDA line. The acknowledgement bit is usually Low (0). The following diagram shows the data communication pattern having 8 data bits and one acknowledgement bit.

Fig 26.2 Timing diagram for data transfer The following features are to be noted 1. SDA line transmits/ receives data bits. MSB is sent first. 2. Data in SDA line is stable during clock (SCL) high. A new bit is initiated at the negative clock transition after a specified hold time. 3. Serial clock (SCL) is driven by the master. 4. An acknowledgement bit (0) is driven by the receiver after the end of reception. If the receiver does not acknowledge, SDA line remains high (1). I2C bus transfer consists of a number of byte transfers within a START condition and either another START condition or a STOP condition. During the idle state when no data transfer is taking place, both SDA and SCL lines are released by all the devices and remains high. When a master wants to initiate a data transfer, it pulls SDA low followed by SCL being pulled low. This is called START condition. Similarly, when the processor wants to terminate the data transfer it first releases SCL (SCL becomes high) and then SDA. This is called a STOP condition. START and STOP conditions are shown in the diagram as follows.

Fig 26.3 Timing diagram for START and STOP Conditions START and STOP conditions are unique and they never happen within a data transfer. Data Communication Protocol: In I2C communication both 7-bit and 10-bit slave addressing are possible. In 7-bit addressing mode 128 slaves can be interfaced with a single master. Similarly, in 10-bit addressing mode, 1024 slaves can be interfaced with the master. We will discuss here 7-bit addressing mode only. 10-bit addressing mode is similar to 7-bit addressing except from the fact that the number of address bits is more. Following a 'start' condition, the master sends a 7-bit address of the slave on SDA line. The MSB is sent first. After sending 7-bit address of the slave peripheral, a R/ (8th bit) bit is sent by the master. If R/ bit is '0', the following byte (after the acknowledgement bit) is written by the master to the addressed slave peripheral. If R/ =1, the following byte (after the acknowledgement bit) has to be read from the slave by the master. After sending the 7-bit address of the slave, the master sends the address (usually 8 bit) of the internal register of the slave wherefrom the data has to be read or written to. The subsequent access is automatically directed to the next address of the internal register. The following diagrams give the general format to write and read from several peripheral internal registers.

Fig 26.4 Data transfer protocol for writing to a slave device R/ (Read / Write) bit indicates whether the data is to be written by the master or read by the master. If R/ is 1, the subsequent data are to be read by the master. If R/ = 0, the subsequent data are to be written by the master to the addressed slave. It has to be noted that the slave address is sent first, following a 'start' condition. The addressed slave responds by acknowledging and gets ready for data transfer. If data has to be read from a specific address of the slave device, the master sends the 7-bit address of the slave first following a 'start' condition. R/ bit is sent as 'low'. The addressed slave acknowledges by pulling the ACK line low. The master then sends the 8-bit internal address of the slave from which data has to be read. The slave acknowledges. Since R/ bit was initially 0, the master is in the write mode. To change this to read mode, the 'start' condition is again generated followed by 7-bit address of the slave with R/ = 1. The slave acknowledges. The slave then sends data from previously specified internal address to the master. The master acknowledges by pulling ACK bit low. The data transfer stops when the master does not acknowledge the data reception and a 'stop' condition is generated.

UNIT IV LCD INTERFACING Liquid Crystal Display (LCD-Displaytech 162A ) LCD Displaytech 162A consists of a LCD panel, a controller IC (KS0070B) and a back light LED. The LCD module consists of total 16 pins in which, 2 are for power supply, 2 pins for Backlight LED, one pin for contrast adjustment, 3 pins are for control signals and 8 pins are data pins. In order to display any data, we need to do certain initiations. The following are the main three steps in displaying any data in the LCD display. 1. Initializing LCD by sequence of instructions 2. Executing commands depending on our settings in the LCD 3. Writing data into the DRAM locations of LCD in the Standard Character Pattern of LCD For doing above steps, refer the manual for LCD and follow the instructions and timing diagrams strictly. MPLABIDE MPLABIDE is a free software which can be downloaded from the website www.microchip.com Working with MPLABIDE : MPLABIDE is a simulator for PIC microcontrollers to write and edit the code in assembly language, compile it and also to run the code. Output can be verified using simulator. Steps to Use MPLABIDE After Installing the software MPLABIDEv7.2,open MPLABIDE. To built a new project, open Project Project Wizard Project wizard New Device 16F877 Location (Ex:C:\ProgramFiles\Microchip\MPASM Suite\MPASMWIN.EXE) Next <Project name>&<Project Directory> Next (Add file "f877tmpo.asm" which was located in programfiles microchip MPASMSuite Template Object) (Add file "16f877.lkr" which was located in programfiles microchip MPASMSuite LKR) Next Finish To have more clear refer to MPLABIDE help files. After building the project open the editor f877tmpo.asm and write the assembly code After writing the assembly code in the editor, build the project by clicking on the following option Project Build all Check for the errors in the output window View Output Once the error free code was made, simulate the code by following option Debugger Select Tool MPLAB SIM Simulator options are 1. Step into - Each time only one instruction will be executed (Single stepping mode)

2. Run - To run the whole code at once. 3. Animate - to animate the executing the code Additional things: 1. To view DRAM, program memory, SFRs, and External memory use the option VIEW 2. To set break points in the code (where simulation stops at that point). Debugger Breakpoints To stop the simulation Debugger Halt

After checking the code in the simulator, the code (file with .HEX extension) is loaded into 16F877 microcontroller using PIC BURNER 3. PIC BURNER3 PIC BURNER3 can be used to program PIC microcontrollers. The steps to be followed to program the IC safely are as follows. 1. Connect the PIC BURNER3 through RS232 Port to computer system with windows98 as operating system. 2. Execute the file "icprog" which was in the software that comes with PIC BURNER3. 3. Set the device as PIC16F877 4. Switch on the power supply of PIC BURNER3 5. Settings Hardware { JDM Programmer,Com1,Direct I/O} 6. Settings Hardware check 1. on clicking "Enable Data out", Data in must be clicked automatically 2. on clicking Enable MCLR, red LED on the PICBURNER3 must glow 7. Settings Options Confirmation [ Erasing the devise,Code Protecting the Devise] 8. Settings Options MISC Process Priority Normal 9. Settings Options Programming Verify After Programming. 10. Remaining options keep them at default settings. [Refer Manual of PICBURNER3 for detail] 11. Now insert the 16F877 microcontroller into the slot provided on the PICBURNER3 as the direction specified in the manual of PICBURNER3. 12. load the .hex file File open file 13. Command Erase All 14. Command Blank Check Then there should be a notice on the window that "Device is Blank " 15. Command Program All 16. Command Blank Check Then there should be a notice on the window that "Device is not blank at address 0x0000H". 17. Close the window, remove the IC from the PIC BURNER3 and switch off the power supply for PIC BURNER3.

Assembly Code

Circuit Diagram

Fig 43.2 Circuit Diagram

Fig 43.3 Circuit assembly on breadboard KEYPAD INTERFACE Keypad is an array of 4x4 keys with each key being a switch. The four rows are connected to pins 0-3 of Port1 and the four columns to pins 4-7 of Port1 as shown in the figure below. Each column is also connected to supply voltage through a pull up resistor (around 1k Ohms). To read a particular key, the corresponding row is driven to '0'. In a key is pressed and the corresponding row is driven '0' then current flows through the corresponding pull up resistor and the corresponding column reads '0'. Otherwise the corresponding column reads '1' (open circuit). For example if Key 5 is pressed R1 = 0, C1:C4 = 1111 R2 = 0, C1:C4 = 1011

Fig 42.1 Keypad schematic Procedure 1. Write the assembly code in Win8051. Compile and simulate it. 2. Once the code is error free, run it and check output with the Simulator 3. After checking the code in the simulator, the code (file with .HEX extension) is loaded into Atmel 89C51 microcontroller using Universal SP3 Programmer. 4. Now connections are made as shown in the circuit diagram. 5. Switch on the supply and push Reset button 6. Observe the results 7. Switch off the supply Assembly Code

Observation Microcontroller takes few microseconds to scan all 16 keys on the keypad whereas human response is of the order of milliseconds. Hence contact time of a key is long enough for it to be scanned by the microcontroller. Circuit Diagram

Fig 42.2 Circuit diagram for keypad interfacing MEASUREMENT OF FREQUENCY

Introduction:

A frequency counter is an electronic instrument, or component of one, that is used for measuring frequency. Frequency is defined as the number of events of a particular sort occurring in a set period of time. Frequency counters usually measure the number of oscillations or pulses per second in a repetitive electronic signal.

The Schematic Diagram:


Most frequency counters work by using a counter which accumulates the number of events occurring within a specific period of time (In this project, I used the counter of Timer1) . After a preset period (1 second, for example), the value in the counter is transferred to a display and the counter is reset to zero.

Fig.(2): Freq. Count. Circuit Diagram

If the event being measured repeats itself with sufficient stability and the frequency is considerably lower than that of the clock oscillator being used, the resolution of the measurement can be greatly improved by measuring the time required for an entire number of cycles, rather than counting the number of entire cycles observed for a pre-set duration (you can use CCP1/Cature to do that).

Source Code:

C Source Code /*************************************/ /* Project: Frequency Counter */ /* Copyright@ Abdullah M. Abdul-Hadi */ /* Date: 12-May-2011 */ /* www.pic-tronics.com */ /*********************************/ #include <16f877a.h> #use delay(clock=20M) #include <lcd420.c> #include <LCD_D.h> #fuses hs,nowdt,nocpd,nolvp,noprotect #byte portc=0x07 #bit led=portc.4 void LCD_D(); unsigned int16 value; void main() { set_tris_c(0x00); led=1; delay_ms(500); LCD_D(); delay_ms(50); while(1) { set_timer1(0); setup_timer_1(t1_external | T1_DIV_BY_1); delay_ms(1000); // in protues, should be 1000/3 setup_timer_1(T1_DISABLED); value=get_timer1(); lcd_gotoxy(11,4); printf(lcd_putc,"%LU HZ ",value); led=!led; } } *****************************************************************

DATA ACQUICATION SYSTEM


Introduction Measurement of the three basic quantities: voltage, temperature, and current can provide enough information to allow for debugging of almost any electrical circuit. During the development of a switch-mode power supply it was determined that some sort of data logging was necessary to protect the supply and determine if the supply was operating properly. Out of this need a data acquisition system was developed. The data acquisition system measures one channel of voltage from 0 to 20 volts, one channel of current from 50 to +50 amps, and two channels of temperature (one ambient and one load). This amount of data is enough to determine supply efficiency and temperature rise. With additional channels or faster sampling rates it would be possible to measure and calculate inrush current, supply stability, and transient response.

Implementation options Two options were initially considered to implement the data logger. First, adding an outboard analog to digital converter (ADC) to the 8052 board used for development in class was considered. This approach had the advantage of allowing me to use a known good development system, software toolset, and the ability to get support from teachers and other students. Unfortunately, I had a difficult time finding multi-channel ADC converters featuring parallel interfaces to 8-bit busses that could resolve more than 8 bits. Most modern ADCs found used a serial interface. This was a problem on the 8052 board as the serial port was tied up for communication to the PC. Also fully developing a software-based serial protocol on a relatively slow processor like the 8052 could be difficult. Figure 1 shows the proposed block diagram for the 8052 based data acquisition system.

Figure 1, data acquisition system using 8052 board

The second option considered the use of an altogether different processor, the Microchip PIC controller. PICs are self-contained microcontrollers often including clock, I/O, and a host of peripherals on-chip. The great advantage seen by adopting the PIC was a chip with onboard analog to digital converters was available in a small 14-pin DIP package. In addition a serial port, and multiple timer/counters were available. A low-cost ($35) development kit is available from Microchip to try out any of the 14-pin series of micrcontrollers. Additionally, for the intended application a low-power small form factor device was a plus. Essentially all the PIC needs to create the system is the analog interface and a voltage regulator. Just the 8052 board requires 2 to 3 times the space of the board designed for the PIC controller and analog board. The downside of this approach hinged around learning a new assembly language for the PIC microcontroller and learning a new development environment and device programmer. Figure 2 shows the block diagram for the PIC data acquisition system.

Figure 2, PIC processor based data acquisition system


PIC selection and setup There are literally hundreds of PIC microcontrollers to pick from. The programmer I had already purchased narrowed this selection down to 8 or 14 pin devices. At minimum 4 ADC channels, a UART, and one counter timer were needed. The first device found to meet these specifications was the PIC16F688. The 688 contains 8 channels of 10-bit AD converters, an enhanced UART, two timer counters, analog input comparison modules, an internal 32kHz to 8MHz clock, and flash program memory. In order to use the PIC, settings for all the internal registers needed to be determined or calculated via the datasheet. The internal oscillator was used and set to 4MHz. Next, the serial port was configured. The enhanced UART (EUSART) has an internal baud rate generator (no external timer is needed). The EUSART was setup to communicate at 9600 bps, 1 stop bit, 8 data bits, and no parity. This seemed to be a common serial data rate that was easily achieved with little error in bit-rate on the PIC (about 0.16%). The commonly used baud rates were all available in tables in the 688 datasheet. After the serial port was configured the analog to digital converter was set-up. A conversion time of 4.0us as dictated by the datasheet was selected. Then, registers were set up to use the positive supply as the ADC reference voltage along with selecting the location of the most significant bit of the result. Finally, a timer was set up to control the rate of data sampling. The timer values were set to allow for maximum delay that turned out to be around of a second. The timer overflow bit was checked via polling. This approach was used because exact time intervals were not needed and quick response was not necessary.

Microchip provides an integrated development environment (IDE) called MPLAB for coding, compiling, setting up, and controlling programmers for the PIC series of microcontrollers. Included in the IDE is a debugger and compiler. The debugger worked well until additional peripherals were initialized and used which then caused the debugger to crash the IDE. Thus, all further testing needed to be conducted on actual hardware. A simple USB powered programmer interfaced to the IDE and reprogrammed the flash program memory in PIC controllers.

Microcontroller Firmware After configuration of peripherals the microcontroller firmware consisted of a simple loop that acquired samples, converted them to a format acceptable to HyperTerminal, and echoed them to the serial port. Code is attached to the end of this document in listing 1. Peripherals were first initialized as described in the previous section. Following this a timer set to approximately one second would overflow triggering a capture event. The capture event consists of setting ADC registers, then waiting for the conversion to be completed. These events are repeated four times to cover all the input channels. The results are then converted to a three digit octal number via shifts and bit masks. Only 8 bits of the 10-bit result are converted to octal, as it appeared the lower value bits only added noise to the acquired signal. Finally, the converted values were output on the serial port to HyperTerminal in ASCII format delimited with commas. Figure 3 shows the block diagram for the microcontroller firmware.

Figure 3, A block diagram of the PICs firmware

Hardware The high integration of the PIC controller leads to a very simple hardware solution. On the digital side the PIC controller is connected to a MAX232, RS-232 to logic-level converter. A 5 V power supply and some supply decoupling capacitors round out the digital section of the hardware. Figure 4 shows the implementation of the digital board that was constructed on the PICKit-1 development board.

Figure 4, the digital section of the data acquisition system


Highly integrated sensors reduced the difficulty of implementing an analog interface board. The LM35 temperature sensor features a conditioned output with a 10mV/C output slope. It was decided to use the LM35s output directly, without amplification, with slightly reduced resolution. A hall-effect current sensor the ASC750SCA-050 made by Allegro was chosen as an easy integrated solution for current sensing. The current sensor is capable of resolving 50 to +50 A and outputs a 0 to 5 V signal corresponding to the current through the device. In the original application it was expected to see load currents up to 30 A. However, when demonstrating the device it was not possible to find power supplies capable of supplying more than 2.5A, thus the captured waveforms appear very noisy due to the small currents measured. Figure 5 shows the schematic of the analog board.

Figure 5, analog interface section of the data acquisition system


The physical hardware is shown in photo 1. Two LM35 temperature sensors are attached via twisted cable, enabling them to be clamped onto heatsinks to measure power supply temperatures. A set of binding posts is provided for voltage measurement and current measurement input. The 9 pin serial port hangs off the left side of the development board (black PCB on top). Unregulated (9 to 37 VDC) DC input is supplied via two wires exiting the back of the board.

Photo 1, physical realization of the data acquisition system

Results To test the data acquisition system an unregulated power supply was used. Real power supplies have internal resistance that can be demonstrated if the load of the supply is varied. The circuit in figure 6 was built to show the effect of loading the supply under various conditions.

Figure 6, an unregulated power supply loaded with various power resistors


The output voltage, current, ambient temperature, and temperature of the load resistor were all monitored via the data acquisition system. After logging the octal numbers to a text file via HyperTerminal, the data was scaled and plotted in MS Excel.

Plot 1, result of power supply testing, showing voltage, current, and two temperatures
Plot 1 shows the results of loading the supply with three different values of load resistors. As expected the supply voltage sags with decreasing resistance. The output current changes from 400mA to about 1A over the three different resistors. Finally, the temperature of the load resistor peaks at about 55 degrees Celsius. This simple application example shows the utility and some of the capabilities of the data acquisition system.

Conclusions and Future Work The data acquisition system proved to be a successful, yet challenging final project. Choosing a different microcontroller platform on which to base the project made hardware design much simpler. However, using the PIC controller greatly increased the difficulty of software design. A new assembly language was learned to take advantage of the PIC. Additionally, it was necessary to learn the development environment, compiler, and device programmer. Hardware design went relatively smoothly. Highly integrated sensors made the analog interface a snap. For some sensors such as the current sensor and to a lesser degree the temperature sensors the data acquired was of low resolution. Ideally, a higher resolution ADC converter would be needed to take better data, or a variable gain amplifier could be used. The primary problem with the current sensor was because it was intended for a 0 to 50 A range. In the original application this high current sensor was fine. Under testing, low-current supplies were used that showed the low resolution of the ADC. This combined with using a very small region of the current sensors range resulted in noisy captured data. This data acquisition system, while functional, could be improved. Primarily, the improvements are centered on the lack of resolution of the ADC in the PIC controller and the need for better PC interface software. Other microcontrollers such as the MSC series from Texas Instruments have on-board ADC converters with up to 24 bits of resolution. These microcontrollers also feature programmable gain

amplifiers, which effectively increase the dynamic range of the ADC and thus further increase resolution. An improved voltage measurement input is also desired. Currently, the system can only measure positive ground referenced voltages. With a true differential amplifier input, positive and negative voltages could be read without the fear of shorting a measurement channel to ground. On the software side two major improvements are warranted. First, the capability to display real-time values of the captured data would greatly increase the utility of the data acquisition system. Next, an integrated capture and display program would greatly simplify data capture. The current system requires capturing data via HyperTerminal to a text file. This text file then is updated in an excel spreadsheet. Excels update feature works most of the time, however, trouble was occasionally experienced resulting in Excel crashing. The current solution is far from a one-click data capture. With dedicated software it is possible that a single click would enable a user to view live data and concurrently save the trend data to a file.

Listing 1, PIC16F688 assembly code for the data acquisition system

list #include

p=16f688 <P16F688.inc>

; list directive to define processor ; processor specific variable definitions

__CONFIG _CP_OFF & _CPD_OFF & _BOD_OFF & _PWRTE_ON & _WDT_OFF & _INTRC_OSC_NOCLKOUT & _MCLRE_OFF & _FCMEN_OFF & _IESO_OFF

; '__CONFIG' directive is used to embed configuration data within .asm file. ; The labels following the directive are located in the respective .inc file. ; See respective data sheet for additional information on configuration word.

;***** VARIABLE DEFINITIONS w_temp status_temp pclath_temp EQU EQU EQU 0x71 0x72 0x73 ; variable used for context saving ; variable used for context saving ; variable used for context saving

ADCH0 ADCH1 ADCH2 ADCH3 COUNTER TXPREBUF OCTTOVERT

EQU B'00000001' EQU B'00000101' EQU B'00001001' EQU B'00001101' EQU 0x60 EQU 0x61 EQU 0x20

;setup ch 0, Vdd for Vref, and left justified result ;set to Ch1 same settings as above ;set to Ch2 same settings as above ;set to Ch3 same settings as above ;counter variable ;A buffer for the serial transmit buffer (a prebuf) ;stores the a/d value when it's being converted to octal

;********************************************************************** ORG goto 0x0 main ; processor reset vector ; go to beginning of program

main

;*********************************************************** ;Setup For 9600 bps tx serial interface ;*********************************************************** bsf STATUS, RP0 ;bank 1 ;setup RC0-5 as inputs for serial i/o and A/D

movlw B'00111111' movwf TRISC bcf bsf bsf bcf movlw d'25' movwf SPBRG bcf bsf TXSTA, SYNC TXSTA, TXEN STATUS, RP0 RCSTA, SPEN

;bank 0 ;serial port enable

BAUDCTL, BRG16 ;use 16 bit baudrate generator TXSTA, BRGH ;use low baudrate speed

;setup baudrate generator ;asynchronous serial i/o ;enable transmission

;*********************************************************** ;Setup A/D converter ;*********************************************************** bsf STATUS, RP0 movlw B'00011111' movwf TRISA movlw 0xFF movwf ANSEL movlw B'01010000' movwf ADCON1 bcf STATUS, RP0 ;Set 4uS conversion time w/ 4MHz internal clk ;bank 0 ;Enable all available Analog channels ;bank 1 ;Setup all of port A as inputs for A/D

movlw ADCH0 movwf ADCON0 call WaitForAD ;AD: right justified result, ch 0, VDD ref. voltage

;*********************************************************** ;Setup Timer1 for 1/10 second wait period ;*********************************************************** movlw B'00110001' movwf T1CON ;load timer1 config register

GoAgain: movlw 0x01 movwf TMR1L movlw 0x00 movwf TMR1H ;bsf T1CON, TMR1ON bcf PIR1, TMR1IF ;start timer ;clear overflow flag ;set to max for approx 1 sec delay

;This is the delay between sample periods from the analog inputs Wait: btfss PIR1, TMR1IF goto Wait ;check if timer has overflowed

call GetADValues

; loop through 4 values here and print them out movlw 0x4 movwf COUNTER movlw 0x21 movwf FSR ;point to first a/d value ;data pointer ;loop 4 times

OutLoop:

movf INDF, W movwf OCTTOVERT

;getting indirect data ;store a/d value we need to convert

call TO_OCTAL

;convert currently selected A/D Channel to octal

movf 0x30, W movwf TXPREBUF call SENDBYTE

;output all bytes

movf 0x31, W movwf TXPREBUF call SENDBYTE

movf 0x32, W movwf TXPREBUF call SENDBYTE

movlw ',' movwf TXPREBUF call SENDBYTE

;do checking on this one to see if we're at the last byte

incf FSR decfsz COUNTER goto OutLoop ; end of above loop

;goto next a/d value ;is counter zero yet? if so skip goto

movlw 0x0A movwf TXPREBUF call SENDBYTE

;Line Feed (newline, hopefully)

;movlw 0x0D ;movwf TXPREBUF

;carridge return

;call SENDBYTE

goto GoAgain

;Reset the timer for another go around

;*********************************************************** ;Subroutines ;***********************************************************

WaitForAD: movlw D'176' movwf COUNTER FourFourWait: decf COUNTER bnz FourFourWait

;wait 44us to init, 176 instruction cycles ;really only need 1/2 this many cycles due to test and set

;keep decrementing until we reach 0

return

;get a/d values for 4 ch GetADValues: movlw 0x21 movwf FSR ;start of free ram ;setup indirect addressing register

movlw ADCH0 movwf ADCON0 bsf ADCON0, GO btfsc ADCON0, GO goto $-1 movf ADRESH, W movwf INDF incf FSR

;goto channel 0

;start conversion ;conversion done? ;keep looping ;get high byte into acc W ;store adresh to 21h ;move ptr to 22h

call WaitForAD

movlw ADCH1 movwf ADCON0 bsf ADCON0, GO btfsc ADCON0, GO goto $-1 movf ADRESH, W movwf INDF incf FSR

;goto channel 1

;start conversion ;conversion done? ;keep looping ;get high byte into acc W ;store adresh to 22h ;move ptr to 23h

call WaitForAD

movlw ADCH2 movwf ADCON0 bsf ADCON0, GO btfsc ADCON0, GO goto $-1 movf ADRESH, W movwf INDF incf FSR

;goto channel 2

;start conversion ;conversion done? ;keep looping ;get high byte into acc W ;store adresh to 23h ;move ptr to 24h

call WaitForAD

movlw ADCH3 movwf ADCON0 bsf ADCON0, GO btfsc ADCON0, GO goto $-1 movf ADRESH, W movwf INDF

;goto channel 3

;start conversion ;conversion done? ;keep looping ;get high byte into acc W ;store adresh to 24h

return

;convert to 3 octal bytes in ASCII ;stores bytes in 0x30 to 0x32, w/ lsb in 0x32 msb in 0x30 ;input value stored in 0x20, ie OCTTOVERT TO_OCTAL: clrc ;clear carry ;bit mask field ;and with ADRESH ;make this into an ASCII number ;store result away

movlw B'00000111' andwf OCTTOVERT, W addlw 0x30 movwf 0x32 ;octal byte 2 movlw B'00111000' andwf OCTTOVERT, W movwf 0x31 rrf 0x31 rrf 0x31 rrf 0x31 movf 0x31, W addlw 0x30 movwf 0x31 ;octal byte 3 clrc ;clear carry

;bit mask field ;get 2nd set of 3 bits ;place back into file ;rotate to LSB, need 3x

;now get it back ;and add 30h to make a ascii number ;store again

movlw B'11000000' andwf OCTTOVERT, W movwf 0x30 rrf 0x30 rrf 0x30 rrf 0x30 rrf 0x30 rrf 0x30

;bit mask field ;get last 2 bits

rrf 0x30 ;btfsc 0x21, 0 ;bsf 0x31, 2 movf 0x30, W addlw 0x30 movwf 0x30 ;get value back ;convert to ASCII ;store it ;check the LSB value from the last byte

return

;transmit data on serial port SENDBYTE: btfss TXSTA, TRMT goto SENDBYTE ;check tx buffer ready bit ;try again, keep polling

movf TXPREBUF, W movwf TXREG

;get data from pre-buffer ;move data to tx register and start transmission

return

ORG DE

0x2100 1,2,3,4

; data EEPROM location ; define first four EEPROM locations as 1, 2, 3, and 4

END

; directive 'end of program'

MOTOR CONTROL

Controlling Stepper Motors with a PIC Microcontroller


For applications where precise measuring of a motors' rotor position is critical, a Stepper Motor is the best choice. Stepper motors operate differently from other motors; rather than voltage being applied and the rotor spinning smoothly, stepper motors turn on a series of electrical pulses to the motor's windings. Each pulse rotates the rotor by an exact degree. These pulses are called "steps", hence the name "stepper motor".

The degrees per pulse is set in the motor's manufacturing, and is provided in the spec sheets for that motor. They can range from ultra-fine movements of a fraction of a degree (i.e., 0.10 degrees), to larger steps (i.e. 62.5 degrees). This article will explain the operating principals of stepper motors, and will give instructions on how to control them via a PIC16F84 microcontroller to perform many functions.

How Stepper Motors Work


Stepper motors consist of a permanent magnet rotating shaft, called the rotor, and electromagnets on the stationary portion that surrounds the motor, called the stator. Figure 1 illustrates one complete rotation of a stepper motor. At position 1, we can see that the rotor is beginning at the upper electromagnet, which is currently active (has voltage applied to it). To move the rotor clockwise (CW), the upper electromagnet is deactivated and the right electromagnet is activated, causing the rotor to move 90 degrees CW, aligning itself with the active magnet. This process is repeated in the same manner at the south and west electromagnets until we once again reach the starting position.

Figure 1

In the above example, we used a motor with a resolution of 90 degrees or demonstration purposes. In reality, this would not be a very practical motor for most applications. The average stepper motor's resolution -- the amount of degrees rotated per pulse -- is much higher than this. For example, a motor with a resolution of 5 degrees would move its rotor 5 degrees per step, thereby requiring 72 pulses (steps) to complete a full 360 degree rotation. You may double the resolution of some motors by a process known as "half-stepping". Instead of switching the next electromagnet in the rotation on one at a time, with half stepping you turn on both electromagnets, causing an equal attraction between, thereby doubling the resolution. As you can see in Figure 2, in the first position only the upper electromagnet is active, and the rotor is drawn completely to it. In position 2, both the top and right electromagnets are active, causing the rotor to position itself between the two active poles. Finally, in position 3, the top magnet is deactivated and the rotor is drawn all the way right. This process can then be repeated for the entire rotation.

Figure 2

There are several types of stepper motors. 4-wire stepper motors contain only two electromagnets, however the operation is more complicated than those with three or four magnets, because the driving circuit must be able to reverse the current after each step. For our purposes, we will be using a 6-wire motor. Unlike our example motors which rotated 90 degrees per step, real-world motors employ a series of mini-poles on the stator and rotor to increase resolution. Although this may seem to add more complexity to the process of driving the motors, the operation is identical to the simple 90 degree motor we used in our example. An example of a multipole motor can be seen in Figure 3. In position 1, the north pole of the rotor's permanent magnet is aligned with the south pole of the stator's electromagnet. Note that multiple positions are aligned at once. In position 2, the upper electromagnet is deactivated and the next one to its immediate left is activated, causing the rotor to rotate a precise amount of degrees. In this example, after eight steps the sequence repeats.

Figure 3

The specific stepper motor we are using for our experiments (ST-02: 5VDC, 5 degrees per step) has 6 wires coming out of the casing. If we follow Figure 5, the electrical equivalent of the stepper motor, we can see that 3 wires go to each half of the coils, and that the coil windings are connected in pairs. This is true for all four-phase stepper motors.

Figure 5

However, if you do not have an equivalent diagram for the motor you want to use, you can make a resistance chart to decipher the mystery connections. There is a 13 ohm resistance between the center-tap wire and each end lead, and 26 ohms between the two end leads. Wires originating from separate coils are not connected, and therefore would not read on the ohm meter.

First Stepper Circuit


Figure 4 is the schematic of our first test circuit. The PIC's output lines are first buffered by a 4050 hex buffer chip, and are then connected to an NPN transistor. The transistor used, TIP120, is actually a NPN Darlington (it is shown as a standard NPN). The TIP120's act like switches, activating one stepper motor coil at a time.

Figure 4

Due to a inductive surge created when a coil is toggled, a standard 1N4001 diode is usually placed across each transistor as shown in the figure, providing a safe way of dispersing the reverse current without damaging the transistor. Sometimes called a snubbing diode. The TIP120 transistors do not need an external snubbing diode because they have a built in diode. So the diodes shown in the drawing are the internal diodes in the TIP120 transistors. The simplest way to operate a stepper motor with a PIC is with the full step pattern shown in Table 1. Each part of the sequence turns on only one transistor at a time, one after the other. After the sequence is completed, it repeats infinitely until power is removed.
Q1 + Q2 + Q3 + Q4 -

Table 1

I purposely made this first program as small as possible, simply to demonstrate how easy it is to control a stepper motor. Also note the use of high and low commands to control the output lines, rather than peek and poke routines. For our purposes, high and low are sufficient. Listing 1 ' First stepper motor controller program ' Rotates motor at set speed forever Symbol delay = B0 delay = 25 loop: high 0 pause delay low 0 high 1 pause delay low 1 high 2 pause delay low 2 high 3 pause delay low 3 goto loop ' use b0 as the delay variable ' set the delay to 25 ms

' turn on Q1 ' wait 25 ms ' turn off Q1 ' turn on Q2 ' wait 25 ms ' turn off Q2 ' turn on Q3 ' wait 25 ms ' turn off Q3

' turn on Q4 ' wait 25 ms ' turn off Q4 ' forever

Second Basic Program


The first program was fine for demonstrating how to control a stepper motor with a PIC Micro, but was severely limited to the one mode of operation preprogrammed into it. In this next program, we will make the program controllable by external user input in the form of four switches: SW1 will incrementally increase the delay variable, thereby slowing the rotation of the motor. SW2 does the opposite. SW3 halts all operation while the switch is pressed. SW4 reverses direction of the motor (CW to CCW or vice-versa) while it is closed (pressed). listing 2 ' Second stepper motor controller program ' Responds to user input by changing speed or direction Symbol delay = B0 delay = 100 forward: high 0 pause delay low 0 high 1 pause delay low 1 high 2 pause delay low 2 high 3 pause delay low 3 goto check reverse: high 3 pause delay low 3 high 2 pause delay low 2 high 1 pause delay

low 1 high 0 pause delay low 0 goto check check: if pin4 = 0 then timeup if pin5 = 0 then timedn if pin6 = 0 then halt if pin7 = 0 then reverse goto forward timeup: delay = delay + 5 pause 50 if delay > 250 then max if pin4 = 0 then timeup goto check timedn: delay = delay - 5 pause 50 if delay <20 then min if pin5 = 0 then timedn goto check halt: if pin6 = 0 then halt goto check max: delay = 245 goto check min: delay = 25 goto check ' use b0 as the delay variable ' delay will begin at 100 ms

' turn on Q1 ' wait for delay ms ' turn off Q1

' turn on Q2 ' wait for delay ms ' turn off Q2 ' turn on Q3 ' wait for delay ms ' turn off Q3 ' turn on Q4 ' wait for delay ms ' turn off Q4 ' check the status of switches

' turn on Q4 ' wait for delay ms ' turn off Q4 ' turn on Q3 ' wait for delay ms ' turn off Q3 ' turn on Q2 ' wait for delay ms ' turn off Q2 ' turn on Q1 ' wait for delay ms ' turn off Q1 ' check the status of switches

' if nothing pressed, continue

' increase delay by 5 ms ' pause for 50 ms

' check switches again

' decrease delay by 5 ms ' pause for 50 ms

' check switches again

'check switches again

' cap the delay at 245 ms ' check switches again

' limit the delay to 25 ms ' go back and check switches

End Listing 2 As you can see by looking at the schematic (Figure 7), the "switches" used in this circuit are pieces of jumper wire on a breadboard. The inputs (B0-B3) are kept high via Vcc through a 10K resistor. Theses switches are activated by grounding them via another piece of jumper wire.

Figure 7

A note on the previous two listings: the minimum delay used in the programs was 25 ms. Depending on the clock speed of your crystal, 25 ms may be either too fast or too slow for the rotor to move. If you are having problems getting these programs to work, this is a likely culprit (further troubleshooting information).

Half Stepping
As previously stated, half-stepping doubles the resolution of the motor. In our case, we are using a motor with a 5 degree / per step resolution, requiring 72 steps to complete one rotation. By half stepping, we could double this to 2.5 degrees / pulse, requiring 144 steps to complete one rotation. Table 2 shows the step pattern.
Step 1 2 3 4 5 6 7 8 Q1 + + + Q2 + + + Table 2 Q3 + + + Q4 + + +

There are two ways in which you could implement half-stepping in a PIC. One way would be to drive it directly, using the two previous listings, but replacing the high/low commands with the pins that correspond to each step. The other (and easier) way would be to use a UCN 5804 Stepper Motor IC in conjunction with the PIC.

The UCN 5804 Stepper Motor IC


By using an external stepper motor controller, such as the UCN 5804, you can simplify your programs and control as many motors as you have outputs via an array of UCN 5804's. Not only does it allow for the control of more motors, but more importantly, it simplifies the process. You now only have to output the pulse of your desired speed. Additionally, you can switch between full and half stepping in real time via a switch on the UCN 5804 (or you may have the PIC control it), as well as reverse direction. A pinout for the UCN804 is shown in Figure 8.

Figure 8

The schematic we will build to use this chip is shown in Figure 9. Since we are using a 5V stepper motor, we will be powering the UCN 5804 with a 9V wall transformer. You cannot use 6V, due to the draw of the motor. The UCN 5804 can support voltages up to 35V.

Figure 9

Notice in the schematic that two resistors, rx and ry, do not have an assigned value. This is because our motor draws only 100 mA, well under the chip's supported 1,250 mA. However, if you were to use a motor that draws the maximum or above, then you would need to use rx and ry to get the amperage under 1,250 mA. For example, a 24V motor with a phase resistance of 15 ohms would draw 1,600 mA (24/15 = 1.6). In this case, you should use _at least_ a 5 ohm resistor for both rx and ry, which would bring the current down to 1.2 A. Since the input of the UCN 5804 is CMOS and TTL compatible, we can connect the outputs from the PIC directly into the UCN 5804. Two outputs are needed; one to control the step input (pin 11), and one to control the output enable (pin 15) which enables the stepper motor while high and disables the stepper motor while low. Pins 9 and 10 control the stepping method (half or full steps). Pin 14 controls the step direction. Both of these controls can be manipulated by the PIC, but it is easier to control them directly through the use of jumpers acting as switches. All the program has to do, is output a pulse and set the output enable low. This can be accomplished with a very simple program such as the following:

Listing 3 ' Stepper motor control with a UCN 5804 Symbol delay = B0 low 1 delay = 10 delay = delay * 1000 loop: pulsout 0,delay goto loop ' make a delay variable ' set the output enable low ' set a pulsewidth of 10 ms ' turn delay into microseconds ' send pulsewidth of delay to UCN5804 ' repeat forever

End Listing 3 Notice that I added an extra step; taking the defined "delay" value and multiplying it by 1,000. This is necessary because the pulsout command requires a pulsewidth in micro-seconds, not milli-seconds. You can make the code even smaller by removing lines 1, 3, and 4 and replacing "delay" in line 5 with a set number in microseconds. However, I prefer to the method shown in the listing, because it makes it easier to change the delay parameter in the more familiar milliseconds without having to convert it to microseconds.

Speed Control via Potentiometers


The PIC Basic language has a command that allows you to read the value of potentiometers on a given scale. This is the "pot" command, and is used in the following manner: pot pin,scale,var Where pin is the pin the potentiometer is connected to (pins B0-7), scale is the maximum value the command will return (in this case 245, being the maximum amount of ms we want in between pulses), and var is the variable the value will be placed in.

Using this command, we can determine the value of a potentiometer (we will be using a 50K ohm pot) and then use it to control the pulsewidth outputted to the UCN 5804. A schematic is shown in Figure 10.

Figure 10

The program is shown in listing 4. First, it reads the value of pin B2 (the potentiometer), then places it on a scale of 245. That value is then multiplied by 1,000 (converting it into microseconds) and set to the UCN 5804. Listing 4 ' Controlling a stepper motor with the UCN 5804 and a potentiometer Symbol delay = B0 low 1 start: pot 2,245,delay if delay < 25 min

goto turn turn: delay = delay * 1000 pulsout 0,delay goto start min: delay = 25 goto turn ' make a delay variable ' set the output enable low

' read pot at pin B2 ' set min delay to 25 ' if delay is over 25, start moving

' turn delay into microseconds ' send to UCN 5804 ' go back to start

' bottom out the delay at 25 ' start the motor

End Listing 4 Not quite as complicated as you may have expected (thanks to the use of the UCN 5804). Notice again, the minimum delay set at 25 ms. If you would like to make it a lower number (thereby making the motor turn faster), simply change all occurrences of "25" to the number desired.

Controlling Stepper Motors with a PIC Microcontroller


If your motor does not move at all when the program is active, then the most likely problem is that the diodes are facing the wrong direction. Check the schematic for proper wiring. If the motor is moving, but does so only sporadically or jiggles back and forth, then there can be a number of possible causes:

1. There is not enough power going to the motor. This is often the case when using batteries which cannot support the drain of the motor. It is recommended that you use a wall transformer to power the motor in combination with a 7805 voltage regulator to power the circuitry. 2. You are not using TIP 120 transistors, or a variation that is not able to support the load of the stepper motor. 3. The stepper motor is not wired to the correct transistor. Check the coil resistance with an ohm meter and rewire properly. For motors purchased from us, the pinouts are available here. 4. The pulse frequency is higher than that which the motor can react to, causing a malfunction. The programs in this article use the delay variable to control pulse frequency. Try increasing the value to decrease pulse frequency. GENERATION OF GATE SIGNAL FOR CONVERTER AND INVERTER

Variable Light Source

Solar Panel

Charging Circuit

Battery

Inverter Circuit

Output 120V AC/ Variable Load

Hand Crank Station

Microcontroller
Phil (Power)

User Interface

Sierra (Station) Luis (Interface)

Figure 1: Project Block Diagram

2 Design

2.1 Component Descriptions


2.1.1 Variable Light Source
The Variable Light Source is used to simulate different levels of solar radiation. It will be a small desk lamp, about two feet high with an adjustable neck and a 40 W soft white light bulb. This lamp will be attached to a dimmer that will slide to allow various amount of light output. Users of the circuit will be able to change the amount of light the panel receives and therefore see what effects that has on solar panel voltage and efficiency.

2.1.2 Solar Panel


The Solar Panel is the backbone for the power system and therefore was mandatory to size first. Originally a Universal Power Group (18V, .56A 10W) solar panel was going to be used however, a six cell white Sun Power promotional panel was available on loan from the Power Group and was selected for this reason. Since the panel was promotional it was necessary to map out its IV-characteristics. The technique used to do this is outlined in section 3.2.1. The results were an open circuit voltage around 4V

and a short circuit current around 4A with a maximum power achieved of 9.68W. This fits our requirements of the panel being able to provide 8W which is described in section 2.2.1.

2.1.3 Charging Circuit


The charging circuit is used to provide a constant float voltage to the Lead-Acid Battery. It will take the solar panels 3-6V as input and boost it to 13.7V +/- 0.1V in order to match the batteries charging requirements. The converter will be built with discrete parts and the schematic is given in Error! Reference source not found. below. A MTP50N06 MOSFET (50V/60A) was used since its voltage and current ratings are well above the required 11V/5A limit. A 1N5822 Schottky Rectifier was selected due to its low 0.525V on-state voltage drop. To drive the MOSFET an IR2112 low-side gate driver will be used. The output capacitors are two 100F electrolytic capacitors. The choice for two capacitors rather than one comes from a desire to reduce the overall effective series resistance (ESR). By placing two similar capacitors in parallel the ESR will drop to half its original value simply based on basic resistor physics. The input inductor is a 325H inductor sized in order to reduce the current ripple of the circuit. It was wound using a powdered iron core of material type #26 and 28 gauge wire. The circuit will utilize the microcontroller as a feedback loop to insure it meets the batteries charging specifications.

Figure 2: Charging Circuit Design

2.1.4 Battery
The battery was selected to handle a load up to 100W for at least a 50 minute class period. The Universal Power Group 12V 7Ah battery was borrowed from the Power Lab. It will take a charge input from the charging circuit and output power to the inverter. The voltage of the battery will be monitored by the PIC through a simple resistor divider network. Current will also be monitored by the PIC through a 5V 5A Current Sensor. This information will then be displayed to the user.

2.1.5 Inverter Circuit


The inverter is the final stage in the conversion process. It will take the output from the battery and convert it to 120VAC to drive the variable load station. Originally the goal was to have 60Hz sine wave at the output but due to the unavailability of a 100W transformer it was decided to keep the 100 kHz switching and provide a 100 kHz square wave at the output. It will be built discretely and the schematic is given in Error! Reference source not found. below. The MOSFETs used will be MTP50N06

(50V/60A) which was selected because they had suitable voltage and current ratings. Two IRS2003 Dual High/Low side gate drivers will be used to drive the FETs. These drivers were selected due to the fact that they came with a built in dead time between high and low driving. This dead time is necessary to prevent creating a short across the battery terminals which is known as shoot-through current. The circuit will take a PWM signal generated from the PIC. A transformer will be the final stage in the conversion and is used to boost the inverters output from the 12V to 120V value needed for 120Vrms. The inverter should be able to handle 100W at the output in order to drive the entire range of the Variable Load Station. Finally, it will be monitored by the microcontroller to provide information on the power delivered to the load.

Figure 3: Inverter Circuit Design

2.1.6 Variable Load Station


The Variable Load Station provides the educator the ability to demonstrate the effect of different loading conditions on the overall efficiency and operation of the power circuitry. To mimic real world applications a load that varies from 0 100W was desired. This is handled by implementing the circuitry depicted in figure 4 below. Each resistor is a PF1260 High Power Silicon Resistor (20W, 1k). Each resistor being 1k means that each one will consume 14.4W when switched into the circuit. The switches are Single Pull Double Throw (SPDT) Switches that were provided by the parts shop. The station has its own printed circuit board (PCB) in order to allow the switches to be mounted to the external of the display case.

Figure 4: Variable Load Station Schematic

2.1.7 Microcontroller

As seen below in Error! Reference source not found., the microcontroller circuit consists of a PIC18LF2610, 12V to 5V voltage regulator IC, a 0.1F capacitor connected at VDD in order to clean up the power signal, and both VSS connected to ground. The PIC has a TX and RX outputs and inputs that will be used to connect to the Sparkfun BlueSMiRF Bluetooth module RX and TX pins respectively, which will facilitate the Bluetooth connection between the PIC and the Android phone. The PICs output pins 24 and 13 are CCP2 and CCP1 respectively and are the PWM outputs that are connected to the charging circuit and the inverter circuit. Pins 2-5, 7, and 21 are configured as inputs with an analog to digital converter. These inputs will be used to measure in voltage and current at the specific probe points in order to calculate power, and to monitor and maintain the optimal charging circuit voltage.

Figure 5: Microcontroller Schematic

2.1.8 User Interface Application


The user interface block will be design using Eclipse IDE, Java Development Tool, and XML based layout files. The end product will be an Android app that the user can download to their Android phone and follow the different components of the project on their own while learning about the process and looking at real time data values such as power, voltage, current, duty cycle, and frequency. The app will look similar to the layouts shown in Figures 6.

Figure 6: Android App Home Screen

2.1.9 Hand Crank Station


The Hand Crank Station is meant as a fun way for the user to compare the power produced by the solar panel to that produced by a more conventional mechanical method. The station consists of a 12V DC motor connected to an 8.5cm shaft through a gearbox. The gearbox was necessary based on our testing which showed a human can spin the shaft at a slower 40-60RPM than is need for the 1800RPM motor. The 65.5:1 gear ratio was selected due to availability in the machine shop and worked well.

2.2 Design Calculations


2.2.1 Solar Panel
The panel should be able to charge the 80Wh battery 10% in a one hour class period. This means that the panel should be able to provide 8W at any given time. This is given by equation 1 below. P= The 10W promotional panel obtained from the power lab will provide enough power.

(1)

2.2.2 Charging Circuit


Input: 3-6Vdc from Solar Panel Output: 13.7V +/- 0.1Vdc to the Battery PIC to deliver Switching Signal The characteristic equation for a Boost topology converter is given in equation 2 below. This assumes ideal parts (i.e. no voltage drop across the diode) and was used when making the design calculation.

(2)

As a quick check to see whether one or two boosts would be needed the Duty values were calculated in the extreme cases. These values should be between 10-90% and as can be seen below they came out within this range.

(3) (4)

One issue is how close the duty cycle gets to 90% even when using a simplified model. This implies a need to check a more realistic model by including a voltage drop across the diode of 0.5V (the value for the 1N5822). The new equation for duty cycle is worked out below.

(5)
Solving for D yields:

(6)
D = 77% This is still below the 90% mark so the design can be continued. With the duty signal verified the parts now need to be selected. First is the capacitor sizing which determines the ripple on the output of the converter. This is done by using the characteristic equation for a capacitor given below.

(7) (8)
For a Boost converter the current is simply the output current when the MOSFET is on. The current relationship is simply the inverse of the voltage relationship. Therefore, for our circuit, the output current will be either 1.45A or 2.2A in the worst case scenario when the solar panel is supplying its full 5A. Using the values above the Capacitance should be 66F. The selection of two 100F came from a desire to reduce ESR. Now the diode and MOSFET must be sized for voltage and current ratings. Both the diode and MOSFET must be able to block:

(9)

Therefore, in worst case when the input is 3V they must be able to block 10.7V. The current they can carry must be Iin which in the worst case is 5A. Finally, the inductor value must be large enough such that the converter remains in continuous mode. To find the inductor value the characteristic equation of an inductor was used.

(10) (11)
Using this equation when the MOSFET is on yields an inductance value greater than 3H. The oversizing of the inductor to 300 H was selected due to the ease of design when physically winding the inductor.

2.2.3 Battery
Ideally the battery could power a 100W load for a 50 minute class period. = 80 Wh

(12)

This implies that the 12V, 7Ah (84Wh) battery just meets this requirement. This is acceptable since in reality the load will not be continuously connected and will be varied from 0-100W throughout the class period.

2.2.4 Inverter Circuit


Input: 11-13Vdc from the battery Output: 120Vac, 60Hz, sine wave to variable load Take a PWM signal from the MCU A Full-Bridge or H-Bridge inverter will be used in our design with PWM switching signal. In this set-up the MOSFETs must be able to block the peak voltage and carry the highest peak output current. For our design the current peak will be 8.33A and the peak voltage will be the 12Vnom from the battery. The output from the inverter will be sent to a step-up transformer. This transformer will have to take the 10V peak from the inverter and boost it up to 170V peak. This means a 1:17 winding will be used. The transformer should be able to handle 100W on either side which means 0.833A on the secondary (highside) and 14.17A on the primary (low-side). Another issue in the inverter circuit is the selection of proper bootstrapping capacitors. The purpose of the bootstrap capacitor is to insure that a high enough voltage is kept between the gate and source in order to properly turn the high side gate on or off. This voltage for our circuit was 10-12V. To maintain this level a 56F tantalum capacitor was used. This was obtained from the equation below where the information on the right hand side was obtained from the IRS2003 datasheet.

(13 )

2.2.5 Inductor Design


Because inductors are such specialty items it was necessary to wind our own inductors. A powdered iron core was selected to act as the magnetic medium due to the wide range of core types and their availability in the parts shop. The characteristic equation for these inductors is given below where N is the number of windings and AL is given in .

(14)
Since the required inductance value was calculated above in the charging circuit section it is desired to find a material with an AL value that will give a reasonable amount of number of turns. Solving for AL in the equation above and taking N to be 100 yields:

(15) (16)
The material T-80-26 was found in the parts shop with an AL value of 450. Using this material with 80 turns would yield a value of 288H according to the inductance equation above. This is what was selected and after winding was measured using the LRC Bridge 2400 to be 325H. This discrepancy is acceptable and most likely occurred due to incorrect counting when winding the inductor.

2.2.6 Variable Load Station


The load station has to be able to handle a maximum of 100W and be incremental in nature. Ideally each resistor will consume 10W which leads to a total of 10 incremental steps that can be demonstrated. To find the resistance needed for each step the equation below can be solved using V as 120VAC. P=

(17)

R=

(18)

This yields R = 1.44 k. 1k resistors were selected due to availability which led to 14.4W dissipated in each resistor. This meant a total of 7 resistors are needed to reach the 100W maximum.

2.2.7 Microcontroller
Equation 19 below will be used to initialize the charging circuits PWM signal duty cycle, where Vin is the monitored voltage, Vout is to be maintained at 13.7V, and D is the duty cycle of the PWM signal. (19) When using the calculation above the duty cycle should stay between 10%-90% range so as to not damage the circuit. After initializing the duty cycle value for the PWM signal the charging circuit voltage is monitored in order to change the D to maintain a 13.7V at Vout. The voltage and current values measured at the probe points will be used to measure the power at specific points in the process through the use of equation 20. (20) (21) (22)

3. Design Requirements and Verification

3.1 Requirements
Status Complete Performance Requirement 1) The solar panel will provide 8 W a) The open circuit voltage will be approximately 4 V outside on a day when the sun is unobstructed for at least 70% of the time b) The short circuit current of the solar panel will be 5-6 A outside on a day when the sun is unobstructed for at least 70% of the time c) Plot of the solar panels I-V curve will be fitted to the curve of Figure 1 within 10% Testing and Verification Procedure 1) Measure the output power when the lamp is on at full power and is shone directly onto the solar panel a) Obtain the open circuit voltage with the solar panel outside at noon on a day with >70% sun by measuring voltage with a known resistance b) Obtain short circuit current of the solar panel by dividing the obtained voltage by the known resistance c) Once the current and resistances are known, the

Complete

Transformer Needed

Complete

results will be plotted on a graph and the output will be analyzed and included in documentation 2) The charging circuit will provide 2) Monitor the converter recording 13.7V +/- 0.1V for charging of Pin ,Pout, Vout, Vin to see proper the battery over entire solar operation and record efficiency. panel range. a) Connect input to variable a) Can handle the 2-5V input power supply. Measure variation with external output voltage on Switching Signal. oscilloscope to verify proper b) Gate of the MOSFET is 13.7 +/- 0.1V output. Ensure receiving a 100kHz Switching duty cycle is within 10-90%. signal. b) Check to see a 0-5V square wave at Pin 24 of the PIC. Check to see a 0-12V square wave at Pin 7 of the Gate Driver. Both signals should be 100 kHz. 3) The inverter should convert the 3) Test the converter over the output from the battery into entire load range. Record 120VAC to either of the loads efficiency data as well as display c) Can handle 12Vdc to 120Vac output waveform on conversion over entire oscilloscope. output range with 100 kHz a) Vary load over 0-100W switching signal. range. View the output d) Can accept PWM signal from voltage waveform and PIC compare to a 120V square wave. Its frequency should be 100 kHz. b) Using the oscilloscope, view the PIC PWM signal from Pin 13. It should be a 0-5V square wave with a duty cycle of 50%. With the oscilloscope view both the outputs of the gate driver. They should be 0-12V square waves. One will be inverted while the other is not. 4) The microcontroller will make 4) Because the output of the solar accurate measurements of the panel and the hand crank can be inputs including the power found from aforementioned measurements from the solar processes, lab equipment will panel and hand crank, the be used to test values from the charging of the batter, and the microcontroller and a chart will efficiency of the circuitry to be created to ensure

Complete

Complete

within 5% of the actually value functionality within 5% of the A. Charging Circuit PWM actual value. Output will be 100KHz with a) View oscilloscope to ensure feedback controlled duty the microcontroller is cycle value producing accurate values. B. Inverter Circuit PWM Output b) The Bluetooth connectivity will be 100KHz with a 50% will be tested by using test duty cycle text to check connectivity. C. Analog to Digital Converter c) An oscilloscope will be used will measure accurate to compare the actual duty voltage and current cycle. measurements d) Use a multimeter to ensure D. PIC will send and receive the LM7805 IC is regulating data via Bluetooth voltage properly from 12V. accurately a) 5V voltage regulation at VDD on the PIC 5) Hand Crank Station should 5) Hook output to voltmeter and output 12V+/-2V verify 12V +/-1V at the output a) The hand crank startup under moderate human strain torque should be no greater a) Measure torque by finding than 6.87 Nm the product of the length of the arm, the magnitude of the force and the sine of the angle between the force vector and arm vector 6) The Android App will present 6) The Android App functionality the project data point values, can be observed by running the update its values real-time via app on an Android phone. Bluetooth, and provide A. Confirm pairing and summary information on the connection between the PIC different processes in the and app through real-time project. updates of the data points. A. Bluetooth connectivity through the app B. Provide voltage, current, power, and duty cycle, values C. Provide summary information on the Charging Circuit, Inverter Circuit, 120VAC Variable Load Station, Hand Crank Station, and Battery. Figure 7: Verification Table

3.2 Verification Testing

3.2.1 Solar Panel


The solar panel was tested outside on three separate occasions. Since the panel was a promotional item no datasheet exists for the unit. Because of this the data was compared to a typical IVCurve of a solar panel given in figure 8 below.

Figure 8: Typical IV-Curve of Solar Panel To get different points on the panels IV-Curve a system of parallel resistors like that of figure 9 was used. As more resistors are switched in the overall resistance is decreased and the curve is traced from the open circuit voltage (Voc) towards the short circuit current (Isc). Data for our three tests are given below in figure 10, 11, and 12. Figure 13 is a graph of test 3 which yielded the best results. Test 3 yielded the best results because the values of the resistors (10) were low enough to begin the change from the constant voltage region near the open circuit voltage to the constant current region. The other tests used resistors that were too large (3k, 39) and therefore the data obtained only covered a small portion of the graph close to Voc. Figure 13 shows that the panel fits a typical curve although the slope from Voc to the knee of the curve is much flatter. Also, still more resistors would have been needed in order to trace the curve even closer to the sort circuit current.

Figure 9: Schematic for Solar Panel Testing

Ohms Voltage Current Power

Test 1 on February 22nd Open Circuit 3000 2000 1000 666.67 560 280 186 112 3.33 3.24 3.3 3.26 3.26 3.19 3.19 3.18 2.96 0 0.00108 0.00165 0.00326 0.00489 0.005696 0.011393 0.017097 0.026429 0 0.003499 0.005445 0.010628 0.015941 0.018172 0.036343 0.054368 0.078229 Figure 10: Test 1 Data

Test 2 on February 29th Ohms Voltage Current Power Open Circuit 39 19.5 13 9.75 7.8 6.5 3.88 3.76 3.75 3.6 3.6 3.7 3.66 0 0.09641 0.192308 0.276923 0.369231 0.474359 0.563077 0 0.362503 0.721154 0.996923 1.329231 1.755128 2.060862 Figure 11: Test 2 Data Test 3 on March 9th 5 3.33 1.666667 1.111111 0.833333 0.714286 3.62 3.5 3.28 3.04 2.85 2.63 0.724 1.051051 1.968 2.736 3.42 3.682 2.62088 3.678679 6.45504 8.31744 9.747 9.68366 Figure 12: Test 3 Data

Ohms Open Circuit 10 Voltage 3.81 3.7 Current 0 0.37 Power 0 1.369

Figure 13: IV-Curve for Test 3

3.2.2 Charging Circuit


The charging circuit has been tested using an external switching signal and Power Supplies. The 12V and 5V logic level supplies were provided by the HP E3631A Triple Outlet Power Supply. The solar panel input voltage was provided by the Kenwood Variable DC Supply and was varied over the entire 36V range. Finally, the switching signal was provided by the 8011A Pulse Generator which allowed for control over the switching frequency and pulse width. The frequency was set to 100kHz in order to test the circuit as designed. It was desirable to see the efficiency of the converter over the range of desired inputs as well as over a range of Load levels. Two separate tests were performed. First, the Load was set at a constant 1.25 W by putting a 150 load across the output. The voltage was then varied from 3V to 6V in increments of 1V to see the effects of varying solar panel input voltage on converter efficiency. Data was also collected using the Oscilloscope to see the ripple on the output voltage. The results are given in Figure 14 and Figure 15 below:

Vin

Vout Delta V Efficiency 2.94 13.71 0.1 0.71 3.95 13.68 0.15 0.8

4.98 5.97

13.76 13.72

0.14 0.11

0.85 0.87

Figure 14: Data for Constant Power Varying Input Voltage

Figure 15: Graph of Efficiency vs. Input Voltage Next, the input voltage was held at 5V and the input power was varied from 1W to 5W. This is a good estimate of what we believe our panel will be able to provide and was made based on the solar testing that Sierra did. Again data was collected in order to obtain efficiency of the converter. The results are given in Figure 16 and Figure 17 below:

Vin

Vout Pin Pout Efficiency 4.98 13.71 0.87 0.74 0.85 4.98 13.76 1.48 1.26 0.85 4.95 13.72 2.32 1.91 0.82 4.89 13.73 5.2 3.9 0.75 Figure 16: Data for Constant Voltage Varying Power

Figure 17: Efficiency vs. Input Power These tests verify that the converter can function over the expected input voltage range and provide adequate output voltage. The ripple on the output is slightly higher than desired however this shouldnt cause any problems with the functioning of the overall circuit. If it becomes an issue more capacitance can be used on the output or a smaller switching frequency can be used for the switching signal both of which should reduce voltage ripple.

3.2.3 Inverter Circuit

To test the functioning of the inverter circuit a simple constant load was attached to the output of the converter. Data was then recorded through the oscilloscope to demonstrate the delay time between the high and low gate drivers which are demonstrated in Figure 18.

Figure 18: Gate Delay for the IRS2003

Data was also taken to see the output voltage and frequency. This data is shown in Figure 19 with CH1= Reference Signal from PIC, CH2 = High Side Gate Drive Signal, CH3= Low Side Gate Drive Signal, and CH4 being the Output Voltage of the inverter. It is significant to notice that the output signal is a 100 kHz square wave due to the inability to find a suitable 100 W 60 Hz transformer. Also, it is significant to notice 12 VAC rather than the 120 VAC desired. This was due to a failure in the design of the transformer which we believe to be inadequate to handle the 100 kHz signal. A new magnetic core would need to be selected to avoid transformer saturation.

Figure 19: Testing and Verification of Inverter Circuit

3.2.4 Microcontroller
As seen in Figure 20, the 12V to 5V regulator is working as it should maintain a 5V supply to the PIC. In Figure 21, it can be seen that the output of the PIC charging circuit PWM produces the desired 100 kHz signal with a feedback controlled variable duty cycle that changes per the monitoring code to keep the charging circuit Vout at 13.7V. Figure 22 shows that the inverter circuit PWM is at 100kHz and a constant 50% duty cycle. As seen in Figure 23, the Analog to Digital converter works as expected.

Figure 20: 12V to 5V Voltage Regulator

Figure 21: PIC Charging Circuit PWM Output

Figure 22: PIC Inverter Circuit PWM Output

Actual Voltage 1 2 3 4 5 6 7 8 10 14

ADC Voltage 1 2 3 4 5 6 8 9 11 16 Figure 23: Analog to Digital Converter Testing Results

Percent Error 0.00% 0.00% 0.00% 0.00% 0.00% 0.00% 14.29% 12.50% 10.00% 14.29%

3.2.5 Current Sensors

To measure current and report it to the PIC 5V 5A Hall Effect current sensors were used. According to the manufacturers datasheet the relationship between input current to the output voltage is given by the equation below.

(23)
To verify this relationship a simple test circuit was hooked up following the schematic given on the datasheet in Figure 24.

Figure 24: Current Sensor Testing Setup The pins 1 and 2 were connected to a constant DC voltage source provided by the Kenwood Supply in the Power Lab. Pins 3 and 4 went out to the load while Pin 7 was monitored by the bench multimeter. We then swept the input voltage over a range while keeping the output load constant. We measured the current through Pins 1 and 3 and the voltage out at Pin 7. This allowed for the creation of a V vs. I graph that is given in Figure 25. The data for our tests is given in Figure 26.

Figure 25: V vs. I Curve Generated For Current Sensors

As can be seen the measured values yielded a relationship given by the equation below.

(24)
This is slightly different than the value given on the manufacturers datasheet and was used when programming the PIC. Current sensor testing March 29 Voltage Resistance Measured Vout Vout % Error

Current 2.26 1.7 1.13 0.56 0 1.13 1.13 1.13 1.13 1.13 1.84 1.375 0.912 0.46 0

Expected 2.868 2.775 2.6824 2.592 2.5 2.83 2.74 2.66 2.58 2.5 1.32% 1.26% 0.84% 0.46% 0.00%

Figure 26: Data For Current Sensor Testing

Das könnte Ihnen auch gefallen