mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Introduction: World of microcontrollers The situation we find ourselves today in the field of microcontrollers had its beginnings in the development of technology of integrated circuits.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers of all today’s microprocessors. Intel kept on developing it and in April 1974 it launched an 8-bit processor called the 8080. It was able to address 64Kb of memory, had 75 instructions and initial price was $360. Another American company called Motorola, quickly realized what was going on, so they launched 8-bit microprocessor 6800. Their chief constructor was Chuck Peddle.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Fig. 0-1 Microcontroller versus Microprocessor On the other hand, the microcontroller is designed to be all of that in one. No other specialized external components are needed for its application because all necessary circuits which otherwise belong to peripherals are already built into it. It saves the time and space needed to design a device. BASIC CONCEPT http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Did you know that all people can be classified into one of 10 groups- those who are familiar with binary number system and those who are not familiar with it. You don’t understand? That means that you still belong to the later group. If you want to change your status read the following text describing briefly some of the basic concepts used further in this book (just to be sure we are on the same page).
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers example, but in reverse order. Bear in mind that all this is about mathematics with only two digits- 0 and 1, i.e. base-2 number system (binary number system). Fig. 0-3 The number 218 represented in binary and decimal system Clearly, it is the same number represented in two different ways. The only difference is in the number of digits necessary for writing some number.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Fig. 0-4 Binary and Hexadecimal number The largest number that can be represented by 4 binary digits is the number 1111. It corresponds to the number 15 in decimal system. That number is in hexadecimal system represented by only one digit F. It is the largest onedigit number in hexadecimal system.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers In order to make conversion of a hexadecimal number to decimal, each hexadecimal digit should be multiplied with the number 16 raised by its position value. For example: Fig. 0-5 Hexadecimal to decimal number conversion Hexadecimal to Binary Number Conversion It is not necessary to perform any calculation in order to convert hexadecimal numbers to binary numbers.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Comparative table below contains the values of numbers 0-255 in three different numbering systems. Marking Numbers The hexadecimal numbering system is along with binary and decimal number systems considered to be the most important for us. It is easy to make conversion of any hexadecimal number to binary and it is also easy to remember it. However, these conversions may cause confusion.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers is therefore called the least significant bit (LSB). Since eight zeros and units of one byte can be combined in 256 different ways, the largest decimal number which can be represented by one byte is 255 (one combination represents zero). A nibble is referred to as half a byte. Depending on which half of the byte we are talking about (left or right), there are “high” and “low” nibbles. Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers When used in a program, a logic AND operation is performed by the program instruction, which will be discussed later. For the time being, it is enough to remember that logic AND in a program refers to the corresponding bits of two registers. OR Gate Similarly to the previous case, OR gates also have two or more inputs and one output.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers If a program, logic NOT operation is performed on one byte. The result is a byte with inverted bits. If byte is considered to be a number, the inverted value is actually a complement of that number, i.e. the complement of a number is what is needed to add to it to make it reach the maximal 8 bit value (255). EXCLUSIVE OR Gate The EXCLUSIVE OR (XOR) gate is a bit complicated comparing to other gates.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Fig. 0-17 Register Special Function Register In addition to the registers which do not have any special and predetermined function, every microcontroller has a number of registers whose function is predetermined by the manufacturer.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Fig. 0-18 Special Function Register Input/Output Ports In order to make the microcontroller useful, it has to be connected to additional electronics, i.e. peripherals. Each microcontroller has one or more registers (called a “port”) connected to the microcontroller pins. Why input/output? Because you can change the pin’s function as you wish.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Fig. 0-19 Input / Output ports One of the more important specifications of input/output (I/O) pins is the maximum current they can handle. For most microcontrollers, current obtained from one pin is sufficient to activate an LED or other similar low-current device (10-20 mA). If the microcontroller has many I/O pins, then the maximum current of one pin is lower.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers drawers. Suppose, the drawers are clearly marked so that it is easy to access any of them. It is easy enough to find out the contents of the drawer by reading the label on the front of the drawer. Each memory address corresponds to one memory location. The content of any location becomes known by its addressing. Memory can either be written to or read from.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers UV Erasable Programmable ROM (UV EPROM). Both the manufacturing process and characteristics of this memory are completely identical to OTP ROM. However, the package of this microcontroller has a recognizable “window” on the upper side. It enables the surface of the silicon chip inside to be lit by an UV lamp, which effectively erases and program from the ROM.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers ● ● ● Instruction Decoder is a part of the electronics which recognizes program instructions and runs other circuits on the basis of that. The “instruction set” which is different for each microcontroller family expresses the abilities of this circuit. Arithmetical Logical Unit (ALU) performs all mathematical and logical operations upon data.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Fig. 0-23 Serial communication should be strictly observed. It is a set of rules which must be applied in order that the devices can correctly interpret data they mutually exchange. Fortunately, the microcontrollers automatically take care of this, so the work of the programmer/user is reduced to simple write (data to be sent) and read (received data).
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers I2C (Inter Integrated Circuit) is a system used when the distance between the microcontrollers is short and specialized integrated circuits of of a new generation (receiver and transmitter are usually on the same printed circuit board). Connection is established via two conductors- one is used for data transfer whereas another is used for synchronization (clock signal).
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Even pulses coming from the oscillator enable harmonic and synchronous operation of all circuits of the microcontroller. The oscillator module is usually configured to use quartz crystal or ceramic resonator for frequency stabilization. Furthermore, it can also operate without elements for frequency stabilization (like RC oscillator).
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Fig. 0-27 Timers/Counters same width, which makes them ideal for time measurement. Such oscillators are used in quartz watches. If it is necessary to measure time between two events, it is sufficient to count pulses coming from this oscillator. That is exactly what the timer does. Most programs use these miniature electronic “stopwatches”.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers subtraction T2-T1). If the registers use pulses coming from external source then such a timer is turned into a counter. This is only a simple explanation of the operation itself. How does a timer operate? In practice pulses coming from the quartz oscillator are once per each machine cycle directly or via a prescaler brought to the circuit which increments the number in the timer register.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Fig. 0-29 Using prescaler in timer operating Using the interrupt in timer operation If the timer register consists of 8 bits, the largest number that can be written to it is 255 (for 16-bit registers it is the number 65.535). If this number is exceeded, the timer will be automatically reset and counting will start from zero again. This condition is called overflow.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Fig. 0-30 Using the interrupt in timer operation This figure illustrates the use of the interrupt in timer operation. Delays of arbitrary duration with minimal interference by the main program execution can be easily obtained by assigning a prescaler to the timer. Counters If a timer is supplying pulses into the microcontroller input pin then it turns into a counter.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Fig. 0-31 Watchdog Timer A/D Converter External signals are usually fundamentally different from those the microcontroller understands (Ones and Zeros), so that they have to be converted in order for the microcontroller to understand them. An analogue to digital converter is an electronic circuit which converts continuous signals to discrete digital numbers.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Fig. 0-32 A/D Converter Internal Architecture All upgraded microcontrollers use one of two basic design models called Harvard and von-Neumann architecture. Briefly, they are two different ways of data exchange between CPU and memory. von-Neumann Architecture http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Microcontrollers using this architecture have only one memory block and one 8-bit data bus. As all data are exchanged by using these 8 lines, this bus is overloaded and communication itself is very slow and inefficient. The CPU can either read an instruction or read/write data from/to the memory. Both cannot occur at the same time since the instructions and data use the same bus system.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers contains information upon WHICH data it should be done). However, it is not a hard and fast rule, but the most common case. In microcontrollers with Harvard architecture, the program bus is wider than one byte, which allows each program word to consist of instruction and data. In other words: one program word- one instruction.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers Remember learning to ride a bicycle: after several unavoidable bruises at the beginning, you will manage to keep balance and will be able to easily ride any other bicycle.
mikroElektronika | Free Online Book | PIC Microcontrollers | Introduction: World of Microcontrollers As seen in the table on the previous page, excepting “16-bit monsters”- PIC 24FXXX and PIC 24HXXX- all PIC microcontrollers have 8-bit harvard architecture and belong to one out of three large groups. Therefore, depending on the size of a program word there are first, second and third category, i.e. 12-, 14- or 16-bit microcontrollers.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Chapter 1: PIC16F887 Microcontroller - Device Overview The PIC16F887 is one of the latest products from Microchip. It features all the components which modern microcontrollers normally have.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview ❍ ● ● ● ● ● ● 10-bit resolution 3 independent timers/counters Watch-dog timer Analogue comparator module with ❍ Two analogue comparators ❍ Fixed voltage reference (0.6V) ❍ Programmable on-chip voltage reference PWM output steering control Enhanced USART module ❍ Supports RS-485, RS-232 and LIN2.0 ❍ Auto-Baud Detect Master Synchronous Serial Port (MSSP) ❍ supports SPI and I2C mode Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview Fig. 1-2 PIC16F887 QFN 44 Microcontroller http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview Fig. 1-3 PIC16F887 Block Diagram Pin Description As seen in Fig. 1-1 above, the most pins are multi-functional.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview Table 1-1 Pin Assignment http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview Table 1-1 cont. Pin Assignment http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview Table 1-1 cont. Pin Assignment Central Processor Unit (CPU) I’m not going to bore you with the operation of the CPU at this stage, however it is important to state that the CPU is manufactured with in RISC technology an important factor when deciding which microprocessor to use.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview the PC and a simple electronic device called the Programmer. Fig. 1-5 ROM Memory Consept EEPROM Memory Similar to program memory, the contents of EEPROM is permanently saved, even the power goes off. However, unlike ROM, the contents of the EEPROM can be changed during operation of the microcontroller.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview Fig. 1-6 SFR and General Purpose Registers General-Purpose Registers General-Purpose registers are used for storing temporary data and results created during operation. For example, if the program performs a counting (for example, counting products on the assembly line), it is necessary to have a register which stands for what we in everyday life call “sum”.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview function of each port A pin can be changed in a way it acts as input or output. Another feature of these memory locations is that they have their names (registers and their bits), which considerably facilitates program writing.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview Table 1-3 SFR Bank 0 http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview Table 1-4 SFR Bank 1 http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview Table 1-5 SFR Bank 2 Table 1-6 SFR Bank 3 STACK A part of the RAM used for the stack consists of eight 13-bit registers. Before the microcontroller starts to execute a subroutine (CALL instruction) or when an interrupt occurs, the address of first next instruction being currently executed is pushed onto the stack, i.e. onto one of its registers.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 1: PIC16F887 Microcontroller - Device Overview pushed eight times, the ninth push overwrites the value that was stored with the first push. The tenth push overwrites the second push and so on. Data overwritten in this way is not recoverable. In addition, the programmer cannot access these registers for write or read and there is no Status bit to indicate stack overflow or stack underflow conditions.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Chapter 2: Core SFRs Features and Function The special function registers can be classified into two categories: ● ● Core (CPU) registers - control and monitor operation and processes in the central processor.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs not affect any Status bits (C, DC and Z). Refer to “Instruction Set Summary”. ● ● IRP - Bit selects register bank. It is used for indirect addressing. ❍ 1 - Banks 0 and 1 are active (memory location 00h-FFh) ❍ 0 - Banks 2 and 3 are active (memory location 100h-1FFh) RP1,RP0 - Bits select register bank. They are used for direct addressing.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs ● ❍ ❍ RBPU - Port B Pull up Enable bit. 1 - PortB pull-ups are disabled. 0 - PortB pull-ups are enabled. Fig.2-3 ● ❍ ❍ INTEDG - Interrupt Edge Select bit. 1 - Interrupt on rising edge of RB0/INT pin. 0 - Interrupt on falling edge of RB0/INT pin. Fig.2-4 ● ❍ ❍ T0CS - TMR0 Clock Source Select bit. 1 - Transition on TOCKI pin. 0 - Internal instruction cycle clock (Fosc/4). Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs 1 1 1 1 0 1 1:128 1:256 1:64 1:128 Table 2-2 In order to achieve 1:1 prescaler rate when the timer TMR0 counts up pulses, the prescaler should be assigned to the WDT.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs Fig. 2-9 Interrupt SFRs INTCON Register The INTCON register contains various enable and flag bits for TMR0 register overflow, PORTB change and external INT pin interrupts. Fig. 2-10 INTCON Register ● ● GIE - Global Interrupt Enable bit - controls all possible interrupt sources simultaneously. ❍ 1 - Enables all unmasked interrupts. ❍ 0 - Disables all interrupts.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs that it does not affect interrupts triggered by the timer TMR0 or by changing state on port B or RB0/INT pin. ❍ 1 - Enables all unmasked peripheral interrupts. ❍ 0 - Disables all peripheral interrupts. ● ● ● ● ● ● T0IE - TMR0 Overflow Interrupt Enable bit controls interrupt enabled by TMR0 overflow. ❍ 1 - Enables the TMR0 interrupt. ❍ 0 - Disables the TMR0 interrupt.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs ● ● ● ● SSPIE - Master Synchronous Serial Port (MSSP) Interrupt Enable bit - enables an interrupt request to be generated after each data transfer via synchronous serial communication module (SPI or I2C mode). ❍ 1 - Enables the MSSP interrupt. ❍ 0 - Disables the MSSP interrupt. CCP1IE - CCP1 Interrupt Enable bit enables an interrupt request to be generated in CCP1 module used for PWM signal processing.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs ❍ ❍ 1 - Enables CCP2 interrupt. 0 - Disables CCP2 interrupt. PIR1 Register The PIR1 register contains the interrupt flag bits. Fig. 2-13 PIR1 Register ● ● ● ● ● ● ● ADIF - A/D Converter Interrupt Flag bit. ❍ 1 - A/D conversion is completed (bit must be cleared in software). ❍ 0 - A/D conversion is not completed or has not started. RCIF - EUSART Receive Interrupt Flag bit. ❍ 1 - The EUSART receive buffer is full.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs Fig. 2-14 PIR2 register ● ● ● ● ● ● ● OSFIF - Oscillator Fail Interrupt Flag bit. ❍ 1 - System oscillator failed and clock input has changed to internal oscillator INTOSC. This bit must be cleared in software. ❍ 0 - System oscillator operates normally. C2IF - Comparator C2 Interrupt Flag bit. ❍ 1 - Comparator C2 output has changed (bit C2OUT). This bit must be cleared in software.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs Fig. 2-15 PCON register ● ● ● ● ULPWUE - Ultra Low-Power Wake-up Enable bit ❍ 1 - Ultra Low-Power Wake-up enabled. ❍ 0 - Ultra Low-Power Wake-up disabled. SBOREN - Software BOR Enable bit ❍ 1 - Brown-out Reset enabled. ❍ 0 - Brown-out Reset disabled. POR - Power-on Reset Status bit ❍ 1 - No Power-on reset has occurred. ❍ 0 - Power-on reset has occurred. This bit must be set in software after a Power-on Reset occurs.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs jump to the subroutine PP2 address. Fig. 2-17 PCLATH Registers In both cases, when the subroutine reaches instructions RETURN, RETLW or RETFIE (to return to the main program), the microcontroller will simply continue program execution from where it left off because the return address is pushed and saved onto the stack which, as mentioned, consists of 13-bit registers.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 2: Core SFRs Fig. 2-18 Direct and Indirect addressing Previous Chapter | Table of Contents | Next Chapter http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 3: I/O Ports ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Chapter 3: I/O Ports Features and Functions One of the most important feature of the microcontroller is a number of input/output pins used for connection with peripherals.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 3: I/O Ports Fig. 3-1 I/O Ports Port A and TRISA Register Port A is an 8-bit wide, bidirectional port. Bits of the TRISA and ANSEL control the PORTA pins. All Port A pins act as digital inputs/outputs. Five of them can also be analog inputs (denoted as AN): http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 3: I/O Ports Fig. 3-2 Port A and TRISA Register Similar to bits of the TRISA register which determine which of the pins will be configured as input and which as output, the appropriate bits of the ANSEL register determine whether the pins will act as analog inputs or digital inputs/outputs.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 3: I/O Ports Theoretically, this is a perfect solution. The problem is that all pins able to cause an interrupt in this way are digital and have relatively large leakage current when their voltage is not close to the limit values Vdd (1) or Vss (0). In this case, the capacitor is discharged for a short time since the current amounts to several hundreds of microamperes.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 3: I/O Ports Fig. 3-6 WPUB register Having a high level of resistance (several tens of kilo ohms), these “virtual” resistors do not affect pins configured as outputs, but serves as a useful complement to inputs. As such, they are connected to CMOS logic circuit inputs. Otherwise, they would act as if they are floating because of their high input resistance. Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 3: I/O Ports Fig. 3-8 IOCB register Because of these features, the port B pins are commonly used for checking push-buttons on the keyboard because they unerringly register any button press. Therefore, there is no need to “scan” these inputs all the time. Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 3: I/O Ports voltages is applied first, are beside the point, the programmers electronics are in charge of that. The point is that the program can be loaded to the microcontroller even when it is soldered onto the target device. Normally, the loaded program can also be changed in the same way. This function is called ICSP (In-Circuit Serial Programming). It is necessary to plan ahead when using it.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 3: I/O Ports Fig. 3-13 Port D and TRISD Register Port E and TRISE Register Port E is a 4-bit wide, bidirectional port. The TRISE register’s bits determine the function of its pins. Similar to other ports, a logic one (1) in the TRISE register configures the appropriate port pin as input. The exception is RE3 which is input only and its TRIS bit is always read as ‘1’. Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 3: I/O Ports Fig. 3-15 ANSEL and ANSELH Registers The rule is: To configure a pin as an analog input, the appropriate bit of the ANSEL or ANSELH registers must be set (1). To configure pin as digital input/output, the appropriate bit must be cleared (0). The state of the ANSEL bits has no affect on digital output functions. The result of any attempt to read some port pin configured as analog input will be 0. Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 3: I/O Ports there is to know about these Ports. However, they are probably the simplest modules within the microcontroller. This is how they are used: ● ● ● ● ● When designing a device, select a port through which the microcontroller will communicate to the peripheral environment. If you intend using only digital inputs/outputs, select any port you want.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Chapter 4: Timers The timers of the PIC16F887 microcontroller can be briefly described in only one sentence. There are three completely independent timers/counters marked as TMR0, TMR1 and TMR2. But it’s not as simple as that.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers Fig. 4-1 Timer TMR0 OPTION_REG Register Fig. 4-2 OPTION_REG Register ● ● ● RBPU - PORTB Pull-up enable bit ❍ 0 - PORTB pull-up resistors are disabled; and ❍ 1 - PORTB pins can be connected to pull-up resistors. INTEDG - Interrupt Edge Select bit ❍ 0 - Interrupt on rising edge of INT pin (0-1); and ❍ 1 - Interrupt on falling edge of INT pin (1-0).
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers ❍ ● ● ● 1 - Internal cycle clock (Fosc/4). T0SE - TMR0 Source Edge Select bit ❍ 0 - Increment on high-to-low transition on TMR0 pin; and ❍ 1 - Increment on low-to-high transition on TMR0 pin. PSA - Prescaler Assignment bit ❍ 0 - Prescaler is assigned to the WDT; and ❍ 1 - Prescaler is assigned to the TMR0 timer/counter.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers Fig. 4-4 The function of the PSA bit 1 As seen, the logic state of the PSA bit determines whether the prescaler is to be assigned to the timer/counter or watchdog timer.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers BANKSEL CLRWDT BANKSEL MOVLW ANDWF TMR0 IORLW MOVWF b’00000011’ OPTION_REG ;CLEAR WDT AND PRESCALER OPTION_REG b’11110000’ OPTION_REG,W ;SELECT ONLY BITS PSA,PS2,PS1,PS0 ;CLEAR THEM AFTERWARDS BY INSTRUCTION ;“LOGICAL AND” ;PRESCALER RATE IS 1:16 In order to use TMR0 properly, it is necessary: To select mode: ● Timer mode is selected by the T0CS bit of the OPTION_REG register, (T0CS: 0=timer, 1=counter); ● When used, the p
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers Fig. 4-6 Timer TMR1 Overview Timer TMR1 Prescaler Timer TMR1 has a completely separate prescaler which allows 1, 2, 4 or 8 divisions of the clock input. The prescaler is not directly readable or writable. However, the prescaler counter is automatically cleared upon write to the TMR1H or TMR1L register.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers Fig. 4-7 Timer TMR1 Oscillator Timer TMR1 Gate Timer 1 gate source is software configurable to be the T1G pin or the output of comparator C2. This gate allows the timer to directly time external events using the logic state on the T1G pin or analog events using the comparator C2 output. Refer to figure 4-7 above. In order to time a signals duration it is sufficient to enable such gate and count pulses having passed through it.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers Fig. 4-9 Timer TMR1 Oscillator In order to solve this problem, a completely independent Low Power quartz oscillator, able to operate in sleep mode, is built into the PIC16F887 microcontroller. Simply, what previously has been a separate circuit, it is now built into the microcontroller and assigned to the timer TMR1. The oscillator is enabled by setting the T1OSCEN bit of the T1CON register.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers Fig. 4-11 Counter Mode This counter registers a logic one (1) on input pins. It is important to understand that at least one falling edge must be registered prior to the first increment on rising edge. Refer to figure on the left. The arrows in figure 4-11 denote counter increments. T1CON Register Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers T1CKPS1, T1CKPS0 - Timer1 Input Clock Prescale Select bits determine the rate of the prescaler assigned to the timer TMR1. T1CKPS1 T1CKPS0 Prescaler Rate 0 0 1:1 0 1 1:2 1 0 1:4 1 1 1:8 Table 4-2 Prescaler Rate T1OSCEN - LP Oscillator Enable Control bit ● ● 1 - LP oscillator is enabled for timer TMR1 clock (oscillator with low power consumption and frequency 32.768 kHz); and 0 - LP oscillator is off.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers Fig. 4-13 Timer TMR2 The pulses from the quartz oscillator first pass through the prescaler whose rate may be changed by combining the T2CKPS1 and T2CKPS0 bits. The output of the prescaler is then used to increment the TMR2 register starting from 00h. The values of TMR2 and PR2 are constantly compared and the TMR2 register keeps on being incremented until it matches the value in PR2.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 4: Timers TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 Postscaler Rate 0 0 0 0 1:1 0 0 0 1 1:2 0 0 1 0 1:3 0 0 1 1 1:4 0 1 0 0 1:5 0 1 0 1 1:6 0 1 1 0 1:7 0 1 1 1 1:8 1 0 0 0 1:9 1 0 0 1 1:10 1 0 1 0 1:11 1 0 1 1 1:12 1 1 0 0 1:13 1 1 0 1 1:14 1 1 1 0 1:15 1 1 1 1 1:16 Table 4-3 Postscaler Rate TMR2ON - Timer2 On bit turns the timer TMR2 on.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Chapter 5: CCP Modules The abbreviation CCP stands for Capture/Compare/PWM. The CCP module is a peripheral which allows the user to time and control different events. Capture Mode, allows timing for the duration of an event.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules Fig. 5-1 CCP1 Module In Compare mode, if enabled by software, the timer TMR1 reset may occur on match. Besides, the CCP1 module can generate PWM signals of varying frequency and duty cycle. Bits of the CCP1CON register controls the CCP1 module.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules bit enabling CCP1IE interrupt and flag bit CCP1IF should be cleared prior to any change occuring in the control register. Undesirable interrupt may be also generated by switching from one capture prescaler to another. To avoid this, the CCP1 module should be temporarily switched off before changing the prescaler.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules Fig. 5-4 CCP1 in PWM mode Another example, common in practice, is the usage of PWM signals in the circuit for generating signals of arbitrary waveforms, for example, sinusoidal waveform. See figure 5-5 below: Fig. 5-5 CCP1 in PWM mode with filtration Devices which operate in this way are often used in practice as switching regulators which control the operation of motors (speed, acceleration, deceleration etc.).
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules Fig. 5-6 PWM module The figure above shows the block diagram of the CCP1 module setup in PWM mode. In order to generate a pulse of arbitrary form on its output pin, it is necessary to determine only two values- pulse frequency and duration. Fig.5-7 PWM Mode PWM Period The output pulse period (T) is specified by the PR2 register of the timer TMR2.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules by equation F=1/T. PWM Duty Cycle The PWM duty cycle is specified by using in total of 10 bits: eight MSbs found in the CCPR1L register and two additional LSbs found in the CCP1CON register (DC1B1 and DC1B0).
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules Fig. 5-8 CCP1CON Register P1M1, P1M0 - PWM Output Configuration bits - In all modes, excepting PWM, the P1A pin is Capture/Compare module input. P1B, P1C and P1D pins act as input/output port D pins. In PWM mode, these bits affect the CCP1 module as shown in the table 5-4 below: P1M1 P1M0 0 0 0 1 1 0 1 1 Mode PWM with single output Pin P1A outputs modulated signal.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules 1 0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1 Every 16th rising edge on the CCP1 pin Compare mode Output and CCP1IF bit are set on match Compare mode Output is cleared and CCP1IF bit is set on match Compare mode Interrupt request arrives and bit CCP1IF is set on match Compare mode Bit CCP1IF is set and timers 1 or 2 registers are cleared PWM mode Pins P1A and P1C are active-
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules Similar to the pervious module, this circuit is under control of the bits of the control register. This time, it is the CCP2CON register. CCP2CON Register Fig. 5-10 CCP2CON Register DC2B1, DC2B0 - PWM Duty Cycle Least Significant bits - are only used in PWM mode representing two least significant bits of a 10-bit number. This number determines PWM signal’s duty cycle.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules In order to setup the CCP module for PWM operation, the following steps should be taken: ● ● ● ● ● ● Disable the CCP1 output pin.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules In this mode, the PWM signal is output on the P1A pin, while at the same time the complementary PWM signal is output on the P1B pin. Such pulses activate MOSFET drivers in Half-Bridge mode which enable/disable current flow through device. Fig. 5-12 Half-Bridge Mode In relation to this circuit, it is very dangerous to switch on both MOSFET drivers simultaneously. The short circuit caused in that moment will be fatal.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules Fig. 5-14 Activate MOSFET drivers Full-Bridge Mode In Full-Bridge mode, all four pins are used as outputs. In practice, this mode is commonly used to run motors, which provides simple and complete control of speed and rotation direction. There are two such configurations: Full BridgeForward and Full Bridge-Reverse. Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules Figure below shows the state of the P1A-P1D pins during one full PWM cycle. Fig. 5-16 Forward Mode Full Bridge - Reverse Configuration The same occurs in Reverse mode, except of the pins functions: ● ● ● Logic one (1) appears on the P1C pin (pin is active-high); Pulse sequence appears on the P1B pin; and Logic zero (0) appears on the P1A and P1D pins (pins are active-low). Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules Fig. 5-18 PWM1CON Register PSTRCON Register STRSYNC - Steering Sync bit determines the moment of PWM pulse steering: ● ● 1 - Steering occurs upon the PSTRCON has been changed, but only if a PWM waveform is completed; and 0 - Steering occurs upon the PSTRCON register has been changed. The PWM signal on output pin is immediately changed with no regard to whether the previous cycle is completed or not.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 5: CCP Modules ECCPASE - ECCP Auto-Shutdown Event Status bit indicates whether shut-down of CCP module has occurred (Shutdown state): 1 - CCP module is in Shutdown state; and 0 - CCP module operates normally.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Chapter 6: Serial Communication Modules EUSART The Enhanced Universal Synchronous Asynchronous Receiver Transmitter (EUSART) module is a serial I/O communication peripheral. It is also known as Serial Communications Interface (SCI).
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules EUSART Asynchronous Mode The EUSART transmits and receives data using standard non-return-to-zero (NRZ) format. As seen in figure 6-2 below, this mode does not use clock signal, while the data format being transferred is very simple: Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules SPEN = 1 - By setting this bit of the RCSTA register, EUSART is enabled and the TX/CK pin is automatically configured as output. If this bit is simultaneously used for some analog function, it must be disabled by clearing the corresponding bit of the ANSEL register. The central part of the EUSART transmitter is the shift register TSR which is not directly accessible by the user.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules When this first and necessary step is accomplished and START bit is detected, data is transferred to the shift register RSR through the RX pin. When the STOP bit has been received, the following occurs: ● ● ● ● ● Data is automatically transferred to the RCREG register (if empty); The flag bit RCIF is set and an interrupt, if enabled by the RCIE bit of the PIE1 register, occurs.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Fig. 6-5 Receiving 9-bit Data Address Detection When the ADDEN bit of the RCSTAregister is set, the EUSART module is able to receive only 9-bit data, whereas all 8-bit data will be ignored. Although it seems like a restriction, such modes enable serial communication between several microcontrollers. The principle of operation is simple.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules device should set the ADDEN bit in order to enable new address detection. Fig. 6-7 Sending Data TXSTA Register Fig.6-8 TXSTA Register CSRC - Clock Source Select bit - determines clock source. It is used only in synchronous mode. ● ● 1 - Master mode. Clock is generated internally from Baud Rate Generator; and 0 - Slave mode. Clock is generated from external source.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules SENDB - Send Break Character bit is only used in asynchronous mode and only in case it is required to observe LIN bus standard. ● ● 1 - Sending Break character is enabled; and 0 - Break character transmission is completed. BRGH - High Baud Rate Select bit determines baud rate in asynchronous mode. It does not affect EUSART in synchronous mode.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules ● ● 1 - Enables continuous receive until the CREN bit is cleared; and 0 - Disables continuous receive. ADDEN - Address Detect Enable bit is only used in address detect mode. ● ● 1 - Enables address detection on 9-bit data receive; and 0 - Disables address detection. The ninth bit can be used as parity bit. FERR - Framing Error bit ● ● 1 - On receive, Framing Error is detected; and 0 - No framing error.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules and BRGH16 bits in order to obtain some of the standard baud rates. The formulas used to determine the Baud Rate are: http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Table 6-2 Determining Baud Rate BAUDCTL Register http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Fig. 6-11 BAUDCTL Register ABDOVF - Auto-Baud Detect Overflow bit is only used in asynchronous mode during baud rate detection. ● ● 1 - Auto-baud timer overflowed; and 0 - Auto-baud timer did not overflow. RCIDL - Receive Idle Flag bit is only used in asynchronous mode. ● ● 1 - Receiver is idle; and 0 - START bit has been received and receiving is in progress.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules 5. If needed the bit TXEN causes an interrupt, the GIE and PEIE bits of the INTCON register should be set; 6. On 9-bit data transmission, value of the ninth bit should be written to the TX9D bit of the TXSTA register; and 7. Transmission starts by writing 8-bit data to the TXREG register. Receiving data via asynchronous EUSART communication: 1.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Fig.6-12 MSSP Module SPI Mode The SPI mode allows 8 bits of data to be transmitted and received simultaneously using 3 input/output lines: ● ● ● SDO - Serial Data Out - transmit line; SDI - Serial Data In - receive line; and SCK - Serial Clock - synchronization line.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Fig. 6-13 SPI Mode As seen in figure 6-14, the central part of the SPI module consists of two registers connected to pins for receive, transmit and synchronization. Shift register (SSPRS) is directly connected to the microcontroller pins and used for data transmission in serial format. The SSPRS register has its input and output and shifts the data in and out of device.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Step 1. Data to transmit should be written to the buffer register SSPBUF. Immediately after that, if the SPI module operates in master mode, the microcontroller will automatically perform the following steps 2, 3 and 4. If the SPI module operates as Slave, the microcontroller will not perform these steps until the SCK pin detects clock signal. Fig. 6-15 Step 1 Step 2.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules frequency (so called high-speed I²C bus), but the clock frequency of the most frequently used protocol is limited to 100 KHz. There is no limit in case of minimal frequency. When master and slave components are synchronized by the clock, every data exchange is always initialized by master. Once the MSSP module has been enabled, it waits for a Start condition to occur.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Fig. 6-21 Data Transfer Figure below shows the block diagram of the MSSP module in I²C mode. http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Fig. 6-22 MSSP Block Diagram in I²C Mode The MSSP module uses six registers for I²C operation. Some of them are shown in figure above: ● ● ● ● ● ● SSPCON; SSPCON2; SSPSTAT; SSPBUF; SSPSR; and SSPADD. SSPSTAT Register Fig. 6-23 SSPSTAT Register SMP Sample bit SPI master mode - This bit determines input data phase.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules CKP = 1: ● ● 1 - Data is transmitted on falling edge of clock pulse (1 - 0); and 0 - Data is transmitted on rising edge of clock pulse (0 - 1). D/A - Data/Address bit is used in I²C mode only. ● ● 1 - Indicates that the last byte received or transmitted was data; and 0 - Indicates that the last byte received or transmitted was address. P - Stop bit is used in I²C mode only.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Fig. 6-24 SSPCON Register WCOL Write Collision Detect bit ● ● 1 - Collision detected. A write to the SSPBUF register was attempted while the I²C conditions were not valid for a transmission to start; and 0 - No collision. SSPOV Receive Overflow Indicator bit ● ● 1 - A new byte is received while the SSPSR register still holds the previous data.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules SSPCON2 Register Fig. 6-25 SSPCON2 Register GCEN - General Call Enable bit In I²C slave mode only ● 1 - Enables interrupt when a general call address (0000h) is received in the SSPSR; and ● 0 - General call address disabled. ACKSTAT - Acknowledge Status bit In I²C Master Transmit mode only ● 1 - Acknowledge was not received from slave; and ● 0 - Acknowledge was received from slave.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules SEN - START Condition Enabled/Stretch Enabled bit In I²C Master mode only ● 1 - Initiate START condition on pins SDA and SCL. Afterwards, this bit is automatically cleared by hardware; and ● 0 - START condition is not initiated. I²C in Master Mode The most common case is when the microcontroller operates as a master and the peripheral component as a slave. This is why this book covers just this mode.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Since maximum 112 integrated circuits may simultaneously share the same transmission line, the first data byte must contain address which matches only one slave device. Each component has its own address listed in the proper data sheet. The eighth bit of the first data byte specifies direction of data transmission, the microcontroller is to send or receive data.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Fig. 6-30 Data Reception in I²C Master Mode Start - Address - Acknowledge - Data - Acknowledge .... Data - Acknowledge - Stop! In this pulse condition, the acknowledge bit is sent to slave device. Baud Rate Generator In order to synchronize data transmission, all events taking place on the SDA pin must be synchronized with the clock generated in master device.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules Fig. 6-31 Baud Rate Generator Useful notes ... When the microcontroller communicates with peripheral components, it may happen that data transfer fails for some reason. In that case, it is recommended to check the status of some bits which can clarify the problem. In practice, the state of these bits is checked by executing a short subroutine after each byte transmission and reception (just in case).
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 6: Serial Communication Modules In Short: In order to establish serial communication in I²C mode, the following should be done: Setting Module and Sending Address: ● Value to determine baud rate should be written to the SSPADD register; ● SlewRate control should be turned off by setting the SMP bit of the SSPSTAT register; ● In order to select Master mode, binary value 1000 should be written to the SSPM3-SSPM0 bits of the SSPCON1 register
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Chapter 7: Analog Modules Apart from a large number of digital I/O lines, the PIC16F887 contains 14 analog inputs.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules Fig. 7-1 ADC Mode and Registers The module is under the control of the bits of four registers: ● ● ● ● ADRESH - Contains high byte of conversion result; ADRESL - Contains low byte of conversion result; ADCON0 - Control register 0; and ADCON1 Control register 1 ADRESH and ADRESL Registers When converting an analog value into a digital one, the result of the 10-bit A/D conversion will be stored in these two registers.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules Fig. 7-2 ADRESH and ADRESL Registers A/D Acquisition Requirements For the ADC to meet its specified accuracy, it is necessary to provide a certain time delay between selecting specific analog input and measurement itself. This time is called "acquisition time" and mainly depends on the source impedance. There is an equation used for accurately calculating this time, which in the worst case amounts to approximately 20uS.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules Roughly speaking, voltage measurement in the converter is based on comparing input voltage with internal scale which has 1024 marks (210=1024). The lowest scale mark stands for the Vref- voltage, whilst the highest mark stands for the Vref+ voltage. Figure 7-3 below shows selectable referent voltages and their minimum and maximum values as well. ● Fig. 7-3 How to Use The A/D Converter ADCON0 Register Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules CHS3 CHS2 CHS1 CHS0 Channel Pin 0 0 0 0 0 RA0/AN0 0 0 0 1 1 RA1/AN1 0 0 1 0 2 RA2/AN2 0 0 1 1 3 RA3/AN3 0 1 0 0 4 RA5/AN4 0 1 0 1 5 RE0/AN5 0 1 1 0 6 RE1/AN6 0 1 1 1 7 RE2/AN7 1 0 0 0 8 RB2/AN8 1 0 0 1 9 RB3/AN9 1 0 1 0 10 RB1/AN10 1 0 1 1 11 RB4/AN11 1 1 0 0 12 RB0/AN12 1 1 0 1 13 RB5/AN13 1 1 1 0 CVref 1 1 1 1 Vref = 0.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules ● ● 1 - Negative voltage reference is applied on the Vref- pin; and 0 - Voltage power supply Vss is used as negative voltage reference source. VCFG0 - Voltage Reference bit selects positive voltage reference source needed for A/D converter operating. ● ● 1 - Positive voltage reference is applied on the Vref+ pin; and 0 - Voltage power supply Vdd is used as positive voltage reference source.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules Fig. 7-6 Analog Comparator ● ● When the analog voltage at Vin- is higher than the analog voltage at Vin+, the output of the comparator is a digital low level; and When the analog voltage at Vin+ is higher than the analog voltage at Vin-, the output of the comparator is a digital high level.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules Fig. 7-7 VREF The comparator voltage reference has 2 ranges with 16 voltage levels in each range. Range selection is controlled by the VRR bit of the VRCON register. The selected voltage reference may be output to the RA2/AN2 pin. Even though the main idea was to obtain varying voltage reference for the operation of analog modules, a simple A/D converter is obtained in that way too.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules Fig. 7-8 CM1CON0 Regsiter Bits of this register are in control of the comparator C1. It mainly affects configuration of its inputs. To understand it better, look at figure 7-9 below which shows only a part of electronics directly affected by the bits of this register. Fig. 7-9 Comparator C1 Enable Bit C1ON - Comparator C1 Enable bit enables comparator C1.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules 1 - Comparator C1OUT output is connected to the C1OUT pin.*; and 0 - Comparator output is internal only. ● ● * In order to enable the C1OUT bit to be present on the pin, two conditions must be met: C1ON = 1 (comparator must be on) and the corresponding TRIS bit = 0 (pin must be configured as output). C1POL - Comparator C1 Output Polarity Select bit enables comparator C1 out put state to be inverted.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules Fig. 7-11 Comparator C2 Schematic Diagram C2ON - Comparator C2 Enable bit enables comparator C2. ● ● 1 - Comparator C2 is enabled; and 0 - Comparator C2 is disabled. C2OUT - Comparator C2 Output bit is comparator C2 output. If C2POL = 1 (comparator output inverted) ● 1 - Analog voltage at C1Vin+ is lower than analog voltage at C1Vin-; and ● 0 - Analog voltage at C1Vin+ is higher than analog voltage at C1Vin-.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules C2CH1 C2CH0 Comparator C2Vin- input 0 0 Input C2Vin- is connected to the C12IN0- pin 0 1 Input C2Vin- is connected to the C12IN1- pin 1 0 Input C2Vin- is connected to the C12IN2- pin 1 1 Input C2Vin- is connected to the C12IN3- pin Table 7-5 Comparator C2 Channel Select Bit CM2CON1 Register Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules Fig. 7-13 VRCON Register VREN Comparator C1 Voltage Reference Enable bit ● ● 1 - Voltage reference CVref source is powered on; and 0 - Voltage reference CVref source is powered off. VROE Comparator C2 Voltage Reference Enable bit ● ● 1 - Voltage reference CVref is connected to the pin; and 0 - Voltage reference CVref is disconnected from the pin.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 7: Analog Modules Formula used to calculate voltage reference: VRR = 1 (low range) CVref = ([VR3:VR0]/24)VLADDER VRR = 0 (high range) CVref = (VLADDER/4) + ([VR3:VR0]VLADDER/32) Vladder = Vdd or ([Vref+] - [Vref-]) or Vref+ Step 3 - Starting operation: ● ● ● Enable interrupt by setting bits CMIE (PIE register), PEIE and GIE (both in the INTCON register); Read bits C1OUT and C2OUT of the CMCON register; and Read flag bit CMIF of the PIR r
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Chapter 8: Other MCU's Circuits As seen in figure below, clock signal may be generated by one of two built in oscillators. Fig. 8-1 Two built in oscillators http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits An External oscillator is installed within the microcontroller and connected to the OSC1 and OSC2 pins. It is called “external” because it relies on external circuitry for the clock signal and frequency stabilization, such as a stand-alone oscillator, quarts crystal, ceramic resonator or resistor-capacitor circuit. The oscillator mode is selected by bits of bytes sent during programming, so called Config Word.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits HTS - HFINTOSC Status bit (8 MHz - 125 kHz) indicates whether high-frequency internal oscillator operates in a stable way. ● ● 1 - HFINTOSC is stable; and 0 - HFINTOSC is not stable. LTS - LFINTOSC Stable bit (31 kHz) indicates whether low-frequency internal oscillator operates in a stable way. ● ● 1 - LFINTOSC is stable; and 0 - LFINTOSC is not stable.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits Fig.8-3 PICflash Program External oscillator in EC mode The external clock (EC) mode uses the system clock source configured from external oscillator. The frequency of this clock source is unlimited (0- 20MHz). Fig.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits Fig. 8-6 Two Types of External Oscillators The LP, XT and HS modes support the usage of internal oscillator for configuring clock source. The frequency of this source is determined by quartz crystal or ceramic resonators connected to the OSC1 and OSC2 pins. Depending on features of the component in use, select one of the following modes: LP mode (Low Power) is used for low-frequency quartz crystal only.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits Fig.8-8 Ceramic Resonator Ceramic resonators are by their features similar to quartz crystals. This is why they are connected in the same way. Unlike quartz crystals, they are cheaper and oscillators containing them have a bit worse characteristics. They are used for clock frequencies ranging between 100 kHz and 20 MHz.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits Similar to the external oscillator, the internal one can also operate in several modes. The mode is selected in the same way as in case of external oscillator- using bits of the Config Word register. In other words, everything is performed within PC software, immediately before program writing to the microcontroller starts.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits Fig. 8-13 Internal Oscillator settings 2. The low-frequency oscillator LFINTOSC is uncalibrated and operates at 31 kHz. It is enabled by selecting this frequency (bits of the OSCCON register) and setting the SCS bit of the same register. Two-Speed Clock Start-up Mode Two-Speed Clock Start-up mode is used to provide additional power savings when the microcontroller operates in sleep mode.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits Fig.8-14 Enable Int-Ext Switchover Fail-Safe Clock Monitor The Fail-Safe Clock Monitor (FSCM) monitors the operation of external oscillator and allows the microcontroller to proceed with program execution even the external oscillator fails for some reason. In this case, the internal oscillator takes over its role. http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits Fig. 8-15 Fail-Safe Clock Monitor The fail-safe clock monitor detects a failed oscillator by comparing the internal and external clock sources. In case it takes more than 2mS for the external oscillator clock to come, the clock source will be automatically switched. The internal oscillator will thereby continue operating controlled by the bits of the OSCCON register.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits Fig. 8-16 Enabling Fail-Safe Clock Monitor OSCTUNE Register Modifications in the OSCTUNE register affect the HFINTOSC frequency, but not the LFINTOSC frequency. Furthermore, there is no indication during operation that shift has occurred. Fig. 8-17 OSCTUNE Register TUN4 - TUN0 Frequency Tuning bits. By combining these five bits, the 8MHz oscillator frequency shifts.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits ● ● ● ● EECON1 (control register); EECON2 (control register); EEDAT (saves data ready for write and read); and EEADR (saves address of EEPROM location to be accessed). In addition, EECON2 is not true register, it does not physically exist. It is used in write program sequence only. The EEDATH and EEADRH registers belong to the same group as the registers used during EEPROM write and read.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits In order to read data EEPROM memory, follow the procedure below: Step Step Step Step 1: 2: 3: 4: Write an address (00h - FFh) to the EEADR register; Select EEPROM memory block by clearing the EEPGD bit of the EECON1 register; To read location, set the RD bit of the same register; and Data is stored in the EEDAT register and ready to use.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits When power supply voltage reaches 1.2 - 1.7V, a circuit called Power-up timer resets the microcontroller within approximately 72mS. Immediately upon this time has run out, the reset signal generates another timer called Oscillator start-up timer within 1024 quartz oscillator periods.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 8: Other MCU's Circuits This is a special kind of Brown-out reset which occurs in industrial environment when the power supply voltage “blinks” for a moment and drops its value beneath minimal level. Even short, such noise in power line may catastrophically affect the operation of device. Fig. 8-22 Noises MCLR pin Logic zero (0) on the MCLR pin causes immediate and regular reset.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Chapter 9: Instruction Set It has been already mentioned that microcontrollers differs from other integrated circuits. Most of them are ready for installation into the target device just as they are, this is not the case with the microcontrollers.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Arithmetic-logic Instructions ADDLW k Add W and constant W+k -> W C, DC, Z 1 ADDWF f,d Add W and f W+f -> d C, DC ,Z 1 SUBLW k Subtract W from constant k-W -> W C, DC, Z 1 SUBWF f,d Subtract W from f f-W -> d C, DC, Z 1 ANDLW k Logical AND with W with constant W AND k -> W Z 1 ANDWF f,d Logical AND with W with f W AND f -> d Z 1 1, 2 ANDWF f,d Logical AND with W with f W AND f -> d Z 1
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set RETFIE Return from interrupt TOS -> PC, 1 -> GIE 2 Other instructions NOP No operation TOS -> PC, 1 -> GIE 1 CLRWDT Clear watchdog timer 0 -> WDT, 1 -> TO, 1 -> PD TO, PD 1 SLEEP Go into sleep mode 0 -> WDT, 1 -> TO, 0 -> PD TO, PD 1 Table 9-1 16Fxx Instruction Set *1 When an I/O register is modified as a function of itself, the value used will be that value present on the pins themselves.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set The PIC16F887 executes instructions GOTO, CALL, RETURN in the same way as all other microcontrollers do. A difference is that stack is independent from internal RAM and has 8 levels. The ‘RETLW k’ instruction is identical to RETURN instruction, with exception that a constant defined by instruction operand is written to the W register prior to return from subroutine.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set f - Any memory location (register); W - Working register (accumulator); b - Bit address within an 8-bit register; d - Destination bit; [label] - Set of 8 characters indicating start of particular address in the program; TOS - Top of stack; [] - Option; <> - bit field in register (several bit addresses); C - Carry/Borrow bit of the STATUS register; DC - Digit Carry bit of the STATUS register; and Z - Zero bit of the STAT
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set If d = w or d = 0 the result is stored in the W register. If d = f or d = 1 the result is stored in register f. Operation: (W) + (f) -> d Operand: 0 ≤ f ≤ 127, d [0,1] Status affected: C, DC, Z Number of cycles: 1 EXAMPLE 1: .... [label] ADDWF REG,w Before instruction execution: W = 0x17 REG = 0xC2 After instruction: W = 0xD9 REG = 0xC2 C=0 (No carry occurs, i.e. the result is maximum 8-bit long). EXAMPLE 2: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Operation: (W) AND k -> W Operand: 0 ≤ k ≤ 255 Status affected: Z Number of cycles: 1 EXAMPLE 1: .... [label] ANDLW 0x5F Before instruction execution: W = 0xA3 ; 1010 0011 (0xA3) ; 0101 1111 (0x5F) -----------------After instruction: W = 0x03 ; 0000 0011 (0x03) Z = 0 (result is not 0) EXAMPLE 2: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Operation: (W) AND (f) -> d Operand: 0 ≤ f ≤ 127, d[0,1] Status affected: Z Number of cycles: 1 EXAMPLE 1: .... [label] ANDWF REG,f Before instruction execution: W = 0x17, REG = 0xC2 ; 0001 0111 (0x17) ; 1100 0010 (0xC2) -----------------After instruction: W = 0x17, REG = 0x02 ; 0000 0010 (0x02) EXAMPLE 2: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Operand: 0 ≤ f ≤ 127, 0 ≤ b ≤ 7 Status affected: Number of cycles: 1 EXAMPLE 1: .... [label] BCF REG,7 Before instruction execution: REG = 0xC7 ; 1100 0111 (0xC7) After instruction: REG = 0x47 ; 0100 0111 (0x47) EXAMPLE 2: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Status affected: Number of cycles: 1 EXAMPLE 1: .... [label] BSF REG,7 Before instruction execution: REG = 0x07 ; 0000 0111 (0x07) After instruction: REG = 0x87 ; 1000 0111 (0x87) EXAMPLE 2: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Number of cycles: 1 or 2 depending on bit b EXAMPLE: .... LAB_01 BTFSC REG,1 ; Test bit 1 of REG LAB_02 .... ; Skip this line if bit = 1 LAB_03 .... ; Jump here if bit = 0 Before instruction execution: The program counter was at address LAB_01. After instruction: - if bit 1 of REG is cleared, program counter points to address LAB_03. - if bit 1 of REG is set, program counter points to address LAB_02.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set LAB_01 After instruction: - if bit 3 of REG is cleared, program counter points to address LAB_03. - if bit 3 of REG is cleared, program counter points to address LAB_02. CALL - Calls Subroutine Syntax: [label] CALL k Description: Calls subroutine. First the address of the next instruction to execute is pushed onto the stack. It is the PC+1 address. Afterwards, the subroutine address is written to the program counter.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Operation: 0 -> f Operand: 0 ≤ f ≤ 127 Status affected: Z Number of cycles: 1 EXAMPLE 1: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set EXAMPLE 1: .... [label] CLRW Before instruction: W=0x55 After instruction: W=0x00 Z = 1 CLRWDT - Clear Watchdog Timer Syntax: [label] CLRWDT Description: Resets the watchdog timer and the WDT prescaler. Status bits TO and PD are set. Operation: 0 -> WDT 0 -> WDT prescaler 1 -> TO 1 -> PD Operand: Status affected: TO, PD Number of cycles: 1 EXAMPLE : ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Syntax: [label] COMF f, d Description: The content of register f is complemented (logic zeros (0) are replaced by ones (1) and vice versa). If d = w or d = 0 the result is stored in W. If d = f or d = 1 the result is stored in register f. Operation: (f) -> d Operand: 0 ≤ f ≤ 127, d[0,1] Status affected: Z Number of cycles: 1 EXAMPLE 1: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Syntax: [label] DECF f, d Description: Decrement register f by one. If d = w or d = 0, the result is stored in the W register. If d = f or d = 1, the result is stored in register f. Operation: (f) - 1 -> d Operand: 0 ≤ f ≤ 127, d[0,1] Status affected: Z Number of cycles: 1 EXAMPLE 1: .... [label] DECF REG,f Before instruction execution: REG = 0x01 Z = 0 After instruction: REG = 0x00 Z = 1 EXAMPLE 2: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set register. If d = f or d = 1, the result is stored in register f. If the result is 0, then a NOP is executed instead, making this a two-cycle instruction. Operation: (f) - 1 -> d Operand: 0 ≤ f ≤ 127, d[0,1] Status affected: Number of cycles: 1 or 2 depending on the result. EXAMPLE 1: .... MOVLW .10 MOVWF CNT Loop ...... ...... ...... DECFSZ CNT,f GOTO Loop LAB_03 .......
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set ..... ..... LAB_01 ..... ; Program continues from here Before instruction execution: PC = LAB_00 address After instruction: PC = LAB_01 address INCF - Increment f Syntax: [label] INCF f, d Description: Increment register f by one. If d = w or d = 0, the result is stored in register W. If d = f or d = 1, the result is stored in register f.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Before instruction execution: REG = 0xFF Z = 0 After instruction: REG = 0x00 Z = 1 INCFSZ - Increment f, Skip if 0 Syntax: [label] INCFSZ f, d Description: Register f is incremented by one. If d = w or d = 0, the result is stored in register W. If d = f or d = 1, the result is stored in register f. If the result is 0, then a NOP is executed instead, making this a two-cycle instruction.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Operand: 0 ≤ k ≤ 255 Status affected: Number of cycles: 1 EXAMPLE : .... [label] IORLW 0x35 Before instruction execution: W = 0x9A After instruction: W = 0xBF Z = 0 IORWF - Inclusive OR W with f Syntax: [label] IORWF f, d Description: The content of register f is OR’ed with the content of W register. If d = w or d = 0, the result is stored in the W register. If d = f or d = 1, the result is stored in register f.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set EXAMPLE 2: .... [label] IORWF REG,f Before instruction execution: REG = 0x13, W = 0x91 After instruction: REG = 0x93, W = 0x91 Z = 0 MOVF - Move f Syntax: [label] MOVF f, d Description: The content of register f is moved to a destination determined by the operand d. If d = w or d = 0, the content is moved to register W. If d = f or d = 1, the content remains in register f.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set EXAMPLE 2: .... [label] MOVF INDF,f Before instruction execution: W=0x17 FSR=0xC2, register at address 0xC2 contains the value 0x00 After instruction: W=0x17 FSR=0xC2, register at address 0xC2 contains the value 0x00, Z = 1 MOVLW - Move literal to W Syntax: [label] MOVLW k Description: 8-bit literal k is moved to register W. Operation: k -> (W) Operand: 0 ≤ k ≤ 255 Status affected: Number of cycles: 1 EXAMPLE 1: ...
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set [label] MOVLW Const Before instruction execution: W=0x10 After instruction: W=0x40 MOVWF - Move W to f Syntax: [label] MOVWF f Description: The content of register W is moved to register f. Operation: (W) -> f Operand: 0 ≤ f ≤ 127 Status affected: Number of cycles: 1 EXAMPLE 1: .... [label] MOVWF OPTION_REG Before instruction execution: OPTION_REG=0x20 W=0x40 After instruction: OPTION_REG=0x40 W=0x40 EXAMPLE 2: ..
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set the value 0x00 After instruction: W=0x17 FSR=0xC2, register at address 0xC2 contains the value 0x17 NOP - No Operation Syntax: [label] NOP Description: No operation. Operation: Operand: Status affected: Number of cycles: 1 EXAMPLE : ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set EXAMPLE : .... [label] RETFIE Before instruction execution: PC = x GIE (interrupt enable bit of the SATUS register) = 0 After instruction: PC = TOS (top of stack) GIE = 1 RETLW - Return with literal in W Syntax: [label] RETLW k Description: 8-bit literal k is loaded into register W. The value from the top of stack is loaded to the program counter.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set RETURN - Return from Subroutine Syntax: [label] RETURN Description: Return from subroutine. The value from the top of stack is loaded to the program counter. This is a two-cycle instruction. Operation: TOS -> program counter PC. Operand: Status affected: Number of cycles: 2 EXAMPLE : ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Fig. 9-1 f Register EXAMPLE 1: .... [label] RLF REG,w Before instruction execution: REG = 1110 0110 C = 0 After instruction: REG = 1110 0110 W = 1100 1100 C = 1 EXAMPLE 2: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Operation: (f(n)) -> d(n-1), f(0) -> C, C -> d(7); Operand: 0 ≤ f ≤ 127, d -> [0,1] Status affected: C Number of cycles: 1 Fig. 9-2 f Register EXAMPLE 1: .... [label] RRF REG,w Before instruction execution: REG = 1110 0110 W = x C = 0 After instruction: REG = 1110 0110 W = 0111 0011 C = 0 EXAMPLE 2: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set SLEEP - Enter Sleep mode Syntax: [label] SLEEP Description: The processor enters sleep mode. The oscillator is stopped. PD bit (Power Down) of the STATUS register is cleared. TO bit of the same register is set. The WDT and its prescaler are cleared. Operation: 0 -> WDT, 0 -> WDT prescaler, 1 -> TO, 0 -> PD Operand: Status affected: TO, PD Number of cycles: 1 EXAMPLE : ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set EXAMPLE : ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set After instruction: REG = 0, W = 2, C = 1, Z = 1 result is 0 Before instruction execution: REG = 1, W = 2, C = x, Z = x After instruction: REG = 0xFF, W = 2, C = 0, Z = 0 result is negative SWAPF - Swap Nibbles in f Syntax: [label] SWAPF f, d Description: The upper and lower nibbles of register f are swapped. If d = w or d = 0, the result is stored in register W. If d = f or d = 1, the result is stored in register f.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set XORLW - Exclusive OR literal with W Syntax: [label] XORLW k Description: The content of register W is XOR’ed with the 8-bit literal k . The result is stored in register W. Operation: (W) .XOR. k -> W Operand: 0 ≤ k ≤ 255 Status affected: Z Number of cycles: 1 EXAMPLE 1: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set Syntax: [label] XORWF f, d Description: The content of register f is XOR’ed with the content of register W. A bit of result is set only if the corresponding bits of operands are different. If d = w or d = 0, the result is stored in register W. If d = f or d = 1, the result is stored in register f. Operation: (W) .XOR. k -> d Operand: 0 ≤ f ≤ 127, d[0,1] Status affected: Z Number of cycles: 1 EXAMPLE 1: ....
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set combining already existing instructions.
mikroElektronika | Free Online Book | PIC Microcontrollers | Chapter 9: Instruction Set http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Appendix A: Programming a Microcontroller Microcontrollers and humans communicate through the medium of the programming language called Assembly language.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller A program written in assembly language consists of several elements being differently interpreted while compiling the program into an executable data file. The use of these elements requires strict rules and it is necessary to pay special attention to them during program writing in order to avoid errors.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller Instructions are defined for each microcontroller family by the manufacturer. Therefore, it is up to the user to follow the rules of their usage. The way of writing instructions is also called instruction syntax. The instructions "movlp" and "gotto", in the following example, are recognized by the PIC16F887 microcontroller as an error since they are not correctly written.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller EQU directive This directive is used to replace a numeric value by a symbol. In this way, some a specific location in memory is assigned a name. For example: MAXIMUM EQU H’25’ This means that a memory location at address 25 (hex.) is assigned the name "MAXIMUM". Every appearance of the label "MAXIMUM" in the program will be interpreted by the assembler as the address 25 (MAXIMUM = H’25’).
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller RIGHT ; address 0x24 ENDC ... IF, ENDIF and ELSE directives These directives are used to create so called conditional blocks in a program. Each of these blocks starts with the directive IF and ends with the directive ENDIF or ELSE.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller EXAMPLE OF HOW TO WRITE A PROGRAM The following example illustrates what a simple program written in assembly language looks like. Apart from the regular rules of assembly language, there are also some unwritten rules which should be observed during program writing.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller enough to use command "goto Main" in order to direct the microcontroller to the beginning of the program. The next command selects memory bank 1 in order to enable access to the TRISB register to configure port B as output (banksel TRISB). The main program ends by selecting memory bank 0 and setting all port B pins to logic one (1)(movlw 0xFF, movwf PORTB).
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller bank1 macro bsf STATUS, RP0 bcf STATUS, RP1 endm enableint macro bsf INTCON,7 endm disableint macro bcf INTCON,7 endm ; ; ; ; ; ; ; ; ; ; Macro bank1 Set RP0 bit Reset RP1 bit End of macro Global interrupt enable Set bit End of macro Global interrupt disable Reset bit End of macro Macros defined in this way are saved in a particular data file with extension INC which stands for INCLUDE data file.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller In the event that a macro has labels, they must be defined as local ones by using directive local. The given example contains macro which calls a subroutine (call label in this case) if the Carry bit of the STATUS register is set. Otherwise, the first following instruction is executed.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller Main Loop Add16 call goto clrf movf addwf movwf btfsc incf movf addwf addwf return end ; ; ; ; RESH ; ARG1L,w ; ARG2L,w ; RESL ; STATUS,C ; RESH,f ; Main program Call subroutine Add16 Remain here Subroutine to add two 16-bit numbers RESH=0 w=ARG1L w=w+ARG2L RESL=w Is the result greater than 255? If greater, increment RESH by one ARG1H,w ARG2H,w RESH,f w=ARG1H w=w+ARG2 RESH=w Return from subroutine En
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller Click on this icon to start up the process... Something is going on... The picture coming up indicates that the process of installation has just started! Next window contains the word "Welcome". Need explanation? Actually, the program reminds you to close all active programs in order to not interfere with the installation process.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller Do you want to install the entire software? Yes. Next... Similar to other programs, MPLAB should be also installed into a folder. It may be any folder on any hard disc. If it is not necessary to make changes, select the specified address and click Next. Another license, another acceptance of options specified by the computer... Next, Next... Be patient! http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller Finally! This is what you have been waiting for. Click Finish. The computer will be restarted along with the program saved on hard disc. Everything is OK! Click the MPLAB desktop icon in order to start the program and learn about it. As seen, MPLAB is similar to most Windows programs. Apart from the working area, there are menus (contains options: File, Edit etc.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller there is a rule to have shortcuts for the most commonly used program options created in order to easily access them and speed up operation therefore. These shortcuts are actually icons below the menu bar. In other words, all options contained in the toolbar are contained in the menu too. PROJECT-MAKING Follow these steps to prepare program for loading into the microcontroller: 1. Make a project; 2.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller Keep on project-making by clicking NEXT. Then select the microcontroller you will be using. In our case, it is PIC16F887 microcontroller. At the end, the project is assigned a name which usually indicates the purpose and the content of the program being written. The project should be moved to the desired folder. It is best that the folder associates with PIC microcontrollers (See figure).
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller Click FINISH to complete the project. The window itself contains project parameters. WRITING A NEW PROGRAM When the project is created, a window shown in figure below appears. http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller The next step is to write a program. Open a new document by clicking File>New. Text Editor in MPLAB environment appears. Save the document in the folder D:\PIC projects by using the File>Save As command and name it "Blink.asm" indicating that this program is to be an example of port diode blinking. Obviously you can locate you files wherever you wish, in whichever hard drive you wish.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller Click "Blink" to include the document Blink.asm into the project. Program writing example The program writing procedure cannot start until all previous operations have been performed. Program written below is a simple illustration of project-making. ;Program to set port B pins to logic one (1). ;Version: 1.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller SIMULATOR Asimulator is a part of MPLAB environment which provides better insight into the operation of the microcontroller. Generally speaking, a simulation is an attempt to model a real-life or hypothetical situation so that it can be studied to see how the system works. By means of the simulator, it is also possible to monitor current values of variables, registers and port pins states as well.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller Simulator is activated by clicking on DEBUGGER > SELECT TOOL > MPLAB SIM, as shown in figure. As a result, several icons related to the simulator only appear. Their meanings are as follows: Starts program execution at full speed. In this example, the simulator executes the program at full (normal) speed until it is halted by clicking the icon below. Pauses program execution.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix A: Programming a Microcontroller >FILE REGISTERS option. If the program contains variables, it is good to monitor their values as well. Each variable is assigned a window (Watch Windows) by clicking VIEW->WATCH option. If the program contains variables, it is good to monitor their values as well. Each variable is assigned a window (Watch Windows) by clicking VIEW->WATCH option.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Appendix B: Examples The purpose of this chapter is to provide basic information about microcontrollers that one needs to know in order to be able to use them successfully in practice.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Clearly, it is about simple circuits, but it does not have to always be like that. If the target device is used for controlling expensive machines or maintaining vital functions, everything gets more and more complicated! However, this solution is sufficient for the time being... POWER SUPPLY Even though the PIC16F887 can operate at different supply voltages, why to test "Murphy's low"?! A 5DC power supply is shown above.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Why are these modes so important? Owing to the fact that it is almost impossible to make a stable oscillator which operates over a wide frequency range, the microcontroller must know which crystal is connected in order that it can adjust the operation of its internal electronics to it. This is why all programs used for chip loading contains an option for oscillator mode selection. See above figure.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples These oscillators are used when it is not necessary to have extremely precise frequency. RC oscillator If the operating frequency is not of importance then there is no need for additional expensive components for stabilization. Instead, a simple RC network, as shown in the figure below, will be enough.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples It is about contact bounce- a common problem with mechanical switches. When the contacts strike together, their momentum and elasticity act together to cause bounce. The result is a rapidly pulsed electrical current instead of a clean transition from zero to full current. Generally, it mostly occurs due to vibrations, slight rough spots and dirt between contacts.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples the change, it means that a switch/push-button has changed its position. The advantages of such solution are obvious: it is free of charge, effects of noises are eliminated and it can be applied to the poorer quality contacts as well. RELAY A relay is an electrical switch that opens and closes under the control of another electrical circuit.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Quick burning Like any other diode, LEDs have two ends an anode and a cathode. Connect it properly to a power supply voltage. The diode will happily emit light. Turn it upside down and apply the same power supply voltage (even for a moment). It will not emit light- NEVER AGAIN! Slow burning There is a nominal, i.e. maximum current determined for every LED which should not be exceeded.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Here are a few important things that one should pay attention to when buying LED displays: ● ● ● Depending on whether anodes or cathodes are connected to the common pin, there are common anode displays and common cathode displays. The figure above shows a common anode display.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Here is an explanation on the figure above. First a byte representing units is applied on a microcontroller port and a transistor T1 is activated simultaneously. After a while, the transistor T1 is turned off, a byte representing tens is applied on a port and transistor T2 is activated. This process is being cyclically repeated at high speed for all digits and corresponding transistors.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Digits to display 0 1 2 3 4 5 6 7 8 9 dp 0 0 0 0 0 0 0 0 0 0 a 1 1 1 1 0 1 1 1 1 1 Display Segments b c d e 1 1 1 1 1 0 0 0 1 0 1 1 1 1 1 0 1 1 0 0 0 1 1 0 0 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 f 1 0 0 0 1 1 1 0 1 1 g 0 0 1 1 1 1 1 0 1 1 In addition to digits from 0 to 9, there are some letters- A, C, E, J, F, U, H, L, b, c, d, o, r, t- that can be also displayed by means of the appropriate masking.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples The R/C network represented by the broken line in the figure above denotes optional connection which lessens the effects of noises by eliminating very short pulses. LCD DISPLAY This component is specifically manufactured to be used with microcontrollers, which means that it cannot be activated by standard IC circuits. It is used for displaying different messages on a miniature liquid crystal display.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Control of operating Data / commands 4 RS 5 R/W 6 E 7 8 9 10 11 12 13 14 D0 D1 D2 D3 D4 D5 D6 D7 0 1 0 1 0 1 From 1 to 0 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 D0 – D7 are interpreted as commands D0 – D7 are interpreted as data Write data (from controller to LCD) Read data (from LCD to controller) Access to LCD disabled Normal operating Data/commands are transferred to LCD Bit 0 LSB Bit 1 Bit 2 Bit 3 Bit 4 Bit 5 Bit 6 Bit
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples If there are no characters displayed or if all of them are dimmed when the display is switched on, the first thing that should be done is to check the potentiometer for contrast adjustment. Is it properly adjusted? The same applies if the mode of operation has been changed (writing in one or two lines).
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples This is a sort of RAM memory so data can be written to and read from it, but its contents is irretrievably lost upon the power goes off. CGROM Memory CGROM memory contains the default character map with all characters that can be displayed on the screen. Each character is assigned to one memory location: The addresses of CGROM memory locations match the characters of ASCII.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples What is ASCII? From their inception till today, computers can recognize only numbers, but not letters. It means that all data a computer swaps with a peripheral device has a binary format even though the same is recognized by the man as letters (The keyboard is an excellent example)! It’s as simple as that- every character matches the unique combination of zeroes and ones.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples signal which would, upon command execution, indicate that the display is ready for the next piece of data. That signal, called the busy flag, can be read from the line D7. When the voltage on this line is 0V (BF=0), the display is ready to receive new data. LCD Connecting Depending on how many lines are used for connecting the LCD to the microcontroller, there are 8-bit and 4-bit LCD modes.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples 4. Character entry ID = 1 Displayed addresses are automatically incremented by 1 S = 0 Display shift off Automatic reset is mostly done without any problems. Mostly, but not always! If for any reason the power supply voltage does not reach full value within 10mS, the display will start performing completely unpredictably.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples It is not a mistake! In this algorithm, the same value is transferred three times in a row. In case of 4-bit initialization, the procedure is as follows: http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples EXAMPLE 1 Writing header and configuring I/O pins The only purpose of this program is to turn on a few LED diodes on port B. It is nothing special. Anyway, use this example to study what a real program looks like. The figure below shows a connection scheme, while the program is on the next page. When switching on, every other LED diode on the port B emits light.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples The purpose of the header and initial directives is briefly described below. Header: The header is placed at the beginning of the program and gives basic information in the form of comments (name of the program, release date etc.). Don't be deluded into thinking that after a few months you will know what that program is about and why it is saved in your computer.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples bsf INTCON, GIE It means that the GIE bit of the INTCON register should be set. Instruction, as such, makes no sense to the compiler. It has to access the ".inc" document in order to know that the seventh bit of the SFR at the address 000B hex should be set. errorlevel -302 This is a "cosmetic" directive which disables the irritating message "Register in operand not in ..." to appear at the end of every compiling process.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples EXAMPLE 2 Using program loop and internal oscillator LFINTOSC This is a continuation of the previous example, but deals with a bit more complicated problem... The idea is to make the LED diodes on the port B blink. A simple thing at first glance! It is enough to periodically change logic state on the port B. In this case, numbers 01010101 and 10101010 are selected to change in the following way: 1. 2. 3. 4. 5.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples ;************************************************************************ org 0x0000 ; Address of the first program instruction banksel OSCCON bcf bcf bcf bsf OSCCON,6 OSCCON,5 OSCCON,4 OSCCON,0 ; ; ; ; Selects memory bank containing register OSCCON Selects internal oscillator LFINTOSC with the frequency of 31KHz ; Microcontroller uses internal oscillator banksel TRISB clrf TRISB banksel PORTB ; Selects bank containing
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples movlw movwf movlw movwf B'11110000' PORTB h'FF' counter2 ; ; ; ; Binary Number Number Number number 11110000 is moved to W is moved to PORTB hFF is moved to W is moved to variable "counter2" movlw movwf h'FF' counter1 ; Number hFF is moved to W ; Number is moved to "counter1" decfsz goto counter1 loop1 ; Decrements "counter1" by 1.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Pay attention to a few details: ● ● ● Even though it is unnecessary in this case, the contents of the most important registers (W, STATUS and PCLATH) must be saved at the beginning of the interrupt routine; Interrupt causes the appropriate flag bit to be automatically set and the GIE bit to be automatically cleared.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples movwf pclath_temp banksel incf PORTB PORTB ; Selects bank containing PORTB ; Increments register PORTB by 1 banksel bcf INTCON INTCON,TMR0IF ; Selects bank containing INTCON ; Clears interrupt flag TMR0IF movf movwf movf movwf swapf swapf pclath_temp,w PCLATH status_temp,w STATUS w_temp,f w_temp,w ; PCLATH is given its original content bsf retfie INTCON,GIE ; Global interrupt enabled ; Return from interrupt routi
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples At the beginning of the program, immediately upon defining variables, the microcontroller pins* are configured by using registers TRISA and TRISB. In the main program, one bit on port B is set first. Then the contents of this register is constantly moved by one place to the left (instruction rlf PORTB). It gives us the impression that the lit LED diodes is moving. To make it visible, the whole process must be slow enough.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples movwf TRISA ; Pin RA1 is input banksel movlw movwf PORTB B'00000001' PORTB ; Selects bank containing register TRISB ; Writes 1 to register W ; Number is moved to PORTB rlf call PORTB DELAY ; Port B bits rotates by one place left ; Calls subroutine "DELAY" btfss goto goto PORTA,1 loop3 loop ; Tests the firs port A bit ; "0" is applied to pin.Go to label "loop3" ; "1" is applied to pin.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Example 6: ;**************************************************************************** ; Header ;**************************************************************************** ;************* DEFINING VARIABLES ******************************************* TEST #define equ B'00000101' ; Binary number 00000101 = TEST RELAY PORTD,3 ; Pin PORTD,3 = RELAY ;************************ MAIN PROGRAM ************************************
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples btfsc bsf goto STATUS,Z PORTD,3 loop end ; ; ; ; W register and number TEST (00000101) If numbers are equal, result is 0 and bit STATUS,Z = 1. Bit PORTD,3 is set and jump to label loop is executed ; End of program EXAMPLE 7 Using macros in the program, using debounce routine You have probably noticed in the previous example that the microcontroller does not always operate as expected.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples HIcnt LOcnt LOOPcnt cnt endc ; End of block of variables ;********************************************************************** ORG 0x000 ; Reset vector nop goto main ; Go to program start (label "main") ;********************************************************************** include include "pause.inc" "button.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples btfsc STATUS, Z goto End call Delay1ms decf HIcnt, f decf LOcnt, f goto Loop1 Delay1ms: ; Delay1ms provides delay of movlw .
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples 16-bit timer TMR1 is used in this example. By occupying its registers TMR1L and TMR1H, an interrupt occurs and the number on port B is incremented. This has already been seen in the previous examples. The difference is in the program delay which is a bit longer this time because the prescaler rate is 1:8.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples movf movwf swapf swapf status_temp,w STATUS w_temp,f w_temp,w ; STATUS is given its original content banksel bcf PIR1 PIR1,TMR1IF ; Selects bank containing PIR1 ; Clears interrupt flag TMR1IF bsf retfie INTCON,GIE ; Global interrupt enabled ; Return from interrupt routine ; W is given its original content ;************************ MAIN PROGRAM *************************************** main banksel clrf clrf ANSEL ANS
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples movwf w_temp ; Save register W movf movwf STATUS status_temp ; Save register STATUS movf movwf PCLATH pclath_temp ; Save register PCLATH banksel incf banksel decf movf movwf movf movwf swapf swapf PORTB PORTB PR2 PR2 pclath_temp,w PCLATH status_temp,w STATUS w_temp,f w_temp,w ; ; ; ; ; banksel bcf PIR1 PIR1,TMR2IF ; Selects bank containing PIR1 ; Clears interrupt flag TMR2IF bsf retfie INTCON,GIE ; Global int
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Example 10: ;********************** Header ********************************************** ;************* DEFINING VARIABLES ******************************************* cblock 0x20 ; Block of variables starts at address 20h w_temp ; Variable at address 20h pclath_temp ; Variable at address 21h status_temp ; Variable at address 22h endc #define DARK PORTB,0 ; Push-button "DARK" is connected ; to PORTB,0 pin #define BRIGHT PO
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples movf movwf PCLATH pclath_temp ; Save register PCLATH banksel btfss decf btfss incf CCPR1L DARK CCPR1L BRIGHT CCPR1L ; ; ; ; movf movwf movf movwf swapf swapf pclath_temp,w PCLATH status_temp,w STATUS w_temp,f w_temp,w ; PCLATH is given its original content banksel bcf PIR1 PIR1,TMR1IF ; Selects bank containing PIR1 ; Clears interrupt flag TMR1IF bsf bsf bsf retfie TMR1H,7 TMR1H,6 INTCON,GIE ; Accelerates timer T
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples possible, only 8 lower bits of the result of conversion are shown. GND is used as a negative voltage reference Vref-, while positive voltage reference is applied on the AN3 pin. It enables voltage measurement scale to "stretch and shrink". To make this clear, the A/D converter always generates a 10-bit binary result, which means that it detects a total of 1024 voltage levels (210=1024).
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples ; loop banksel movf ADRESL ADRESL,w banksel movwf bsf goto end PORTB PORTB ADCON0,1 loop ; Lower byte of conversion result is ; copied to W ; ; ; ; Byte is copied to PORTB Starts new conversion Jump to label "loop" End of program EXAMPLE 12 Using EEPROM memory This example demonstrates write to and read from built-in EEPROM memory. The program works as follows.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Example 12: ;********************** Header ********************************************** ;*********** Defining variables in program ********************************** cblock 0x20 ; Block of variables starts at address 20h HIcnt LOcnt LOOPcnt cnt endc ; End of block ;**************************************************************************** ORG 0x000 ; Reset vector nop goto main ; Go to start of the program (label "main"
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples movwf banksel bcf bsf EEDAT EECON1 EECON1,EEPGD EECON1,WREN ; Writes data to temporary register bcf btfsc goto INTCON,GIE INTCON,GIE $-2 ; All interrupts disabled movlw movwf movlw movwf bsf 55h EECON2 H'AA' EECON2 EECON1,WR btfsc goto EECON1,WR $-1 ; Wait for write to complete bsf bcf goto end INTCON,GIE EECON1,WREN Loop ; Interrupt enabled ; Write enabled ; Tests push-buttons again ; End of program EXAMPLE 1
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Example 13: ;************************* Header ******************************************* ;**************************************************************************** ; DEFINING VARIABLES IN PROGRAM w_temp EQU 0x7D ; Variable for saving W register status_temp EQU 0x7E ; Variable for saving STATUS register pclath_temp EQU 0x7F ; Variable for saving PCLATH register CBLOCK ; Block of variables starts at address 20h 0x20
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples digbyte movf call movwf bsf goto Dval Dig0, w Bcdto7seg PORTD PORTA, 0 ISR_end ; Place LO mask on the PORTD ; End of interrupt routine...
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples ; tant to have it all on one page Bcdto7seg addwf PCL, f DT 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f ;**************************************************************************** END ; End of program Macro "digbyte": digbyte MACRO arg0 LOCAL Exit0 LOCAL Exit1 LOCAL Exit2 clrf clrf clrf clrf Dig0 Dig1 Dig2 Dig3 movf movwf movlw arg0, w Digtemp .
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Example 14: ;*********************** Header *************************************** ;******************* Defining variables in program ******************** cblock 0x20 HIcnt ; Auxiliary variables for macro pausems LOcnt LOOPcnt PRESCwait Beep_TEMP1 ; Belongs to macro "BEEP" Beep_TEMP2 Beep_TEMP3 endc #define #define BEEPport PORTD, 2 BEEPtris TRISD, 2 ; Speaker pin expand ;*************************************************
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples clrf ANSELH banksel movlw movwf banksel BEEPinit TRISD b'11111011' TRISD PORTD button button goto PORTD,0,0,Play1 ; Push-button 1 PORTD,1,0,Play2 ; Push-button 2 Loop BEEP BEEP BEEP BEEP goto 0xFF, 0x90, 0xC0, 0xFF, Loop ; PORTA D initialization ; Macro "Beep" Loop Play1 ; First tone 0x02 0x05 0x03 0x03 Play2 ; Second tone BEEP 0xBB, 0x02 BEEP 0x87, 0x05 BEEP 0xA2, 0x03 BEEP 0x98, 0x03 goto Loop ;****************
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples B_Wait movf Beep_TEMP1, w movwf Beep_TEMP3 B_Waita decfsz Beep_TEMP3, f goto B_Waita return EXAMPLE 15 Using LCD display This example illustrates the use of the alphanumeric LCD display. The program itself is very simple because macros are used (usually the effort of creating Macros pays off in the end). Two messages written on two lines change on display. The second message is intended to display the current temperature.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples LCDportBuf ; LCD Port Buffer Digtemp Dig0 Dig1 Dig2 Dig3 ; Belongs to macro "digbyte" temp ENDC LCDport RS EN EQU PORTB EQU 4 EQU 5 ; End of block ; LCD is on PORTB (4 data lines on RB0-RB3) ; RS line connected to RB4 ; EN line connected to RB5 ;********************************************************************** ORG 0x0000 ; Reset vector address nop goto main ; Go to beginning of the program (label "main") ;********
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples bcf STATUS, RP1 ; Function set (4-bit mode change) movlw b'00100000' movwf LCDbuf swapf LCDbuf, w movwf LCDportBuf bcf LCDportBuf, RS movf LCDportBuf, w movwf LCDport bsf LCDportBuf, EN movf LCDportBuf, w movwf LCDport bcf LCDportBuf, EN movf LCDportBuf, w movwf LCDport call Delay1ms ; 1 ms delay ; Function set (display mode set) lcdcmd b'00101100' call Delay1ms ; 1 ms delay ; Display ON/OFF Control lcdcmd b'00001100' cal
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples movlw call ENDM LCDcommand LCDcomd LCDcomd movwf bcf movf movwf goto LCDbuf LCDportBuf, RS LCDportBuf, w LCDport LCDwr LCDdata movwf bsf movf movwf goto LCDbuf LCDportBuf, RS LCDportBuf, w LCDport LCDwr swapf call movf call return LCDbuf, w SendW LCDbuf, w SendW andlw movwf 0x0F LCDtemp movlw andwf movf iorwf movf movwf call bsf movf movwf bcf movf movwf call return 0xF0 LCDportBuf, LCDtemp, w LCDportBuf, LCDportBu
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples i=i+1 ENDW Exit ENDM ;********************************************************************** ; This macro writes value in size of 1 byte on LCD ; excluding leading zeros ;********************************************************************** lcdbyte MACRO arg0 digbyte arg0 ; A hundred is in Dig2, ; A ten is in Dig1 and one in Dig0 movf Dig2, w addlw 0x30 call LCDdata movf Dig1, w ; If digit is 0 move cursor addlw 0x30 call LC
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples Example 16: ;*********************** Header *************************************** ; DEFINING VARIABLES IN PROGRAM w_temp EQU 0x7D status_temp EQU 0x7E pclath_temp EQU 0x7F ; Variable for saving W register ; Variable for saving STATUS register ; Variable for saving PCLATH w register cblock 0x20 ; Block of variables starts at address 20 h Port_A ; Variable at address 20 h Port_B ; Variable at address 21 h RS232temp ; Varia
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples ; This part of the program is executed in interrupt routine banksel PIE1 btfss PIE1, RCIE goto ISR_Not_RX232int banksel PIE1 btfsc PIR1, RCIF call RX232_int_proc ISR_Not_RX232int movf movwf movf movwf swapf swapf pclath_temp,w PCLATH status_temp,w STATUS w_temp,f w_temp,w ; PCLATH is given its original value ; STATUS is given its original value ; W is given its original value retfie ; Return from interrupt routine ;*******
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix B: Examples movwf TRISA movlw b'00000000' movwf TRISB ;--------------------------------------; Setting initial values ;--------------------------------------banksel PORTA movlw b'11111100' movwf PORTA movwf Port_A movlw b'00000000' movwf PORTB movwf Port_B ;--------------------------------------; USART - setting for 38400 bps ;--------------------------------------banksel TRISC bcf TRISC, 6 ; RC6/TX/CK = output bsf TRISC, 7 ; RC7/RX/DT =
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix C: Development Systems ● TOC ● Introduction ● Ch. 1 ● Ch. 2 ● Ch. 3 ● Ch. 4 ● Ch. 5 ● Ch. 6 ● Ch. 7 ● Ch. 8 ● Ch. 9 ● App. A ● App. B ● App. C Appendix C: Development Systems How to start working? A microcontroller is a good-natured "genie in the bottle" and no extra knowledge is required to use it.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix C: Development Systems goto Loop Increment incf cnt,f movf cnt,w movwf PORTB goto Loop Decrement decf cnt,f movf cnt,w movwf PORTB To enable the compiler to perform its task successfully, it is necessary that a document containing this program has the extension, .asm in its name, for example: Program.asm When a specialized program (MPLAB) is used, this extension will be automatically added.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix C: Development Systems In case other software for program writing in assembly language is used, special software for compiling the program must be installed and used as follows: set up the compiler, open the document with .asm extension and compile. The result is the same- a new document with .hex extension. The only problem you have now is that it is stored in your PC.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix C: Development Systems OK. You have written a program and tested it with the simulator. The program did not reports any error during the compiling process? It seems that everything is under control... http://www.mikroe.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix C: Development Systems The program is written and successfully compiled. All that’s left is to dump the program to the microcontroller. For this purpose it is necessary to have software that takes the written and compiled program and passes it into the microcontroller ( PIC Flash for example). Start up this program...
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix C: Development Systems That's it! The microcontroller is programmed and everything is ready for operation. If you are not satisfied, make some changes in the program and repeat the procedure. Until when? Until you feel satisfied... Development systems A device, which in testing program phase, can simulate any environment is called a development system.
mikroElektronika | Free Online Book | PIC Microcontrollers | Appendix C: Development Systems Development system EasyPIC5 Previous Chapter | Table of Contents http://www.mikroe.