Before getting into the minute details of PIC programming, it would be first important to learn a few good programming methods.
Understanding Registers
To begin with suppose you type a ;(semicolon) at any point of the program, all’s that come after this semicolon would get ignored by the compiler, until of course the carriage get’s back into the position.
The above feature allows us to add comments or remarks such that they don’t become the part of the program yet facilitates us to identify the program with the help of the comments beside it. Putting comments is a recommended practice while programming any IC.
Next important thing in the course is to assign names to the various constants (you would learn them later elaborately). This aso makes it simpler to understand what’s being written to, or regarding the involved values, instead of getting confused with the included numbers.
The above must be done in the form of actual names for instant recognition, for example COUNT, it would be important to note that here all capital letters are employed to make it distinct and also indicate that it’s a constant value.
As we can see, the above is done in the form of a box made of semicolons; this just makes it look cleaner. Additionally try documenting the program on paper as well, this practice will help to understand things in a step wise manner.
2. The Registers.
The register within a PIC is an area which accepts written details as well allows reading from it. You may compare it to a sheet of paper where you can visualize contents and aso add by writing over it.
The figure below depicts a typical register file map embedded within a PIC16F84. The format is not something which is actually set inside the PIC, it’s simply to indicate how the bits may be arranged inside the chip and to understand a few of the involved commands.
You can see that it’s basically divided into Bank 0 and Bank 1. Bank 1 is responsible for controlling the actual working of the PIC, for instance it tel the PIC which bits at Port A are assigned as inputs and which are as outputs.
Bank 2 is just for manipulating the information.
Let’s understand this through the following example:
Suppose we wish to assign one bit at PortA high. For this we would first need to go to Bank 1 for setting the specified bit or pin at Port A in the form of an output. After this we return to Bank 0 and deliver a logic 1 (bit 1) to that specific pin.
The most common registers which we woud like to use in Bank 1 are STATUS, TRISA and TRISB.
STATUS helps us to return to Bank 0, TRISA permits us to choose which pins at Port A are outputs and which may be inputs, while TRISB facilitates to select between output and input pin at Port B.The SELECT register in BANK 0 permits the user to flip to Bank 1.
Let’s summarize the whole concept with the following description:
STATUS:
In order to switch from Bank 0 to Bank 1 we command the STATUS register. This is implemented by setting bit#5 of the STATUS register to 1. In order to return back to Bank 0, we assign bit 5 of the STATUS register to 0. The STATUS register is positioned at address 03h, here h signifies tat the number may be in Hexadecimal.
TRISA and TRISB:
These are situated at address 85h and 86h correspondingly. For programming a pin as an output or an input, we just deliver a zero or a one to the particular bit in the register. Now this may be done in two ways, via binary, or Hex. In case one is unable to convert the parameter he or she may go for a scientific calculator for implementing the values.
Now we have 5 pins at Port A, which corresponds to 5 pins. If we intend to fix one of the pins as inputs, we deliver a “1” to the particular bit.
In case we wanted to assign one of the pins as outputs, we would set the specific pin to “0”. The bits are aid down exacty corresponding to the bits, or more precisey bit 0 is RA0, bit 1 would be RA1, bit 2 = RA2 and so forth. Let’s understand it in this way:
Suppose you wish to fix RA0, RA3 and RA4 as outputs, while RA1/RA2 as i/ps, you would do this by sending 00110 (06h). Check out that bit 0 is toward the right as indicated here:
Port A Pin RA4 RA3 RA2 RA1 RA0
Bit Number 4 3 2 1 0
Binary 0 0 1 1 0
The same goes for TRISB.
PORTA and PORTB
In order to deiver one of the output pins high, we just offer a “1” to thr respective bit in our PORTA or PORTB register. An identical procedure may be followed for TRISA and TRISB registers also.Before we speed into our first example coding, let’s just understand a coupe of more registers, viz: w and f.
W and F
The W register is an ordinary register which enables you to assign any value of your choice. As soon as you assign a magnitude to W, you may proceed by adding this to another value or simply move it. With another value assigned, the details simply get overwritten on W.
The F register forwards its written matter over to a register. We would require this F register to assign a value over a register, may be over the STATUS or the TRISA registers, as these won’t allow us to put the values directly over them. An Example Program
Let’s examine the following example code which will show us how the above instruction is implemented and would also witness a few of the instructions in the course.
Let’s begin by fixing Port A as discussed above.
For this we need to shift from Bank 0 to Bank1, this is done by setting up the STATUS register situated at address 03h, bit 5 to 1.
BSF 03h,5
The BSF Means Bit Set F. We are using two numbers after this instruction – 03h, which is the STATUS register address, and the number 5 which corresponds to the bit number.
So, what we are saying is “Set bit 5 in address 03h to 1”.
We are now in Bank 1.
MOVLW 00110b
We are putting the binary value 00110 (the letter b means the number is in binary) into our general purpose register W. I could of course have done this in hex, in which case our instruction would be:
MOVLW 06h
Either works. The MOVLW means ‘Move Literal Value Into W’, which in English means put the value that follows directly into the W register.
Now we need to put this value onto our TRISA register to set up the port:
MOVWF 85h
This instruction indicates “Move The Contents Of W Into The Register Address That Follows”, in this instance the address refers to TRISA.
Our TRISA register at this point bears the figure 00110, or presented graphically:
Port A Pin RA4 RA3 RA2 RA1 RA0
Binary 0 0 1 1 0
Input/Output O O I I O
So now we possess our Port A pins, we must return to Bank 0 to adjust one of the info.
BCF 03h,5
This instruction accomplishes the reverse of BSF. It implies “Bit Clear F”. The a pair of numbers that correspond are the address of the register, here the STATUS register, as well as the bit figure, in this instance bit five. What exactly we have completed at present is, defined bit five on our
STATUS register to 0
We have at this point returned in Bank 0.
The following is the code all in one block:
BSF 03h,5 ;Go to Bank 1
MOVLW 06h ;Put 00110 into W
MOVWF 85h ;Move 00110 onto TRISA
BCF 03h,5 ;Come back to Bank 0
Within the last instructional, we confirmed you the way to establish the IO port pins on the PIC to be possibly input or output.
Through this course, Let me assist you to send data to the ports.
Sending Data to Ports
In the subsequent tutorial, we are going to complete by flashing an LED on and off that consist of a complete program detailing and a straightforward circuit diagram so that you could see the PIC performing precisely what we anticipate it to.
Don’t attempt to put together and program your PIC with the results below, since they are illustrations only. Initially, we will establish Port A bit 2 as an output:
This could be recognizable from the previous instructional. The sole distinction could be We have fixed every bit of the pins on A as output, by delivering 0h to the tri-state register. So what now he must do is switch an LED on.
We accomplish this by scheduling one of the pins (the one with the LED linked to it) high. To put it differently, we apply a ‘1’ to the pin. This is exactly exactly how it’s carried out (observe the comments for a clarification for every line):
Therefore, what now we have accomplished is switch the LED on then off one time. What we desire is for the LED to switch on subsequently off continually.
We achieve this by obtaining the program to return to the start. We accomplish this by initially establishing a tag at the outset of our program, thereafter informing the program to proceed back there. We specify a tag quite straightforwardly.
We key in a term, say START, next type the code:
As is demonstrated, we initially mentioned the expression ‘Start’ immediately at the outset of the program.
Next, at the very finish of the program we plainly mentioned ‘goto Start’. The ‘goto’ instruction performs just what it declares.
This program would consistently switch the LED on and off whenever we power up the circuit, tending to switch OFF once we remove electricity. May be we ought to check our program yet again:
Surely we have omitted the comments off, however we can still observe the instructions and the numbers.
This can be a slightly puzzling later in case you try troubleshooting the program and while writing the code you've memorize al of the addresses.
Although the comments may be be placed still it could become a bit cluttered. This will require naming the numbers and might be accomplished by an additional instruction: 'equ' The 'equ' instruction suggests that some stuff might be equal to another stuff.
It may not be an instruction for PIC, rather for the assembler. This instruction facilitates assigning name to a register address location, or a constant to a programming term.
We will establish a few constants for our program and also witness how much straightforward it is reading the program.
Since now we have fixed the constant values we may proceed by setting them up into our program. The constant values needs to be designated prior to using them.
therefore make sure to always position them at the beginning of the program. We will rewrite the program excluding the comments once again, in order to compare the earlier labeling with the latest one.
May be you are able to notice that the constants are enabling slightly easier understanding of the program, however we are still without the comments, no worries though, since we are not yet finished.
There may be a minor downside of our flashing LED program.
Every instruction needs 1 clock sequence to finish. In case we are utilizing a 4MHz crystal, then every instruction calls for 1/4MHz, or 1uS to finish.
Since we have been employing just five instructions, the LED would activate then off in 5uS. This could be much too rapid for folks to notice, in addition, it will seem that the LED is fully on.
What we should instead accomplish is produce a inhibition between switching the LED on and turning the LED off. The theory of the inhibition is that we count down from a earlier quantity, so when it gets to zero, we quit counting.
The zero value signifies the conclusion of the delay, and we keep working our process throughout the program. Therefore, the firstly we must do is to determine a constant to make use of as our counter.
Let us term this constant COUNT. After that, we must determine how significant a number to begin counting from. Surely, the biggest figure we could include is 255, or FFh in hex., as I talked about in the earlier tutorial, the equ instruction assigns a expression to a register situation.
This implies that no matter what quantity we allocate our COUNT, it would match the items of a register. In case we try to designate the value FFh, we are going to get a mistake once we get to compile the program.
The reason being the location FFh is , therefore we can’t gain access to it. Therefore, how must we designate a genuine number? Certainly, it will require a small amount of lateral pondering.
If perhaps we designate our COUNT to the address 08h, for instance, this would indicate a basic objective register destination. By default, the untouched areas are set to FFh. Consequently, if COUNT leads to 08h, you will encounter the value of FFh while we first power up. Nevertheless, I you, how can we fix COUNT to another number?, all we apply is ‘move’ a valuation to this destination first.
As an illustration, suppose we wished for COUNT to possess a value of 85h, we can’t mention COUNT equ 85h since that is the position of out Tri-State register for Port A. Precisely what we accomplish is the following: movlw 85h;First put the value of 85h in the W register movwf 08h;
Now move it to our 08h register. Subsequently, in case we express COUNT equ 08h, COUNT would match the value 85h. Delicate, isn’t it! Therefore, initially we determine our constant: COUNT equ 08h Following we must reduce this COUNT by one until it becomes zero.
It simply so occurs that there exists one instruction designed to accomplish this for us, by making use of a ‘goto’ and a tag.
The instruction we are going to apply is: DECFSZ COUNT,1 This instruction states ‘Decrement the register (here it's COUNT) by the number that tracks the comma. If we attain zero, hop two spots ahead.’ Lets find it in action first, before we place it into our course.
What we have performed is initially establish our constant COUNT to 255. The subsequent segment positions a tag, called LABEL close to our decfsz instruction.
The decfsz COUNT,1 reduces the value of COUNT by one, and retains the end result straight into COUNT. Moreover it verifies to check if COUNT possesses a value of 0.
If it doesn’t, it in that case triggers the program to shift to the subsequent line. Now we have a ‘goto’ declaration which delivers us back to our decfsz instruction.
In case the value of COUNT performs equal , then the decfsz instruction results in our program to leap 2 spots ahead, and is sent to where We have claimed ‘Carry on here’.
Therefore, since you can observe, we have brought about the program to sit in one spot for a predestined time before proceeding. This could be named a delay loop.
Understanding Delay Loops
In case we require a more substantial delay, we could pursue one loop by the next. The extra loops, the extended the delay. Let us at least two, assuming we want to observe the LED flash.. We will place these delay loops into our program, and accomplish by rendering it a genuine program by introducing comments:
It is possible to compile this program after which program the PIC. Obviously, be sure that you attempt the circuit out to check if it does indeed function. The following is a circuit diagram that you should construct as soon as you have programmed the PIC.
Well done, you could have actually composed your first PIC program, as well as constructed a circuit to blink an LED on and off. Until now, in case you have ensued these courses, you might have learned an overall of seven instruction out of 35, but without doubt so far you might be controlling the I/O ports!
Would you attempt to change the delay loops to render the LED flash quicker – what appears the minimal value of COUNT to essentially see the LED flash? Or maybe, you will want to include a 3rd or supplementary delay loops after the initial one to stabilize the LED down. a unique constant for each delay loop.
You could potentially then actually fiddle with your delay loops to render the LED flash at a specific speed, for instance after a second. Within the next instructional let us see how we are able to utilize something known as a subroutine to maintain the program compact and basic A subroutine is an integral part of code, or program, that may be referred as and when you may need it. Subroutines are employed in cases where you are accomplishing the identical function frequently.
What are Subroutines
The benefits of employing a subroutine are that it will likely be simpler to modify the value once inside a subroutine instead of, say, ten times all through your program, as well as it contributes greatly to decrease the level of memory your program consumes inside the PIC. We will check out a subroutine:
Initially, we need to provide our subroutine a designation, and in this situation We have selected ROUTINE. We after that type the code that we would like to conduct as normal. That is why, We have selected the delay in our flashing led program. Lastly, we conclude the subroutine by keying the RETURN instruction.
To begin the subroutine from anywhere in our program, we quickly type the instruction CALL and then the subroutine designation.
We will consider this in a little more depth. Once we arrive at the section of our program that CALL xxx, in which xxx is the name of our subroutine, the program leaps to anywhere the subroutine xxx is installed. The instructions inside the subroutine are carried out .
Whenever the instruction RETURN is accomplished, the program leaps returning to our principal program to the instruction subsequent to our CALL xxx instruction.
It is possible to call the similar subroutine several times as you would like, which explains why utilizing subroutines lessens the general duration of our program.
Nevertheless, there are a couple of factors you should know of. Initially, as with our principal program, any specific constants needs to be acknowledged before you can use them.
These may be possibly acknowledged within the subroutine itself, or directly at the beginning of the principal program. I propose you that you acknowledge everything at the beginning of your main program, since then you recognize that things are in an identical position. Next, one should make sure that the main program skips over the subroutine.
What I imply with this is should you place the subroutine directly at the conclusion of your primary program, except if you utilize a ‘Goto’ declaration to leap off of where the subroutine is, the program would continue and implement the subroutine regardless of whether you require it to or otherwise.
The PIC would not distinguish between a subroutine and the principal program. We will check out our flashing led program, however this time we are going to make use of a subroutine for the delay loop. Ideally, you will discover how much less complicated the program appears, as well as you might find how the subroutine applies practically.
Eventually, you can observe that by utilizing a subroutine for our delay loop, we might have downsized the dimensions of the program.
Every time we desire a delay, possibly when the LED is on or off, we basically call the delay subroutine. At the conclusion of the subroutine, the program leads back to the line following our ‘Call’ instruction. In the illustration above, we flip the LED on.
We after that contact the subroutine. The program then comes back in order that we are able to switch the LED off. We call the subroutine once more, just in case the subroutine might have completed, the program comes back and the subsequent instruction it recognizes is ‘goto Start’. For anybody that may be intrigued, our first program was 120 bytes long.
Through the use of the subroutine, we could reduce our program size down to 103 bytes. This could not sound to be that fantastic, however considering the fact that we only have 1024 bytes overall inside the PIC, every small amount benefits.
Within the next instructional, let us check out reading from the ports.
So far, we have been composing to Port A in order that we are able to switch an LED on and off. At this point, we will see how we are going to read the I/O pins on the ports.
Reading Input/Output Ports
This is exactly to ensure that we are able to link an external circuit, and influence any specific outputs it offers.
Should you memorize from our earlier courses, if you want to establish the I/O ports, we needed to jump from Bank 0 to Bank 1. We will accomplish that initially:
At this point we have fixed bit 0 of Port A to input. we must now examine if the pin is high or low. To accomplish this, one can utilize just one of two instructions:
BTFSC and BTFSS.
The BTFSC instruction signifies ‘Do a bit test on the register as well as bit we designate.
In case it is a 0, in that case we omit the subsequent instruction’. BTFSS implies ‘Do a bit test in the register and bit we establish. In case it is set to a 1, then we bypass the subsequent instruction.
Which one we utilize, is determined by precisely how we wish our program to respond while we study the input. As an illustration, in case we are just awaiting the input to be a 1, then we might be able to utilize the BTFSS instruction in the following manner:
Code here:
BTFSS PortA,0Goto start Carry on here:
:
The program would just shift onto ‘Carry on here’ provided that bit 0 on PortA is scheduled to a 1.
We will currently write a program which could prompt an LED at one rate, however if a switch is confined it would flash the LED two times as slower.
It is possible to perhaps exercise this program out for on your own, still We have incorporated the listing somehow.
You could attempt and author the entire program, in order to check if in case you have understood the principles. We will be using the equivalent circuit as before, with the inclusion of a switch attached RA0 of the PIC and the positive rail of our supply.
What We have accomplished here is to switch the LED on. I subsequently determine if the switch is closed off.
In case it is confined, next I connect to our delay subroutine. This provides us the equivalent delay as before, however we are at this point contacting it two times.
The same thing applies to whenever the LED is off. In case the switch is not shut, then we have our previousy recorded on and off periods.
Have you been following these lessons from the beginning, you might be seeking to grasp that you have currently discovered ten of the 35 instructions for the PIC 16F84! And every bit of these happen to be learned merely by switching an LED on and off.
Up till now, we have composed the PIC blink an LED on and off.
Subsequently we were capable of with our PIC by including a switch, therefore varying the flash speed.
Using Memory Space Efficiently
The sole issue is, the program is quite lengthy and rather inefficient of memory space. It seemed ok while i was including the commands for the first time, however there ought to be an easier way of executing it. Positively there is, we will analyze how we were literally switching the LED on and off.
movlw 02hmovwf PORTAmovlw 00hmovlw PORTA
At first we stuffed our w register with 02h, after that transfered it to our PortA register to switch the LED on. To switch it off, we packed w with 00h after which shifted it to our PortA register.
In between all these routines we were forced to get in touch with a subroutine to ensure that we could observe the LED flashing.
Therefore, we needed to transfer two sets of info a couple of times (one time into the w register then to PORTA) as well as call a subroutine two times (once for on then once for off). Thus, how could we achieve this with added efficiency? Very simple.
We utilize a different instruction known as XORF. The XORF instruction works an Exclusive OR function on the register that we stipulate with the info we provide. I believe I have to clarify what in the world an Exclusive OR is before we continue. In case we have two inputs, and one output, the input can only be a 1 if, and as long as, the two inputs differ. While they are the same, then the output will probably be 0. The following is a truth table, for individuals who choose to check out these:
A B F0 0 00 1 11 0 11 1 0
We will at this point check out what goes on if we render B the just like our earlier output, and simply altering the value of A:
A B F
0 0 0
0 0 0
1 0 1
1 1 0
1 0 1
If we maintain the value of A same as 1, and we Exclusive OR it with the output, the output would toggle. In case you can’t notice this from the truth table, below it can be witnessed utilizing binary:
0 Current Output
EX-OR With 1 1 New Output
EX-OR With 1 0 New Output
Maybe you can find that by exclusive ORing the output with 1, we will be now toggling the output from 0 to 1 to 0.
Hence, to switch our LED on and off, we only require a couple of sentences:
MOVLW 02h
XORWF PORTA,1
What precisely we will be accomplishing is adding our w register with 02h. We are in that case Exclusive ORing this number with no matter what is on our PortA. In case bit 1 is a 1, it is going to alter to a 0. In case bit 1 is a 0, it is going to alter to a 1. Let’s examine this code once or twice, to display how it's running binary:
PORTA
00010
xorwf 00000
xorwf 00010
xorwf 00000
xorwf 00010
We don’t actually have to load the identical value into our w register every time, therefore it is possible to accomplish this one time at the start, and simply leap back to our toggle command. Additionally, we don’t ought to fix a value on our PortA register. The reason? Surely, since in case on power up it is a 1, we can easily toggle it. I, alternatively a 0 on power up, we would even now toggle it.
Therefore you would want to see our newly formed code. The first one represents our blinking LED code, while the second shows the one with the addition of the switch:
Lets wish you can find that simply by making use of one easy instruction, we now have cut down the scale of our program. The truth is, in order to display just how much we could reduce our programs by, We have demonstrated the two programs, just what were composed, and their dimensions in the table below:
Program Alter Dimensions (Bytes)
Flashing LED Original 120
Flashing LED Subroutine Added 103
Flashing LED XOR Function Used 91
LED With Switch Original 132
LED With Switch XOR Function Used 124.
Therefore, not just have we discovered a few novel instructions, we certainly in addition have decreased the size of our scripting!
Below, we will analyze how you can wiggle individual bits, carry out certain straightforward arithmetic, as well as data tables.
Logical Managers
Within the last tutorial I presented the Exclusive OR operation. The ExOR function is understood as a logical operator.
Within this tutorial I will enlighten the additional logical operators that the PIC promotes. There won’t be any kind of case in point programs, however We will learn easy methods to use the operators by applying small areas of code.
AND The AND function basically analyzes two bits and delivers a 1 whether they are the same, and a 0 in case they are distinctive. For instance, if we mentioned 1 AND 1, the outcome is 1, while in case we declared 1 AND 0 the consequence would be 0.
Needless to say, we are able to evaluate words also, as well as all of the the AND function accomplishes is review the two terms bit by bit. The instance below demonstrates two 8-bit words becoming ANDed together with the product:
11001011
AND 10110011
Equals 10000011
I hope you agree, the outcome will simply possess a 1 whenever 2 1s hand in hand with one another in the a pair of words. We are able to utilize the AND function to verify the ports, for instance.
In case we are checking a few I/O pins that are linked to a circuit, and we should keep an eye on a particular situation in which only a few of the pins are high, in that case we are able to pretty much read the port, after which AND the outcome with the condition we have been examining for, identical to the instance above.
The PIC provides us two ingredients for AND.
They are ANDLW and ANDWF. ANDLW permits us to carry out an AND function with the details of the W register, and a amount that we stipulate.
The syntax is: ANDLW <number> wherein <number> is exactly what we are going to AND the contents of W with.
The consequence of the AND function would be stored directly into the W register.
ANDWF permits us to carry out an AND function on the W register and a different register, for example a PORT. The syntax is: ANDWF <register>,d in which <register> is the register we are enthusiastic about, e.g. PORTA, and d shows the PIC where you should position the result. If d=0, the outcome is put in the W register, and of d=1 the end result is saved in the register we stipulated. The two parts of code below display a good example of each AND function.
The initial is examining the status of the PORTA, in which we need to check if the inputs are 1100. We can place the outcome back into the W register
movlw 1100
ANDWF 05h,0The second illustration might now verify the contents of the W register:
ANDLW 1100
OR
We have by now discovered one OR function, to be precise the XOR. This develops into a 1 if two bits are not the same, but are different. You can find another OR function called IOR, which is the inclusive OR. This function will generate a 1 in case either bit is a 1, but additionally if each bits are 1. Below is a clear-cut truth table to illustrate this:
A B O/P
0 0 0
0 1 1
1 0 1
1 1 1
What are Arithmetic Operators
ADD
This function accomplishes what usually it claims. It contributes two figures! In case the consequence of adding the two figures surpasses 8 bits, in that case a CARRY flag will probably be set. The CARRY flag is situated at address 03h bit 0.
When this bit is scheduled, then the two figures surpassed 8 bits. When it is a 0, in that case the consequence is located within 8 bits. As before, the PIC delivers us two styles of ADD, specifically ADDLW and ADDWF. As you might have assumed, this is quite like the above function. ADDLW offers the contents of the W register to that we stipulate. The syntax is: ADDLW <number> ADDWF add the contents of the W register and some other register that we designate.
The syntax is: ADDWF <register>,d is where <register is the register we specify and d tells the PIC where to place the outcome. If d=0, the result is put in the W register, and is d=1 it set up in the register that we selected.
SUB
At this point, I guess you can’t presume what this function conducts! Indeed, you suspected it, this function
subtracts one bit from another. Again the PIC provides us 2 tastes: SUBLW and SUBWF. The syntax is precisely the similar to for the ADD function, apart from evidently you type SUB in place of ADD!
Increment In case we wished to include 1 to a number in the PIC, we could absolutely make use of the ADD function, and utilize the number one. ~The difficulty with this is that we must first place the figure into the W register, subsequently use ADDLW 1 control to increment it. In case we desired to include 1 to a register, it can be worse still. We first must place the number 1 into the W register, after that use ADDWF <register>,1. Therefore, for instance, to include 1 to location 0C, say, we would need to possess the following part of script:
movlw 01
addwf 0c,1
There exists an easier method of conducting this. We can exercise the command INCF. The syntax is: INCF <register>,d where <register>, is the register, or place, that we are concerned in, and d shows the PIC where you should position the outcome. In case d=0, the outcome is within the W register, and in case d=1, the consequence is set in the register we stipulated.
By utilizing this individual instruction we are able to actually fifty percent of the coding. In case we desired the outcome restored into the W register, in that case employing the instance above, we might have had to include an additional command to shift the items of 0C back into the W register, after which place the 0C register back to no matter what it was.
There exists increment command. It is INCFSZ. This command might increment the register that we stipulate, however if we the register equals 0 after the increment (that will occur while we include 1 to 127) after that the PIC will probably by pass the subsequent instruction. The portion of code below reflects this:
Loop incfsz 0C
Goto Loop
:
:
Remainder of program.
In the above portion of code, 0C is going to be incremented by 1. We next own an instruction that informs the PIC to return to our tag named Loop, and increment 0C by 1 again. This continues until 0C equals 127. In this circumstance, when we increment 0C by 1, 0C is going to now match 0. Our INCFSZ instruction could very well inform the PIC to omit the subsequent instruction, which in this instance is the goto declaration, hence the PIC will go forward with the remaining of the program.
Decrement
We have by now discussed the decrement function in earlier training, therefore I won’t revise it anymore.
Complement
The final instruction in this discussion would reverse every single bit in the register that we stipulate. The syntax is: COMF <register>,d wherein <register is the register that we wish to reverse, and d will inform the PIC where to collect the result. If d=0, the result is saved in the W register. If d=1, the result is saved again into the register we assigned. The following example exhibits this instruction in practicality:0C = 11001100COMF 0C,10C = 00110011
Understanding Bit Operations
This could be utilized, for instance, to swiftly swap the pins of a port from output to input and so on. Bit functions permit us to shape a single bit within a expression. They permit us to proceed,set and get rid of single bits in registers or numbers that we stipulate.
At the conclusion of this course We will disclose a program designed to create a set of sequencing lights that proceed forward, then the reverse way. We observed this accomplished earlier when we examined the exclusive OR function, wherein we Exclusively ORed the ports with a expression. We have uptil now noticed a few bit functions when we establish the ports on the PIC, and
Let me reiterate their utilization here.
BCF
This instruction will wipe of a bit that we stipulate in a register that we designate. The syntax
is:
BCF <register>,<bit>
We employed this earlier to alter from page 1 to page 0 by removing a bit in the STATUS register. We are able to likewise use it to fix a bit to 0 in any different register/location. For instance, in case we wished to set the 3rd bit in 11001101 saved in section 0C to 0, we might
insert:
BCF 0C,03
BSF
This instruction would fix any bit we stipulate to 1 in any register that we indicate. We utilized this earlier to proceed from Page 0 to Page 1. The syntax is: BSF <register>,<bit>, and is utilized in precisely the same method as BCF above.
BTFSCUp to now we could set or clear a bit in a register. However imagine if we need to basically check if a bit is a 1 or a 0 in a register?
Surely, it is possible to use BTFSC. It states Bit Test Register F, and Skip If It Is Clear. This instruction is going to analyze the bit we designate in the register. In case the bit is a 0, the instruction would inform the PIC to by pass the subsequent instruction.
We might utilize this instruction in case we wished to check a flag, for example the carry flag. This spares us needing to read the STATUS register and searching for the individual bits to learn which flags are fixed. 29 For instance, in case we wished to check if the Carry flag was set to 1 after we had added 2 figures, then we could type the following:
BTFSC 03h,0
carry on here if set to 1
or here if set to 0
In case the status of the bit is a 1, in that case the instruction subsequent to BTFSC would be completed. In case it is set to a 0, in that case the subsequent instruction is skipped. The following part of code exhibits in which it might be employed:
Loop :
:
:
BTFSC 03,0
Goto Loop
In the above code, the PIC will simply get out of the loop in case bit 0 of the STATUS register (or the Carry flag) is defined to 0. Or else, the goto command would be conducted.
BTFSS
This instruction states Bit Test Register F, And Skip If Set. This can be comparable to the BTFSC instruction, apart from that the PIC would omit the subsequent instruction if the bit we have been evaluating is set to 1, instead of 0.
CLRF
This instruction would fix the whole details of a register to 0. The syntax is:
CLRF <register>
We employed this earlier to set the output of the Ports to 0, by applying CLRF 85h. We furthermore employed it to fix the Ports to include all pins to output by utilizing CLRF
05h.
CLRW
This could be resembling the CLRF instruction, except for clears the W register. The syntax is pretty simply:
CLRW
RLF And RRF
These directions would transport a bit in a register a single slot to the left (RLF) or the right (RRF) in a register. For instance, if we needed 00000001 and we employed RLF, in that case we might possess 00000010. At this point, what goes on in case there is 10000000 and applied the RLF instruction? Surely, the 1 would be positioned in the carry flag. In case we applied the RLF instruction once more, the 1 would reappear back at the start. The alike occurs, however in opposite, for the RRF instruction. The case in point below shows this for the RLF instruction, in which We have can see the 8 bits of a register, as well as the carry flag:
C 87654321
0 00000001
RLF 0 00000010
RLF 0 00000100
RLF 0 00001000
RLF 0 00010000
RLF 0 00100000
RLF 0 01000000
RLF 0 10000000
RLF 1 00000000
RLF 0 00000001
Example Program
We are now gonna see an example code that one can compile and drive. It would generate a sequencing light beginning at PortA bit 0, going to PortB bit 8 and
then returning.
Hook up LEDs to each one of the Port pins. We will have some of the bit
procedures pointed out in this tutorial.
TIME EQU 9FH ; Variable for the delay loop.
PORTB EQU 06H ; Port B address.
TRISB EQU 86H ; Port B Tristate address.
PORTA EQU 05H ; Port A address.
TRISA EQU 85H ; Port A Tristate address.
STATUS EQU 03H ; Page select register.
COUNT1 EQU 0CH ; Loop register.
COUNT2 EQU 0DH ; Loop register.
BSF STATUS,5 ; Go to page 1
MOVLW 00H ; and set up
MOVWF TRISB ; both Ports A and B
MOVLW 00H ; to output,
MOVWF TRISA ; then return to
BCF STATUS,5 ; page 0.
MOVLW 00H ; Clear Port A.
MOVWF PORTA ;
; Start of main program
RUNMOVLW
01H ; Set the first bitMOVWF
PORTB ; on Port B.CALL
DELAY ; Wait a whileCALL
DELAY ;;
Move the bit on Port B left, then pause.RLF
PORTB,1CALL
DELAYCALL
DELAYRLF
PORTB,1CALL
DELAYCALL
DELAYRLF
PORTB,1CALL
DELAYCALL
DELAYRLF
PORTB,1CALL
DELAYCALL
DELAYRLF
PORTB,1CALL
DELAYCALL
DELAYRLF
PORTB,1CALL
DELAYCALL
DELAYRLF
PORTB,1CALL
DELAYCALL
DELAYRLF
PORTB,1 ; This moves the bit into the carry flag;
Now move onto Port A, and move the bit left.RLF
PORTA,1 ; This moves the bit from the zero flag into PortACALL
DELAYCALL DELAYRLF
PORTA,1CALL
DELAYCALL
DELAYRLF
PORTA,1CALL
DELAYCALL
DELAYRLF
PORTA,1CALL
DELAYCALL
DELAY;
Move the bit back on Port ARRF
PORTA,1CALL
DELAYCALL
DELAYRRF
PORTA,1CALL
DELAYCALL
DELAYRRF
PORTA,1CALL
DELAYCALL
DELAYRRF
PORTA,1 ; This moves the bit into the zero flag; Now move the bit
back on Port BRRF
PORTB,1CALL
DELAYCALL
DELAYRRF
PORTB,1CALL
DELAYCALL
DELAYRRF
PORTB,1CALL
DELAYCALL
DELAYRRF
PORTB,1CALL
DELAYCALL DELAYRRF
PORTB,1CALL
DELAYCALL
DELAYRRF
PORTB,1CALL
DELAYCALL
DELAYRRF
PORTB,1CALL
DELAYCALL
DELAY ; Now we are back where we started, ;GOTO
RUN ; let's go again.
There exists a great option in the training set that permits you to make use of a data table.
A data table is just a list of data quotes, in which all is looked over based on a few considerations.
For instance, you could have a circuit that utilizes a PIC which counts the quantity of instances an input pin becomes high in 1 second. After that you can exhibit the number on a 7 segment display.
As soon as the timing has launched, the PIC starts counting the quantity of occasions the pin goes high. After 1 second it visits the table and glances up the data it must display the number on the display that symbolizes the amount of situations the pin got high. This can be beneficial, since we don’t determine what the figure could be until the PIC has accomplished its estimate.
By utilizing a table, we are able to allow the PIC determine which figure to portray. At this point, before I continue to show you how the data table functions, I might have to tell you that the PIC maintains path of whereabouts in the program it is whilst the program is operating.
It facilitates for those who have performed certain programming in BASIC. Otherwise, don’t be anxious, you might want to continue to learn about the theory. Envision there is a BASIC program similar to the one presented below:
10 LET K=0
11 K=K+1
12 IF K>10 THEN GOTO 20 ELSE GOTO 11
20 PRINT K
21 END
The program begins at line 10. As soon as K is scheduled to 0, it next advances to line 11. After we have included 1 to K we after that proceed to line 12.
At this point we might be curious if K is higher than 10. In case it is, next we head to line 20, or else we return to line 11.
Line 20 documents the K, and line 21 concludes the program. BASIC employs line statistics to assist the programmer keep a record of where issues are, as labels are not authorized. The PIC employs labels to escape between destinations – or can it really?
We utilize the labels to ensure that we be aware of where issues are, as well as to ensure we are able to inform the PIC in a simple way where to search.
Precisely what occurs is the PIC takes advantage of an inner line counter called a Program Counter. The Program Counter (abbreviated to PC) trail of the memory destination of where the present instruction is.
Whenever we inform the PIC to visit a selected label, it understands the memory spot and therefore augments the PC until it sees that memory destination. This is precisely the same method as we check out the BASIC program above. Below is a segment of code, with the memory spaces, or the items of the PC, beside every instruction:
PC Instruction0000 movlw 03
0001 movwf 0C
0002 Loop decfsc 0C
0003 goto Loop
0004 end
In the demonstration above, We have fixed the PC to 0000. On this we have the instruction movlw 03. When the PIC has implemented this data, it increments the PC in order that the subsequent instruction is scanned. At this point the PIC views movwf 0C. The PC is incremented yet again.
Now the PIC studies decfsc 0C. In case the details of 0C are not 0, in that case the PC is incremented by 1, as well as the following instruction, goto Loop, informs the PC to return to position 0003, which there is the said Loop. In case the details of 0C is 0, then the PC is advised to increment by 2, put simply omit the subsequent instruction.
Understanding Data Tables
This places the PC at position 0004, wherein the program finishes. The destinations are fixed by the assembler, and we don’t generally ought to be concerned what the PC is accomplishing. Until, we find the need to bring it under control just like while we do when utilizing data tables. The most convenient way to describe how a data table functions, is to begin with an illustration.
PC equ 02
movlw 03
call table
:
table addwf PC
retlw 01
retlw 02
retlw 03
retlw 04
retlw 05
retlw 06
retlw 07
return
The initial instruction is allocating the label PC with the address of the Program Counter (02h). We will be soon after putting the value of 03h into the w register. We after that communicate to table. The foremost line in the subroutine table augments the details of the W register (03h) to the program counter.
This triggers the program counter to raise by 3, or to put it a different way, stimulates the program counter to proceed down 3 lines. While the counter arrives 3 lines down it the PIC recognizes the instruction retlw. This command sends the value following it into the W register, after which comes back from the subroutine. RETLW basically signifies Return, Literal to W.
See I placed a comma after the word Return. Since we are in a subroutine, we require a Return instruction to surface of it. Therefore the RET in the instruction. After the RETLW instruction is a number, and this is exactly what is put into the W register.
In this instance it is the figure 3. We could designate any quantity to the W register, so long as this figure is combined with the Program Counter in the table subroutine, we are going to discover a retlw instruction. In the above illustration this implies we are able to possess any number from 1 to 7. In case we proceed past the subroutine, we might be able to finish up performing an additional section of the program. For this reason, it is usually a smart move to place the data table exactly towards the end of the PIC program, therefore if we do overshoot in that case we are going to arrive at the conclusion of the program anyhow.
The topic of interrupts may well gonna be the lengthiest and toughest to go thru.
You cannot find any uncomplicated method of detailing interrupts, however with a little luck towards the end of this part you may be able to apply interrupts into your own programs.
We have separated the section into 2 stages. That is to enable separate the topic into sections, also to provide you with an handy plit up for easy understanding.
What exactly is an interrupt? Surely, as the term indicates, an interrupt is a technique or a signal that prevents a microprocessor/microcontroller from whatever thing its performing that something different could happen.
Allow me to give you an daily illustration. Think you are relaxing in your own home, conversing to another person. All of a sudden the phone sounds.
You quit talking, and grab the telephone to talk to the caller. Once you have your telephone interaction, you decide to return to conversing to the individual before the telephone rang. It is possible to consider the principal routine while you chatt to somebody, the phone ringing brings about to disrupt your conversing, and the break in routine is the method of speaking on the phone.
While the phone discussion comes to an end, then you go back to your primary routine of chatting. This illustration is precisely how an interrupt a processor to take action.
The primary program is operating, carrying out certain function in a circuit, however when an interruption takes place the primary program halts while a different routine is performed. routine ends, the processor moves back to the primary routine just as before.
Understanding Interrupts
The PIC possesses 4 sources of interrupt. They could be broken down into a couple of groups. Two are sources of interrupts which can be utilised outwardly to the PIC, whilst the other two are inner processes. Let me clarify the two external types here. The other two is going to be described in different tutorials once we arrive at timers and storing data.
Should you check out the pin-out of the PIC, you will notice that pin 6 it is RB0/INT. At this point, RB0 is clearly Port B bit 0. The INT represents that it could as well be configures as an outside interrupt pin. Furthermore, Port B pins 4 to 7 (pins 10 to 13) may also be utilized for interrupts. Before we are able to employ the INT or another Port B pins, we must accomplish two tasks. Very first we must inform the PIC that we will utilize interrupts.
Next, we must designate which port B pin we are going to be utilising as an interrupt rather than as an I/O pin. Inside the PIC you can find a register known as INTCON, and is at address 0Bh. In this register you will discover 8 bits that may be enabled or disabled. Bit 7 of INTCON is known as GIE. This is the Global Interrngupt Enable. Fixing this to 1 informs the PIC that we will employ an interrupt.
Bit 4 of INTCON is known as INTE, INTerrupt Enable. Putting this bit to 1 conveys to the PIC that RB0 is going to be an interrupt pin. Configuring bit 3, called RBIE, informs the PIc that we are going to be utilizing Port B bits 4 to 7. At this point the PIC understands when this pin can be high or low, have to halt what it’s performing and proceed with an interrupt routine. At this point, we must inform the PIC whether or not the interrupt will likely be on the ascending edge (0V to +5V) or the dropping edge (+5V to 0V) transformation of the signal.
Put simply, do we wish the PIC to interrupt each time the signal moves from low to high, or from high to low. By delinquency, this can be established to be placed on the rising edge.
The edge ‘triggering’ is scheduled up in an additional register called the OPTION register, at address 81h. The bit we are enthusiastic about is bit 6, often referred to as INTEDG.
Setting this to 1 triggers the PIC to disrupt on the mounting edge (default state) and setting it to 0 stimulates the PIC to disrupt on the sliding edge. If you would like the PIC to activate on the rising edge, then you certainly don’t have to do anything to this bit.
At this point, sadly, the Option register is in Bank 1, meaning that we enjoy to modify from bank 0 to bank 1, set the bit in the Option register, after that return to bank 0. The key here is to accomplish every bit of the Bank 1 registers in a single strike, for example establishing the port pins, after that returning to Bank 0 if you are done.
Fine, consequently we have notified the PIC which pin will probably be the interrupt, and where edge to trigger, what goes on in the program and the PIC any time the interrupt happens? A couple of stuff take place. Very first, a ‘flag’ is scheduled.
This informs the internal processor of the PIC that an interrupt has transpired. Next, the program counter (which I talked about within the previous tutorial) tips to a specific address within the PIC. Let’s swiftly check out all these individually. Interrupt Flag In our INTCON register, bit 1 is the interrupt flag, called INTF. At this point, whenever any interrupt arises, this flag will likely be fixed to 1.
When there isn’t an interrupt, the flag is placed to 0. As well as that is just about all accomplishes. At this point you may be pondering ‘what is the point?’ Surely, even though this flag is scheduled to 1, the PIC is not able to, and will not, react to another interrupt. Therefore, let’s express that we bring about an interrupt. The flag will likely be fixed to 1, and the PIC might go to our routine for working the interrupt.
When this flag wasn’t fixed to 1, and the PIC was permitted to continue answering the interrupt, then continuously pulsing the pin could keep the PIC returning to the beginning of our interrupt routine, and by no means completing it. Returning to my illustration of the telephone, it’s similar to lifting the telephone, and immediately once proceeding to discuss it begins ringing yet again since another person wishes to speak with you.
It is advisable to complete one dialogue, then grab the phone again to speak with the subsequent individual. You can find a small problem with this flag. Even though the PIC quickly sets this flag to 1, it doesn’t set it again 0! That activity must be exercised by the programmer – i.e. you. This can be effortlessly accomplished, since I’m certain presume, and needs to be achieved after the PIC has carried out the interrupt routine.
Memory Location Whenever you initially power up the PIC, or in case there exists a reset, the Program Counter tips to address 0000h, that could be immedaitely at the outset of the program memory. But, in the event there is an interrupt, the Program Counter would indicate address 0004h.
Therefore, while we are composing our program that will have interrupts, we firstly must inform the PIC to hop over address 0004h, and maintain the interrupt routine which begins at address 0004h discrete from the remainder of the program.
This can be hassle-free to perform. Initially, we commence our program with a command known as ORG. This command indicates Origin, or start. We stick to it with an address. Since the PIC commences at address 0000h, we type ORG 0000h. After that we must bypass over address 0004h. We accomplish this by putting a GOTO instruction, accompanied by a label which tips to our primary program.
We after that adhere to this GOTO command with one more ORG, this moment with the address 0004h. It will be after this command that we insert our interrupt routine. At this point, we might be able to possibly type in our interrupt routine straight following the second ORG command, or we are able to position a GOTO statement which points to the interrupt routine.
It truly is related to option on your part. To inform the PIC it offers arrived at the conclusion of the interrupt routine we must position the command RTFIE towards the end of the routine. This command signifies return from the interrupt routine. While the PIC notices this, the Program Counter indicates to the final position the PIC was at before the interrupt occurred. We have established below a brief section of code to display the above:
There are a couple of stuffs you should be informed when utilizing interrupts. The initial tends to be that if you might be utilizing the identical register in your primary program and the interrupt routine, in mind that the details of the register will most likely alter when the interrupt takes place.
For instance, let’s utilizing the w register to forward data to Port A primary program, therefore you can be additionally utilizing the w register in the interrupt routine to shift data from one destination to another.
In case you are not cautious, the w register would include the last value it received while it had been in the interrupt routine, so when you return from the interrupt this information is going to be delivered to Port A rather than the value you possessed before the interrupt occurred.
The means around this is to momentarily save the details of the w register prior to when you utilize it once again in the interrupt routine. The second is the fact you can find a delay between when one interrupt takes place and when the subsequent one can arise. While you understand, the PIC possesses an exterior clock, which could possibly be a crystal or it could be a resistor-capacitor combo.
No matter what the frequency of this clock, the PIC divides it by 4 after which employs this for it’s inner timing. For instance in case you have a 4MHz crystal linked to your PIC, in that case the PIC would perform the instructions at 1MHz. This interior timing is known as an Instruction Cycle. At this point, the data sheet claims (undoubtedly in diminutive print) that you need to enable 3 to 4 instruction rounds between interrupts.
My would be to enable 4 rounds. The reason behind the delay is the PIC requires time to leap to the interrupt address, the flag, and arrive back away from the interrupt routine. Therefore, keep this in your mind if you work with an alternate circuit to activate an interrupt for the PIC.
At this point, a point to is the fact that if you utilize bits 4 to 7 of Port B as an interrupt. You are unable to choose specific pins on Port B to function as an interrupt.
Therefore, in case you allow these pins, they likely could be all obtainable. Therefore, for instance, you can’t simply have bits 4 and 5 – bits 6 and 7 will likely be empowered at the same time. What exactly is the purpose of getting four bits to represent an interrupt? Surely, you might have a circuit hooked up to the PIC, in case anyone of four lines go high, in that case this may be an issue that you require the PIC to influence instantly.
One illustration of this could be a home security alarm, in which four sensors are linked to Port B pins 4 to 7. Any specific sensor can prompt the PIC to trigger an alarm, and the alarm signaling routine is the interrupt routine. This spares checking the ports constantly and permits the PIC to continue with different matters. Within the next tutorial, we are going to compose a program to manage an interrupt.
We dealt with a lot of basics within the last tutorial, therefore I feel the time has come that we composed our first program.
The program we will write would count the quantity of occasions we turn a switch on, and then exhibit the number.
The program would count from 0 to 9, viewable on 4 LEDs in binary form, along with the input or interrupt will likely be on RB0.
The number one thing we must conduct is inform the PIC to leap over the address in which the Program Counter points to whenever an interrupt takes place.
You will observe that We are employing an unique method of exhibiting hexadecimal numbers. Before I happened apply F9h in which h indicated hexadecimal. We could write this as 0xF9, which is the structure we are going to employ from now on.
Now we need to tell the PIC that we are going to use interrupts, and we are using RB0 pin 6 as an interrupt pin:
bsf INTCON,7;GIE – Global interrupt enable (1=enable)
bsf INTCON,4;INTE - RB0 interrupt enable (1=enable)
I am going to clear the interrupt flag just in case (I never trust anything!)
bcf INTCON,1;INTF - Clear flag bit just in case
Currently we must establish our 2 ports. Keep in mind that as we are now utilizing RB0 as an interrupt pin, this needs to be established as an input:
We are going to use a variable called COUNT to store the number of switch counts. We could just simply increment the value on Port A, but you will see why I am using a variable when we write our interrupt routine.
Therefore, our principal program is composed, and at this point we must inform the PIC how to proceed whenever an interrupt takes place. Within this example, our interrupt will probably be the switch. Just what we would like the PIC to is one to the adjustable COUNT every time the switch is confined.
Nevertheless, we just wish to show the how many occasions the switch shuts from 0 to 9. Above, I stated we might be able to have simply incremented the value on Port A every time there is an interrupt. However, Port A has 5 bits, in case we simply incremented the port, we are going to possess the highest count of 31. There are a couple of explanations why I selected not to move up to 31.
Initially, we will employ a 7-segment screen, which could at the most only go from 0 to 15 (0 to F in hex). Next, I additionally wish to show you a few of the arithmetic commands which you stumbled on in the past few lessons.
Therefore we will continue with our interrupt routine. Currently the firstly we must accomplish is briefly store the details of our w register, since we have been applying this to shift the contents of COUNT to PORTA. In case we don’t save it, in that case we might be able to deliver a totally different number because of our arithmetic. Therefore let’s accomplish that first:
At this point we we understand if the value of COUNT is 9 or more. Just what we need to accomplish now is if COUNT is more than 9, place it back to 0, or else return to the main program to ensure that we are able to deliver it to Port A. The BTFSS command since you understand would the subsequent
instruction in case the carry flag is scheduled i.e COUNT = 10:
The only thing which is remaining to do now is enter collectively as well as determine values to our constants, which we are able to perform right at the start of our program.
Each time you activate the switch on, the LEDs are going to count up in binary from 0000 to 1010 then back to 0000.
The following figure shows the circuit diagram compatible with the above explained code. Interestingly you will find that the timing capacitor has been included in the design. This is nice little ploy through which you get the freedom of avoiding the inclusion of the capacitor in case you don't have any with you during that time.
Here the capacitance comes into play via the stray capacitance across the oscillator pin and ground.
Of course it might not seem to be a very intelligent way of avoiding a capacitor practically since the stray value might vary with different given conditions.
Another section which can be witnessed in the circuit is the denouncing network across the switch. This prevents interference while mechanical switching and prevents the PIC from getting confused if the switching was a single toggle or multiple toggles.
Have Questions? Please Comment below to Solve your Queries! Comments must be Related to the above Topic!!