You are on page 1of 84

Now, the personal computer which you are using is working with the software.

The software is the one


to have written the operation order of the hardware (the personal computer). It is possible to make do
the various operation to the hardware when making memorize this procedure at the memory and making
execute it in the order. It is possible to make do the operation which is different with the same hardware
by changing the software. It is very convenient.

On these pages, I will introduce the electronic circuits making which used the PIC(Peripheral Interface
Controller) which is the one-chip microprocessor.
I will make this page for the beginner of PIC including me.

What is the PIC ?

Hardware of the PIC16F84A

Hardware of the PIC16F873

Instructions of PIC16 series


Radix
General format for instructions
Instruction set
Instruction spec (1) ADDLW ADDWF ANDLW ANDWF
Instruction spec (2) BCF BSF BTFSC BTFSS
Instruction spec (3) CALL CLRF CLRW CLRWDT
Instruction spec (4) COMF DECF DECFSZ GOTO
Instruction spec (5) INCF INCFSZ IORLW IORWF
Instruction spec (6) MOVF MOVLW MOVWF NOP
Instruction spec (7) RETFIE RETLW RETURN RLF
Instruction spec (8) RRF SLEEP SUBLW SUBWF
Instruction spec (9) SWAPF XORLW XORWF

Software making for PIC


About the software
Software making procedure
Acquirement of the software development tool and Iinstallation
Initial setting of the software development tool
How to make software
How to debug

Guidelines to make the Source Code


Directive Summary

PIC Programmer

PIC Circuits Gallery


 

Instructions of PIC16 series

Radix
In the software of the computer, hexadecimal is often used.
Decimal
In our daily life, 10 numbers from "0" to "9" are used.
In case of the count-up, after 9, the carry is done and becomes 10. We are using properly but this is
the count method of the number which the human being decided.
This seems to depend on that the fingers of the hand of the person is 10.

Binary
Only two values of "0" and "1" are used to express a condition by the digital world which included a
computer. These are sometimes expressed by "Low level " and "High level ", too.
Like 0 1 10, after 1, it is 10.

Hexadecimal
In the condition to be handling with the computer, it is a binary number but it is difficult to
understand for the person who is using the decimal.
163(Decimal) 10100011(Binary)
Therefore, a hexadecimal is used as the expression which it is easy for the person to understand. As
for the hexadecimal, 16 numbers are used for 1 digit. It is from 0 to 9 that it is expressed by the
figure. So, six of the remainder are expressed by the alphabet.
10 A, 11 B, 12 C, 13 D, 14 E, 15 F
The figure has begun with 0. Therefore, 10 of the figure shows the 11th and 15 shows the 16th.
16 kinds of conditions are expressed by 4 bits in the binary. Oppositely, the hexadecimal is used
because that it is possible to express 16 by 4 bits. There is the octal which is expressed by 3 bits. In
case of the hexadecimal, 1 byte is expressed by 2 digits.
Also, it puts "h" to distinguish the hexadecimal from the decimal. h is the initial of hexadecimal(16).
It shows in 00h or H'00' or 0x00. However, an expression isn't unified.

The correspondence of radix


The correspondence of Binary, Decimal and Hexadecimal is as follows.
Decimal Binary Hexdecimal Decimal Binary Hexdecimal
0 0 0h 100 1100100 64h
1 1 1h 127 1111111 7Fh
2 10 2h 128 10000000 80h
3 11 3h 200 11001000 C8h
4 100 4h 255 11111111 FFh
5 101 5h 256 100000000 100h
6 110 6h 300 100101100 12Ch
7 111 7h 400 110010000 190h
8 1000 8h 500 111110100 1F4h
9 1001 9h 511 111111111 1FFh
10 1010 Ah 512 1000000000 200h
11 1011 Bh 600 1001011000 258h
12 1100 Ch 700 1010111100 2BCh
13 1101 Dh 800 1100100000 320h
14 1110 Eh 900 1110000100 384h
15 1111 Fh 1000 1111101000 3E8h
16 10000 10h 1023 1111111111 3FFh
17 10001 11h 1024 10000000000 400h
18 10010 12h 2000 11111010000 7D0h
19 10011 13h 2047 11111111111 7FFh
20 10100 14h 2048 100000000000 800h

The change of Binary, Decimal and Hexadecimal can make simple if you use the function electronic
calculator which is attached to the Windows.
When changing without using the calculator, it is possible to do in the following way.
It is possible to change simply if dividing 4 bits.
It is easier if learning a binary pattern to Fh from Ah.
EX. 111000100100010000100 1C4884h
It is possible to change 1 digit of the hexadecimal into the binary in the order.
EX. 5F37Bh 1011111001101111011
This is troublesome a little.
First, you write a decimal value every bit like
the following figure. Total the decimal value of
the bit of "1".
EX.

512 + 256 + 128 + 8 + 4 + 1 = 909


This is terrible a little, too.
Subtract the maximum number of power of
two(1,2,4,8,16,32,64,128,256,512,1024,...) which can be subtracted from the decimal
number.
It makes the bit which corresponds to the number of power of two which could be
subtracted to "1".
Subtract the number of power of two which could be subtracted from the remainder
more.
Hereinafter, repeat similar subtraction until the remainder passes away.
The row of "1" and "0" by above result is a binary number.
EX. "582"
582 - 512 = 70
70 - 64 = 6
6-4=2
2-2=0

Change a decimal into the binary first and change a result into the hexadecimal more.
In case of the example(D B) which was shown above, 582 = 1001000110 = 246h.

When changing directly, there is a way of dividing by the value of 4 bits.


582 / 256 = 2 remainder 70
70 / 16 = 4 remainder 6
The result is 246h.
Change a hexadecimal into the binary first and change a result into the decimal more.
In case of the example(B D) which was shown above, 38Dh = 1110001101 = 909

When changing directly, there is a way of multiplying the value of 4 bits.


3 x 256 = 768
8 x 16 = 128
The result is 768 + 128 + 13(Dh) = 909.

Still, it is easy to calculate using the function electronic calculator.

2's Complement
The 2's complement is the one which shows negative numerical value.
For example, "-1" of the decimal number is 11111111 when showing by the binary with byte.
It is as follows when confirming.

The overflow occurs but the numerical value becomes zero.


A binary addition is done from the lower rank figure like the decimal number. When there is a carry,
it calculates a higher rank figure including it.

To use a negative value, there is a condition.


The numerical value which it is possible to show at the byte is 256 kinds of 0 to 255. However, when
using the negative value, it becomes 255 kinds of - 127 to +127. The reason why the numbers are
few is because 10000000 isn't used. The row of these bits shows -0 but in the calculation, it can not
use. Most significant bit 7 is used as the sign bit which shows negative or positive. The type with
numerical value must be considered when processing it.
For example, it is 10000001 when showing -127 in the binary number. It becomes 129, supposing
that this is only plus numerical value.

A change into the 2's complement is done as follows.

I attempt to change 56 into -56 as the example.


(1) Subtract 1 from the value 56 - 1 = 55
(2) Change this into the binary 55 00110111
(3) It makes 0 and 1 opposite 00110111 11001000

11001000 is the binary number which shows -56.

It is as follows when confirming.

The answer became zero.

General format for instructions


The format for instructions of PIC16 series is the following three kinds. The instructions are written in the
program memory and one instruction is composed of 14 bits. These 14 bits are called a word.
Byte-oriented file register operations
The instructions of this format are the instructions which processes a byte unit.

OPECODE
The code to distinguish a instruction is written.
:

d (Destination select) It specifies the register which stores the execution result of the instruction.
: d=0 : It specifies working register ( W reg ).
d=1 : It specifies file register which is specified by f.
In case of the assembler language, d is written in W or F.
(EX) ADDWF COUNT,W ( d=0 when writing W )
ADDWF COUNT,F ( d=1 when writing F )

f (Register file) : It specifies the address of the register which is dealt with for the instruction.
f can specify an address from 0(00h) to 127(7Fh) because it is 7 bits.
In case of PIC16F84A, because the register memory is 80 bytes including SFR, it is
possible to be specified by f if being 7 bits.
When writing by the assembler language, the label is put to the register and uses.
(EX) ADDWF COUNT,F ( COUNT is the label of the register)

Bit-oriented file register operations


The instructions of this format are the instruction which processes a bit unit.

OPECODE : The code to distinguish a instruction is written.

b (Bit address) : It specifies the bit position of the register file.


Because the register file is a byte, it can specify all bit positions with 3-bit b.

f (Register file) : It specifies the address of the register which is dealt with for the instruction.
f can specify an address from 0(00h) to 127(7Fh) because it is 7 bits.
In case of PIC16F84A, because the register memory is 80 bytes including SFR, it is
possible to be specified by f if being 7 bits.
When writing by the assembler language, the label is put to the register and uses.

Literal and control operations


The instructions of this format do the processing which used the fixed number (k) which was
written in the instruction.
There are two instruction types and fixed number (k) is 11 bits about GOTO and CALL instruction.
In case of GOTO and CALL instruction

OPECODE : The code to distinguish a instruction is written.

k (Literal field) : This is the fixed number to use for the calculation.
It specifies by the numerical value or the label.
Because it is a byte except JUMP and CALL instruction, it is the range of 0(00h) to
255(FFh).
Because GOTO or CALL instruction is 11 bits, it is the range of 0(00h) to
2047(7FFh).
 

Instruction set of PIC16 series

In PIC16 series, RISC(Reduced Instruction Set Computer) is adopted and the number of the instructions to
use is 35 kinds.
When clicking the mnemonic of each instruction, you can jump to the instruction specification.
The terminology explanation
Mnemonic : The assembler language which made an operation code plain
Operands : The specification part except the operation code
MSb : Most Significant bit
LSb : Least Significant bit
Flag : The field of the STAUS register

Mnemonic Instruction code


Operation explanation Flag
Operands

Byte-oriented file register operations

ADDWF f, d Add W and f C, DC, Z

ANDWF f, d AND W with f Z

CLRF f Clear f Z

CLRW - Clear W Z

COMF f, d Complement f Z

DECF f, d Decrement f Z

DECFSZ f, d Decrement f, Skip if 0

INCF f, d Increment f Z

INCFSZ f, d Increment f, Skip if 0

IORWF f, d Inclusive OR W with f Z

MOVF f, d Move f Z

MOVWF f Move W to f

NOP - No Operation

RLF f, d Rotate Left f through Carry C


RRF f, d Rotate Right f through Carry C

SUBWF f, d Subtract W from f C, DC, Z

SWAPF f, d Swap nibbles in f

XORWF f, d Exclusive OR W with f Z

Bit-oriented file register operations

BCF f, b Bit Clear f

BSF f, b Bit Set f

BTFSC f, b Bit Test f, Skip if Clear

BTFSS f, b Bit Test f, Skip if Set

Literal and control operations

ADDLW k Add literal and W C, DC, Z

ANDLW k AND literal with W Z

CALL k Call subroutine

CLRWDT - Clear Watchdog Timer

GOTO k Go to address

IORLW k Inclusive OR literal with W Z

MOVLW k Move literal to W

RETFIE - Return from interrupt

RETLW k Return with literal in W

RETURN - Return from Subroutine

SLEEP - Go into stanby mode

SUBLW k Subtract W from literal C, DC, Z

XORLW k Exclusive OR literal with W Z

x : Don't care
Detail specification of PIC16F84A(1)
On this page, I will explaine about the specification of the contents of the various registers of the PIC16F84A.

Each SFR has the following function.

INDF : Data memory contents


by indirect addressing
TMR0 : Timer counter
PCL : Low order 8 bits of the
program counter
STATUS : Flag of the calculation
result
FSR : Indirect data memory
address pointer
PORTA : PORTA DATA I/O
PORTB : PORTB DATA I/O
EEDATA : Data for EEPROM
EEADR : Address for EEPROM
PCLATH : Write buffer for upper 5
A part of the figure above is the clickable image map. bits of the program
counter
INTCON : Interruption control
OPTION_REG : Mode set
TRISA : Mode set for PORTA
TRISB : Mode set for PORTB
Control Register for
EECON1 :
EEPROM
EECON2 : Write protection Register
for EEPROM

A color of INDF and EECON2 is changed because the way of using these registers is different from the other
register.

SFR(Special Function Registers)


The 12 bytes at the head of the RAM file register are used as SFR. These register groups are very important to
the operation of the PIC. I will explain the registers which is necessary to manage the condition of the PIC
below.
STATUS Register ( RAM Memory Address 03h,83h )
R= Readable bit
W= Writable bit
-n = Value at POR reset
Bit6,7 = Unimplemented bit
Bit7: Register Bank Select bit(used for indirect addressing)
IRP The IRP bit is not used by the PIC16F84A.
IRP should be maintained clear.
Bit6,5: Register Bank Select bit(used for direct addressing)
RP1,RP0 Only bit RP0 is used by the PIC16F84A.
'0' means Bank0, '1' means Bank1.
RP1 should be maintained clear.
Bit4: Time-out bit
TO(inv) 1 = After power-on,CLRWDT instruction,or SLEEP instruction
0 = Watchdog time-out occurred
Bit3: Power-down bit
PD(inv) 1 = After power-on or by the CLRWDT instruction
0 = By execution of the SLEEP instruction
Bit2: Zero bit
Z 1 = The result of an arithmetic or logic operation is zero

0 = The result of an arithmetic or logic operation is not zero


Bit1: Digit carry/borrow(invert) bit (for ADDWF and ADDLW)
DC 1 = A carry-out from the 4th low order bit of the result occurred
0 = No carry-out from the 4th low order bit of the result
Bit0: Carry/borrow(invert) bit (for ADDWF and ADDLW)
C 1 = A carry-out from the most significant bit of the result occurred
0 = No carry-out from the most significant bit of the result occurred

OPTION_REG Register ( RAM Memory Address 81h )


R = Readable bit
W = Writable bit
-n = Value at POR reset

Bit7: PORTB Pull-up Enable bit


RBPU(inv) 1 = PORTB pull-ups are disabled
0 = PORTB pull-ups are enabled (by individual port latch values)
Bit6: Interrupt Edge Select bit
INTEDG 1 = Interrupt on rising edge of RB0/INT pin
0 = Interrupt on falling edge of RB0/INT pin
Bit5: TMR0 Clock Source Select bit
T0CS 1 = Transition on RA4/T0CKI pin
0 = Internal instruction cycle clock (CLKOUT)
Bit4: TMR0 Source Edge Select bit
TOSE 1 = Increment on high-to-low transition on RA4/T0CKI pin
0 = Increment on low-to-high transition on RA4/T0CKI pin
Bit3: Prescaler Assignment bit
PSA 1 = Prescaler assigned to WDT
0 = Prescaler assigned to TMR0
Bit2-0: Prescaler Rate Select bits
PS2-0 PS2 PS1 PS0 TMR0 WDT
0 0 0 1:2 1:1
0 0 1 1:4 1:2
0 1 0 1:8 1:4
0 1 1 1:16 1:8
1 0 0 1:32 1:16
1 0 1 1:64 1:32
1 1 0 1:128 1:64
1 1 1 1:256 1:128

INTCON Register ( RAM Memory Address 0Bh, 8Bh )


R = Readable bit
W = Writable bit
-n = Value at POR reset

Bit7: Global Interrupt Enable bit


GIE 1 = Enables all un-masked interrupts
0 = Disables all interrupts
Bit6: EEPROM Write Complete Interrupt Enable bit
EEIE 1 = Enables the EEPROM write complete interrupt
0 = Disables the EEPROM write complete interrupt
Bit5: TMR0 Overflow Interrupt Enable bit
T0IE 1 = Enables the TMR0 interrupt
0 = Disables the TMR0 interrupt
Bit4: RB0/INT Interrupt Enable bit
INTE 1 = Enables the RB0/INT interrupt
0 = Disables the RB0/INT interrupt
Bit3: RB Port Change Interrupt Enable bit
RBIE 1 = Enables the RB port change interrupt
0 = Disables the RB port change interrupt
Bit2: TMR0 Overflow Interrupt Flag bit
T0IF 1 = TMR0 has overflow (must be cleared in software)
0 = TMR0 did not overflow
Bit1: RB0/INT Interrupt Flag bit
INTF 1 = The RB0/INT interrupt occurred (must be cleared in software)
0 = The RB0/INT interrupt did not occurred
Bit0: RB Port Change Interrupt Flag bit
RBIF 1 = When at least one of the RB7:RB4 pins changed state (must be cleared in software)
0 = None of the RB7:RB4 pins have changed state

EECON1 Register ( RAM Memory Address 88h )


R= Readable bit
W= Writable bit
S= Settable bit
U= Unimplemented bit
-n = Value at POR reset
Bit7-5: Read as "0"
Unimplemented
Bit4: EEPROM Write Operation Interrupt Flag bit
EEIF 1 = The write operation completed (must be cleared in software)
0 = The write operation is not complete or has not been started
Bit3: EEPROM Error Flag bit
WRERR 1 = A write operation is prematurely terminated
0 = The write operation completed
Bit2: EEPROM Write Enable bit
WREN 1 = Allows write cycles
0 = Inhibits write to the data EEPROM
Bit1: EEPROM Write Control bit
WR 1 Initiates a write cycle (The bit is cleared by hardware once write is complete. the
= WR bit can only be set(not cleared) in software.)
0
Write cycle to the data EEPROM is complete
=
Bit0: EEPROM Read Control bit
RD 1 Initiates an EEPROM read (read takes one cycle. RD is cleared in hardware. The
= RD bit can only be set(not Cleared) in software)
0
Does not initiate an EEPROM read
=

INDF Register ( RAM Memory Address 00h )


This register is the register to use when reading and writing the contents
of the memory by the indirect addressing method.
When reading a memory by the direct address method, a memory
address is directly designated in the instruction code.
The example of the direct address method
movwf 30h
In this case, memory address (30h) is specified in the
instruction code and becomes 00 0000 1011 0000 .
The red part is the instruction code which shows
movwf, the blue part(one bit) is writing specification
to the file register (the fixation) and the green part is
the memory address.
In this case, to read and write a continuously memory, the instruction
must be written every memory. When reading and writing a
continuously memory, the indirect addressing method is convenient.

When reading and writing a memory by the indirect addressing method,


it sets the address of the memory to the FSR register. The memory
contents of the address which was specified by the FSR register can be
read and written through the INDF register. That is, the INDF register is
a relay register with the actual memory.
If adding the content of FSR when using this way, the contents of the
following memory are linked to INDF. The memory address can be
changed by the calculation even if it doesn't make each instruction.

EECON2 Register ( RAM Memory Address 89h )


When writing data to the EEPROM, the writing in the EEPROM becomes possible by writing 55h and
AAh in the order at this register.
The data which was written in the EEPROM doesn't disappear even if it switches off the power.
Therefore, when wrong writing is done, even if it turns on the power again, it doesn't return to the origin.
So, this sequence is for the abnormally data to make not be written by the wrong processing. But, when
this sequence is used by the wrong processing, it isn't possible to protect.

The sample of the writing sequence of the EEPROM is shown below.


The red part is protection sequence.
bsf status,rp0 ;Change to Bank1
bcf intcon,gie ;Disables all interrupts
bsf eecon1,wren ;Allows write cycles
movlw h'55' ;Set 55h data
movwf eecon2 ;Write 55h to EECON2
movlw h'aa' ;Set AAh data
movwf eecon2 ;write AAh to EECON2
bsf eecon1,wr ;Initiates a write cycle
bsf intcon,gie ;Enables all un-masked interrupts

Configuration Word ( Program Memory Address 2007h )

R= Readable bit
P= Programmable bit
-n = Value at POR reset
u= Unchanged
Bit13-4: Code Protection bit
CP 1 = Code protection off
0 = All memory is code protected
Code protection is used to prevent from the reading of the memory contents of the
PIC.
It sets to OFF if not needing the reading protection.
Bit3: Power-up Timer Enable bit
PWRTE(inv) 1 = Power-up timer is disabled
0 = Power-up timer is enabled
The power up timer is the timer to maintain the reset condition for about 72 ms
after the turning on.
Generally, it sets to enable.
Bit2: Watchdog Timer(WDT) Enable bit
WDTE 1 = WDT enabled
0 = WDT disabled
Bit1-0: Oscillator Selection bits
FOSC1 FOSC1 FOSC0 Oscillator mode Freq
FOSC0
1 1 Resistor/Capacitor Less than 1MHz
1 0 High Speed Crystal/Resonator 4MHz to 20MHz
0 1 Crystal/Resonator Less than 4MHz
0 0 Low Power Crystal Less than 200KHz
Instruction spec (1) of PIC16 series
Instruction set

ADDLW Add W and f

Form [label] ADDLW k


( label is omitable, shows SPACE code )

Operands k : literal field ( 00(00h) to 255(FFh) )

It executes the addition of the literal data


and the contents of the W register.

Operation

(EX)

When the byte overflows, it sets 1 to the C flag.


When 4 bits of lower part overflow, it sets 1 to the DC flag.
Flag
When the result is 0, it sets 1 to the Z flag.
In the case except the above, it sets 0 to C, DC and Z.

Instruction
1 cycle
cycles

ADDWF AND W with f

Form [label] ADDWF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It executes the addition of the contents of


the f register and the W register.
d = 0 : store result in W
d = 1 : store result in f
Operation

(EX)

When the byte overflows, it sets 1 to the C flag.


When 4 bits of lower part overflow, it sets 1 to the DC flag.
Flag
When the result is 0, it sets 1 to the Z flag.
In the case except the above, it sets 0 to C, DC and Z.

Instruction
1 cycle
cycles
ANDLW AND literal with W

Form [label] ADDLW k


( label is omitable, shows SPACE code )

Operands k : literal field ( 00(00h) to 255(FFh) )

It executes the logic AND operation of the


literal data and the contents of the W
register.

Operation

(EX)

When the result is 0, it sets 1 to the Z flag.


Flag
When the result is not 0, it sets 0 to the Z flag.

Instruction
1 cycle
cycles

ANDWF AND W with f

Form [label] ANDWF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It executes the logic AND operation of the


contents of the f register and the W register.
d = 0 : store result in W
d = 1 : store result in f
Operation

(EX)

When the result is 0, it sets 1 to the Z flag.


Flag
When the result is not 0, it sets 0 to the Z flag.

Instruction
1 cycle
cycles

Next instructions
Instruction spec (2) of PIC16 series

Instruction set

BCF Bit Clear f

Form [label] BCF f, b


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
b : Bit address ( 0 to 7 )

It makes the specification bit of the


contents of the f register 0.

Operation

(EX)

Flag No change

Instruction
1 cycle
cycles

BSF Bit Set f

Form [label] BSF f, b


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
b : Bit address ( 0 to 7 )

It makes the specification bit of the


contents of the f register 1.

Operation

(EX)
Flag No change

Instruction
1 cycle
cycles

BTFSC Bit Test f, Skip if Clear

Form [label] BTFSC f, b


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
b : Bit address ( 0 to 7 )

It checks the specification bit of the f


register, and in case of 0, it changes the
following instruction into the NOP and
executes it. (It executes the instruction of
the present address +2.)
Operation

Flag No change

Instruction
1 cycle
cycles

BTFSS Bit Test f, Skip if Set

Form [label] BTFSS f, b


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
b : Bit address ( 0 to 7 )
It checks the specification bit of the f
register, and in case of 1, it changes the
following instruction into the NOP and
executes it. (It executes the instruction of
the present address +2.)
Operation

Flag No change

Instruction
1 cycle
cycles
Instruction spec (3) of PIC16 series

Instruction set

CALL Call subroutine

Form [label] CALL k


( label is omitable, shows SPACE code )

Operands k : literal field ( 000(000h) to 2047(7FFh) )

It jumps to the subroutine which the literal


field shows.
It sets the literal value to 11 bits of lower
part of program counter (PC) and it sets the
bit 3 and 4 of the PCLATH register to 2
bits of higher part.
Operation It stores the present PC value +1 in the
stack.

Flag No change

Instruction
2 cycles
cycles

CLRF Clear f

Form [label] CLRF f


( label is omitable, shows SPACE code )

Operands f : Register file addesss ( 00(00h) to 127(7Fh) )

It clears f register and it sets Z flag.

00000000 f register
Operation 1 Z flag

Flag It sets 1 to the Z flag.


Instruction
1 cycle
cycles

CLRW Clear W

Form [label] CLRW


( label is omitable, shows SPACE code )

Operands None

It clears W register and it sets Z flag.

00000000 W register
Operation 1 Z flag

Flag It sets 1 to the Z flag.

Instruction
1 cycle
cycles

CLRWDT Clear Watchdog Timer

Form [label] CLRWDT


( label is omitable, shows SPACE code )

Operands None

It resets a watchdog timer.


When using the prescaler for the watchdog
timer, it resets the prescaler, too.

Operation

Flag It sets 1 to TO and the PD.

Instruction
1 cycle
cycles
Instruction spec (4) of PIC16 series

Instruction set

COMF Complement f

Form [label] COMF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It executes the complementary operation of


the contents of the f register.(Not 2's
Complement)
d = 0 : store result in W
d = 1 : store result in f
Operation

(EX)

When the result is 0, it sets 1 to the Z flag.


Flag
When the result is not 0, it sets 0 to the Z flag.

Instruction
1 cycle
cycles

DECF Decrement f

Form [label] DECF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It subtracts 1 from the contents of the f


register.
d = 0 : store result in W
d = 1 : store result in f
Operation

(EX)

When the result is 0, it sets 1 to the Z flag.


Flag
When the result is not 0, it sets 0 to the Z flag.
Instruction
1 cycle
cycles

DECFSZ Decrement f, Skip if 0

Form [label] DECFSZ f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It subtracts 1 from the contents of the f


register.
d = 0 : store result in W
d = 1 : store result in f
In case of the result of the subtraction is 0,
it changes the following instruction into the
Operation NOP and executes it. (It executes the
instruction of the present address +2.)

Flag No change

Instruction 1 cycle
cycles When skipping, it is 2 cycles.

GOTO Go to address

Form [label] GOTO k


( label is omitable, shows SPACE code )

Operands k : literal field ( 000(000h) to 2047(7FFh) )

It jumps unconditionally to the address


which the literal field shows.
It sets the literal value to 11 bits of lower
part of program counter (PC) and it sets the
bit 3 and 4 of the PCLATH register to 2
bits of higher part.
Operation

Flag No change

Instruction
2 cycles
cycles
Instruction spec (5) of PIC16 series

Instruction set

INCF Increment f

Form [label] INCF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It adds 1 to the contents of the f register.


d = 0 : store result in W
d = 1 : store result in f
Operation

(EX)

When the result is 0, it sets 1 to the Z flag.


Operation
When the result is not 0, it sets 0 to the Z flag.

Instruction
1 cycle
cycles

INCFSZ Increment f, Skip if 0

Form [label] INCFSZ f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It adds 1 to the contents of the f register.


d = 0 : store result in W
d = 1 : store result in f
In case of the result of the addition is 0, it
changes the following instruction into the
NOP and executes it. (It executes the
Operation instruction of the present address +2.)

Flag No change

Instruction 1 cycle
cycles

IORLW Inclusive OR literal with W

Form [label] IORLW k


( label is omitable, shows SPACE code )

Operands k : literal field ( 00(00h) to 255(FFh) )

It executes the logic OR operation of the


literal data and the contents of the W
register.
Operation

(EX)

When the result is 0, it sets 1 to the Z flag.


Flag
When the result is not 0, it sets 0 to the Z flag.

Instruction
1 cycle
cycles

IORWF Inclusive OR W with f

Form [label] IORWF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It executes the logic OR operation of the


contents of the f register and the W register.
d = 0 : store result in W
d = 1 : store result in f
Operation

(EX)

When the result is 0, it sets 1 to the Z flag.


Flag
When the result is not 0, it sets 0 to the Z flag.

Instruction
1 cycle
cycles
Instruction spec (6) of PIC16 series

Instruction set

MOVF Move f

Form [label] MOVF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It moves (copy) the contents of the f


register.
d = 0 : store result in W
d = 1 : store result in f
Operation
Seemed to move from the f register to the f
register no meaning, but its being used in
the purpose to set a flag.

When the result is 0, it sets 1 to the Z flag.


Flag
When the result is not 0, it sets 0 to the Z flag.

Instruction
1 cycle
cycles

MOVLW Move literal to W

Form [label] MOVLW k


( label is omitable, shows SPACE code )

Operands k : literal field ( 00(00h) to 255(FFh) )

It sets literal data to the W register.

Operation

Operation No change

Instruction
1 cycle
cycles
MOVWF Move W to f

Form [label] MOVWF f


( label is omitable, shows SPACE code )

Operands f : Register file addesss ( 00(00h) to 127(7Fh) )

It moves (copy) the contents of the W


register to the f register.

Operation

Flag No change

Instruction
1 cycle
cycles

NOP No Operation

Form [label] NOP


( label is omitable, shows SPACE code )

Operands None

It is moved to the next instruction without


processing anything.
Operation
This instruction is used when it adjusts a
processing time as the timer processing,
and so on.

Flag No change

Instruction
1 cycle
cycles
Instruction spec (7) of PIC16 series

Instruction set

RETFIE Return from interrupt

Form [label] RETFIE


( label is omitable, shows SPACE code )

Operands None

It returns from the interruption processing.


It sets the latest return address which is
stored in the stack to the PC.
It sets the GIE bit of the INTCON register
to 1 and it makes an interruption possible.
Operation

Flag No change

Instruction
2 cycles
cycles

Return with literal in W


RETLW

Form [label] RETLW k


( label is omitable, shows SPACE code )

Operands k : literal field ( 00(00h) to 255(FFh) )

It returns from the subroutine.


It sets literal data to the W register.
It sets the latest return address which is
stored in the stack to the PC.
The processing result can be delivered by
literal data's using different RETLW by the
Operation processing result of the subroutine.

Flag No change

Instruction
2 cycles
cycles
RETURN Return from Subroutine

Form [label] RETURN


( label is omitable, shows SPACE code )

Operands None

It returns unconditionally from the


subroutine.
It sets the latest return address which is
stored in the stack to the PC.

Operation

Flag No change

Instruction
2 cycles
cycles

RLF Rotate Left f through Carry

Form [label] RLF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It moves the contents of the f register to the


1-bit left including the carry bit.
d = 0 : store result in W
d = 1 : store result in f
Operation

Flag It sets the most significant bit of the f register to C.

Instruction
1 cycle
cycles
Instruction spec (8) of PIC16 series

Instruction set

RRF Rotate Right f through Carry

Form [label] RRF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It moves the contents of the f register to the


1-bit right including the carry bit.
d = 0 : store result in W
d = 1 : store result in f
Operation

Flag It sets the least significant bit of the f register to C.

Instruction
1 cycle
cycles

SLEEP Go into stanby mode

Form [label] SLEEP


( label is omitable, shows SPACE code )

Operands None

It stops a clock generator and it makes a


processor a standby mode.
It resets a watchdog timer.
When using the prescaler for the watchdog
timer, it resets the prescaler, too.
Operation

Flag It sets 1 to TO and it sets 0 to the PD.

Instruction
1 cycle
cycles

Subtract W from literal


SUBLW

Form [label] SUBLW k


( label is omitable, shows SPACE code )

Operands k : literal field ( 00(00h) to 255(FFh) )

It executes the subtraction of the contents of


the W register from the literal data.
In the actual calculation, it changes the
content of the W register by the 2's
complement and it adds with the literal data.
Operation

(EX)

C=1, Z=0 ( Result is positive )


Flag C=1, Z=1 ( Result is zero )
C=0, Z=0 ( Result is negative )

Instruction
1 cycle
cycles

SUBWF Subtract W from f

Form [label] SUBWF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It executes the subtraction of the contents of


the W register from the f register.
d = 0 : store result in W
d = 1 : store result in f
In the actual calculation, it changes the
content of the W register by the 2's
Operation complement and it adds with the contents of
the f register.

(EX)

C=1, Z=0 ( Result is positive )


Flag C=1, Z=1 ( Result is zero )
C=0, Z=0 ( Result is negative )

Instruction
1 cycle
cycles
Instruction spec (9) of PIC16 series

Instruction set

SWAPF Swap nibbles in f

Form [label] SWAPF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It swaps higher 4 bits and lower 4 bits of


the f register.

Operation

Flag No change

Instruction
1 cycle
cycles

XORLW Exclusive OR literal with W

Form [label] XORLW k


( label is omitable, shows SPACE code )

Operands k : literal field ( 00(00h) to 255(FFh) )

It executes the exclusive OR (XOR)


operation of the literal data and the contents
of the W register.

Operation

(EX)

When the result is 0, it sets 1 to the Z flag.


Flag
When the result is not 0, it sets 0 to the Z flag.

Instruction
1 cycle
cycles
XORWF Exclusive OR W with f

Form [label] XORWF f, d


( label is omitable, shows SPACE code )

f : Register file addesss ( 00(00h) to 127(7Fh) )


Operands
d : Destination select ( 0 or 1 )

It executes the exclusive OR (XOR)


operation of the contents of the f register
and the W register.
d = 0 : store result in W
d = 1 : store result in f
Operation

(EX)

When the result is 0, it sets 1 to the Z flag.


Flag
When the result is not 0, it sets 0 to the Z flag.

Instruction
1 cycle
cycles
Software making procedure

Flow chart
It is an old technique but to make software using the flow chart is simple. The flow of the processing can be
made clear. When the step of the software increases, there is possibility to get not to understand the whole.
More than two kinds of flow charts are sometimes made.

General flow chart is used to decide the build


of the software with the whole functional block
shown.

Detaile flow chart

Detaile flow chart is the flow chart which


was written to each instruction level.
It is written in the details to the level that
it is possible to make a source code.
It is possible to be freely created the processing
flow of the software. As for the software to
make PIC work for the purpose, the various
ways are thought of. It depends on the sense of
General flow chart the making person. The author sometimes
forgets the meaning of the processing step
when the time passes. When writing the point
of the processing at the flow chart, it is useful
when reorganizing from behind.

The point to consider in case of software making is shown below.


Think of the processing step
This is the main part of the software making.

Decide labels in the processing block


Attache a label to the part which is jumped from the other processing. There are character
strings which are defined as the reserved word by the assembler. They can not be used as
the label.
Decide the purpose and the labels of the register files
68 bytes can be used as the register file. Decide the structure and the labels of the register
files to use.

Construction of the software


You make software with the following structure.
(1) The definition part of the hardware
Specifie the kind of PIC to use. It is changed based on this specification when changing the source
code into the machine code.
LIST of the assembler direction is used.
The directions are not the instructions to use in actual PIC. They are the direction which is used to
specify the processing of an assembler.

(2) The definition part of the register files


In case of PIC16F84A, the file register of 68 bytes can be used. When attaching a label to each
register, the understanding of processing becomes easy. When changing a register in the arrangement,
it is OK if changing the definition of the label. It makes a label and an actual address correspond.
EQU of the assembler direction is used.

(3) The initialization processing part


From this part, the processing to do actually in PIC is written. The initialization processing is the
processing to do first when PIC works. It sets the environment of the processing which is done after
that such as the setting of an input/output port, the initialization of the STATUS register, the
initialization of the register file contents so on.
When specifying the address which stores a program in the memory, ORG is used as the direction.

(4) The main processing part


Write the processing to have operation for the purpose.
It is sometimes divided into the main part and the subroutine part in the construction of the program.
In the case as it uses the same processing repeatedly, it makes common processing as the subroutine.
Generally, it writes a subroutine group behind the main part but even if it is opposite, there is no
problem.

(6) The source ending


The ending of the source code is written.
END of the assembler direction is used.
About the software
PIC can do various operation by executing the instructions which were stored in the program memory(PM).
The instruction which is stored at the head(0000h) of PM is executed when turning on the power. If GOTO
instruction is stored there, the PIC changes the execution address of the program according to the contents of
the instruction.

To make software is to make the order of the operation to make PIC do. Therefore, it is necessary to decide
what operation you want to make the PIC.
For example, it makes an LED blink, it makes judge the condition of the input or it lets out a specific signal...

To think of the order of the instruction is software creating.

I will explain the following example for you to understand software creating easily.

Job of the PIC


Count-up the content of the specific address of the memory.
(Only in this processing, it is empty but it is simple example.)

Condition
The memory to count-up is the 0Ch address of the RAM file register.

Processing flow
The processing immediately after the turning on starts from address 0 of the PM.
In the actual program, the initialization processing is necessary. However, in the example
this time, it is omitted.

PM address Processing contents Instructions

0000h Clear the contents of the 0Ch address CLRF

0001h Increment the contents of the 0Ch address INCF

0002h Jump to 0001h GOTO

The contents which are written at the PM are as follows.

PM address Memory contents Comments

0000h The red part shows CLRF instruction.


The green part shows the file register
address.

0001h The red part shows INCF instruction.


The blue part shows to store a processing
result in the file register.
The green part shows the file register
address.
0002h The red part shows GOTO instruction.
The green part shows a program address.

The PIC does following operation when writing contents like the above in the 3 words from the head
of the PM and turning on the power.
First, the 0Ch address of the file register is cleared in address 0 of PM and count-up in address 1 of
PM. Next, the GOTO instruction is executed in address 2 and jumps to address 1. Then, it repeats the
operation to count-up again. This processing doesn't end until it switches off the power.

PIC recognizes the combination of "0" and "1" which was written in the PM as the instruction. The
instruction which was expressed by the combination of "0" and "1" is called machine code. At the
digital computer, machine code is always used. Machine code is used for the personal computer
which you are using, too. However, the contents of the machine code depend on the processor.
Therefore, the Pentium doesn't work by the machine code for PIC.

I did contents above by the hand computation. However, it is difficult to do in the hand computation
when the number of the processing(Step) increases.
Therefore, the soft development tool which is called the assembler or the compiler is used for the
software creating. These tools are the one to make it easy for the person to make software.
The instruction can be expressed by the character. It is possible to use a character string(Label) when
specifying the address of the memory. So on.
Also, when working the same software in the hardware which the machine code is different from, it
is sometimes possible if changing only machine code. In the such case, because the assembler or the
compiler changes into the machine code which suited the hardware automatically, the person has the
advantage that he can make software without being conscious of the machine code, too.

It is as follows when changing above-mentioned processing into the machine code automatically
using MPASM(Assembler) of the Microchip Inc..
The input file for the assembler(Source code) is made with Editor. The person makes this source
code. This work is called CODEING.

The Source Code


I am using a hexadecimal number for the specification of the
address(0Ch) of the file register. Because the default is a
LIST hexadecimal number in MPASM, it is handled with the
P=16F84A hexadecimal number when writing just as it is. It's OK even if
you write H'0C'.
ORG When writing in the decimal number, it is written as D'12' or .12
0 (dot 12).
When writing in the binary number, it is written as B'1100'.
CLRF
0C
LOOP
INCF
0C,1

GOTO
LOOP

END
The Listing File

LOC OBJECT CODE LINE SOURCE TEXT


VALUE

00001 LIST
P=16F84A
0000 00002 ORG
0
0000 018C 00003 CLRF
0C
0001 0A8C 00004 LOOP INCF
0C,1
0002 2801 00005 GOTO
LOOP
00006 END

The LOC column shows the program memory address.


The OBJECT CODE column shows the machine code.
You find that it becomes the contents which are the same as the one by the hand computation.
How to debug
The debugging is to confirm that the made software works. The work which removes blight is debugging.

To debug, there are some ways. Here, the way of executing 1 step and the way by the breakpoint(It stops
processing temporarily) are explained.
I use the program which was shown by the previous example for the explanation.

Debugging by the step operation


The step debugging is the way which is convenient to confirm the operation of the software with small scale
or the operation of the specific processing part.
is the step execution button. When the step button isn't displayed in the tool bar, click (Swap
Toolbar).
The step debugging can make execute with Debug > Run > Step , too.

The preparation
It had better display a listing file and a file register beforehand in the window.
Window > Absolute Listing : The listing file display

Window > File Registers : The file register display

The execution of the debugging

(1) The reset operation


is a reset button. It is displayed with "Reset Processor" in the status in the lower left. When the
step button isn't displayed in the tool bar, click (Swap Toolbar).
With this operation, the simulator becomes a condition immediately after the turning on as the
condition of PIC.
The reset operation can make execute with Debug > Run > Reset , too.
A dark bar is displayed at 0 of the program address on the listing file. In the explanation after that, I
call this dark bar as "PC bar ". This bar shows the position of program counter (PC).

Next, let's attempt to confirm the contents of the file register. 03h become 18. This addess is
STATUS register. TO and PD become "1". This shows a condition immediately after the turning on.

(2) The 1 step execution


Click the step button .
The PC bar moves to address 1.
The file register changes as follows.

02h (PC) 00 > 01 The program counter changed to address 1.


03h (STATUS) 18 > 1C After executing CLEF, the Z flag became "1".

(3) The 1 step execution


Click the step button .
The PC bar moves to address 2.
The file register changes as follows.

02h (PC) 01 > 02 The program counter changed to address 2.


03h (STATUS) 1C > 18 Because the result which executed INCF was not 0, the Z flag
became "0".
0Ch 00 > 01 A target counter was counted-up.

(4) The 1 step execution


Click the step button .
The PC bar moves to address 1.
The file register changes as follows.
02h (PC) 02 > 01 After executing GOTO, the PC became 01h.

(5) The 1 step execution


Click the step button .
The PC bar moves to address 2.
The file register changes as follows.

02h (PC) 01 > 02 The program counter changed to address 2.


0Ch 01 > 02 A target counter was counted-up.

When clicking the step button, the PC bar change address 1 and address 2 alternately.
Every time the instruction of 1 address is executed, 0Ch of the file register is updated.

As above mentioned, the operation every step can be confirmed.

Debugging by the breakpoint


This is a way of debugging by by confirming the data when stopping at the breakpoint.
Because it is possible to process at a stroke to the breakpoint, it is possible to debug efficiently.
Before executing the instruction which a breakpoint was set to, processing is stopped temporarily.

The way of setting a breakpoint


( Setting 1 )
Click the step which sets a breakpoint on the listing file.
Press the right mouse button.
Click the "Break Point(s)" at the menu
The line which a breakpoint was set to changes to the red.
The breakpoint can be set to more than one line.

( Setting 2 )
This is the way of making a label a breakpoint.
A breakpoint setting dialog is displayed when pressing .
This setting can make execute with Debug > Break Settings... , too.
Choose the label to want to set a breakpoint by the Start item of the setting dialog.
When clicking the "Add" button, a breakpoint is added. If a checking mark is displayed, the
breakpoint is effective.
The preparation
It had better display a listing file and a file register beforehand in the window.
Window > Absolute Listing : The listing file display
Window > File Registers : The file register display

The execution of the debugging

(1) The reset operation


Click the reset button and it makes a simulator a condition immediately after the turning on as
the condition of PIC.
The PC bar is in the place of address 0.
The file register changes as follows.

02h (PC) 00
03h (STATUS) 18

(2) The setting of a breakpoint


Set a breakpoint to address 2 (GOTO) of the program.
Set by setting 1. The line changes to the red when a breakpoint is set.

(3) The processing execution


Click the run button . It is possible to start the processing execution in Debug > Run > Run .
The PC bar moves to address 2.
The file register changes as follows.

02h (PC) 00 > 02 The program counter changed to address 2.


0Ch 00 > 01 A target counter was counted-up.

(4) The processing execution


Click the run button .
The PC bar is as address 2.
The file register changes as follows.

0Ch 01 > 02 A target counter was counted-up.


When clicking the run button, the contents of file register 0Ch is updated.

(5) Debugging ending


is a stop button(.Halt the processor).
It is possible to stop the processing execution in Debug > Run > Halt .

In the condition which stops at the breakpoint, the debugging operation continues. When ending
debugging, it is necessary to make stop at the stop button.
Guidelines to make the Source Code
The source code should be written by the language which is interpreted by the assembler or the compiler.
When using MPASM, an assembly language is used. When you write a source code with the C language, the
compiler of the C language is necessary.
The compiler interprets the sentence which was written in 1 line and spreads out to the instruction
group(Generally, it is more than one instruction) to realize it. In case of the assembler, it changes each source
code into the instruction. The C language can make a program with few source codes. But, a wasteful
machine code is sometimes contained by the performance of the compiler. It is because it replaces with the
machine code automatically.
When using a compiler, you can make a program easily. When using a memory efficiently, the assembler
suits.

The source code file can be created using any ASCII text file editor. The lowercase and the uppercase are to
be OK as the character.
I will explain the making of the source code which used an assembly language on these pages.

Source code format


The format of the source code is shown below. The maximum column width is 255 characters.

Label Mnemonic Operand ;Comment


;Comment
You can make 1 line only a comment, too. Of course, it is to be OK even if it doesn't write.

Generally, using the TAB, the position of the mnemonic, the operand, the comment is arranged for.
It is for that it is easy to see.

Labels A label must start in colimn 1.


It may be followed by a colon ( : ), space, tab or the end of line.
Labels must begin with an alpha character or an under bar ( _ ) .
Labels may contain alphanumeric characters, the under bar and question mark.
Labels may be up to 32 characters long.
It isn't possible to use the reserved word of the assembler for labels.
Because "B" becomes the reserved word which shows "Binary", it isn't possible to use
for labels.

Mnemonics
Assembler instruction mnemonics, assembler directives and macro calls must begin in
colum two or greater.
If there is a label on the same line, instructions must be separated from that label by a
colon, or by one more spaces or tabs.
Generally, the position of the instructions are arranged for using the tab.
The character which it is possible to use is an alpha character or an under bar.

Operands Operands must be separated from mnemonics by one more spaces, or tabs.
Multiple operands must be separated by commas.
The spaces can be put behind the commas for that it is easy to see.

Comments MPASM treats anything after a semicolon as a comment.


All characters following the semicolon are ignored through the end of the line.
String constants containing a semicolon are allowed and not confused with comments.

Directive Language
PIC16F84A has 35 kinds of instructions. These instructions are the instructions to use when PIC
processes.
MPASM has the directives to control the operation of the assembler as well as it. MPASM has 58
kinds of directives.
These directives are used according to need. However, in the end of the source code, the END
must be always written.
When there is not an END, the assembler doesn't recognize written contents as the source code.

I will explain directives which seems to be often used below.

[] : Optional Arguments expr : Expression

< > : Variables. Text you supply : Space

| : An OR selection

_ _CONFIG Set Processor Configuration Bits

Syntax _ _CONFIG <expr>

Sets the processor's configuration bits to the value described by <expr>.


Descripton Before this directive is used, the processor must be declared through the
command line, the LIST directive, or the PROCESSOR directive.

DB Declare Data of One Byte

Syntax [<label>] DB <expr>[,<expr>,...,<expr>]

Descripton Reserve program memory words with packed 8-bit values.


DT Define Table

Syntax [<label>] DT <expr>[,<expr>,...,<expr>]

Descripton Generates a series of RETLW instructions, one instruction for each <expr>.

EQU Define an Assembler Constant

Syntax <label> EQU <expr>

Descripton The value of <expr> is assigned to <label>.

END End Program Block

Syntax END

Descripton Indicates the end of the program.

INCLUDE Include Additional Source File

Syntax INCLUDE <<include_file>>|"<include_file>"

Descripton The specified file is read in as source code.

LIST List Option

Syntax LIST [<list_option>,...,<list_option>]

Occurring on a line by itself, the LIST directive has the effect of turning listing
output on, if it had been previously turned off. Otherwise, one of the following
list option can be supplied to control the assembly process or format the listing
file.

Options Default Description


b=nnn 8 Set tab spaces.
c=nnn 132 Set column width.

Descripton f=<format> INHX8M Set the hex file output.


free FIXED Use free-format parser.
fixed FIXED Use fixed-format parser.
mm=ON|OFF ON Print memory map in list file.
n=nnn 60 Set lines per page.
p=<type> None Set processor type.
Set default radix.
r=<radix> hex
hex, dec, oct
st=ON|OFF ON Print symbol table in list file.
t=ON|OFF OFF Truncate lines of listing.
w=0|1|2 0 Set the message level.
x=ON|OFF ON Turn macro expansion on or off.

All LIST options are evaluated as decimal numbers.

ORG Set Program Origin

Syntax [label] ORG <expr>

Set the program origin for subsequent code at the address defined in <expr>.
Descripton
If no ORG is specified, code generation will begin at address zero.

PROCESSOR Set Processor Type

Syntax PROCESSOR <processor_type>

Descripton Set the processor type to <processor_type>.

SET Set an Assembler Variable

Syntax <label> SET <expr>

<label> is assigned the value of the valid MPASM expression specified by


Descripton <expr>. The SET directive is functionally equivalent to the EQU directive
except that SET value may be subsequently altered by other SET directives.

IF Begin Conditional Assembled Code Block


ELSE Begin Alternative Assembly Block IF
ENDIF End Conditional Assembly Block

IF <expr>
........
Syntax
ELSE
........
Begin execution of a conditional assembly block. If <expr> evaluates to true,
the code immadiately following the IF will assemble. Otherwise, subsequent
code is skipped until an ELSE directive or an ENDIF directive is encountered.
An expression that evaluates to zero is considered logically FALSE. An
Descripton expression that evaluates to any other value is considered logically TRUE. The
IF and WHILE directives operate on the logical value of an expression. A
relational TRUE expression is guaranteed to return a nonzero value, FALSE a
value of zero.
These directives don't generate instructions like the C language. They only

WHILE Perform Loop While Condition is True


ENDW End a While Loop

WHILE <expr>
Syntax ........
ENDW

The lines between the WHILE and the ENDW are assembled as long as <expr>
evaluates to TRUE. An expression that evaluates to zero is considered logically
FALSE. An expression that evaluates to any other value is considered logically
TRUE. A relational TRUE expression is guaranteed to return a non-zero value;
Descripton FALSE a value of zero.
A WHILE loop can contain at most 100 lines and be repeated a maximum of
256 times.
These directives don't generate instructions like the C language. They only
control the source code to assemble.

Numeric Constants and Radix


MPASM supports the following radix forms. The default radix is hexadecimal.
Constants can be optionally preceded by a plus or minus sign. if unsigned, the value is assumed to be
positive.

Radix Specifications
Type Syntax Example
Decimal D'<digits>' or .(dot)<digits> D'100' or .100
H'<hex_digits>' or 0x<hex_digits> or H'A8' or 0xA8 or
Hexadecimal
0<hex_digits>H 0A8H
Octal O'<octal_digits> O'567'
Binary B'<binary_digits> B'011001'
ASCII A'<characters>' or '<characters>' A'ABC' or 'ABC'

Arithmatic Operators and Precedence


Operator Example
$ Current/Return program counter goto $+3
( Left Parenthesis
(length+1)*256
) Right Parenthesis
* Multiply a*b
/ Divide a/b
+ Add a+b
- Subtract a-b
high Return high byte movlw high TABLE
low Return low byte movlw low TABLE
>= Greater or equal if a>=b
> Greater than if a>b
<= Less or equal if a<=b
< Less than if a<b
== Equal to if (a==b)
!= Not equal to if (a!=b)
& Bitwise AND flag=flag&CHECK_BIT
| Bitwise inclusive OR flag=flag|CHECK_BIT
&& Logical AND if (a==b)&&(c==d)
|| Logical OR if(a==b)||(c==d)
! Item NOT (logical complement) if !(a==b)
Directive Summary
The following summary is the directives supported by MPASM.
MPASM has 58 kinds of directives.
[ ] : Optional Arguments expr : Expression
< > : Variables. Text you supply : Space
| : An OR selection

Directive Description Syntax

_ _badram <expr>[-<expr>][,<expr>[-
_ _BADRAM Specify invalid RAM locations
<expr>]]

Generate RAM bank selecting


BANKISEL bankisel <label>
code for indirect addressing

Generate RAM bank selecting


BANKSEL banksel <label>
code

CBLOCK cblock [<expr>]


Define a Block Constants
ENDC endc

CODE Begins executable code section [<name>] code [<address>]

_ _CONFIG Specify configuration bits _ _config <expr>

constant
CONSTANT Declare Symbol Constant
<label>[=<expr>,...,<label>[=<expr>]]

DA Store Strings in Program Memory [<label>] da <expr>[,<expr>,...,<expr>]

[<label>] data <expr>[,<expr>,...,<expr>]


DATA Create Numeric and Text Data [<label>] data
"<text_string>"[,"<text_string>",...]

[<label>] db <expr>[,<expr>,...,<expr>]
DB Declare Data of One Byte [<label>] db
"<text_string>"[,"<text_string>",...]

[<label>] de <expr>[,<expr>,...,<expr>]
DE Define EEPROM Data [<label>] de
"<text_string>"[,"<text_string>",...]

#define <name>[<value>]
#DEFINE Define a text Substitution Label
#define <name>[<arg>,...,<arg>]<value>

#UNDEFINE Delete a Substitution Label #undefine <label>

[<label>] dt <expr>[,<expr>,...,<expr>]
DT Define Table [<label>] dt
"<text_string>"[,"<text_string>",...]

[<label>] dw <expr>[,<expr>,...,<expr>]
DW Declare Data of One Word
[<label>] dw
"<text_string>"[,"<text_string>",...]

END End Program Block end

EQU Define an Assembly Constant <label> equ <expr>

ERROR Issue an Error Message error "<text_string>"

errorlevel "0|1|2 <+|-


ERRORLEVEL Set Error Level
><message_number>"

EXITM Exit from a Macro exitm

EXPAND Expand Macro Listing expand

NOEXPAND Turn off Macro Expansion noexpand

EXTERN Declares an external label extern <label>[,<label>]

FILL Fill Memory [<label>] fill <expr>,<count>

GLOBAL Exports a defined label global <label>[,<label>]

IDATA Begin initialized data section [<name>] idata [<address>]

_ _IDLOCS Specify ID locations _ _idlocs <expr>

Begin Conditionally Assembled


#IF #if <expr>
Code Block

Begin Alternative Assembly Block


#ELSE #else
to IF

#ENDIF End conditional Assembly Block #endif

Execute if Symbol has Been


#IFDEF #ifdef <label>
Defined

Execute if Symbol has not Been


#IFNDEF #ifndef <label>
Defined

INCLUDE Include Additional Source File include <<include_file>>|"<include_file>"

LIST Listing Options list [<list_optin>,...,<list_option>]

NOLIST Turn off Listing Output nolist

LOCAL Declare Local Macro Variable local <label>[,<label>]

MACRO Declare Macro Definition <label> macro [<arg>,...,<arg>]

ENDM End a Macro Definition endm

_ _MAXRAM Specify maximum RAM address _ _maxram <expr>

MESSG Create User Defined Message messg "<message_text>"

ORG Set Program Origin [<label>] org <expr>

PAGE Insert Listing Page Eject page


PAGESEL Generate ROM page selecting code pagesel <label>

PROCESSOR Set Processor Type processor <processor_type>

RADIX Specify Default Radix radix <default_radix>

RES Reserve Memory [<label>] res <mem_units>

SET Define an Assembler Variable <label> set <expr>

SPACE Insert Blank Listing Lines space <expr>

TITLE Specify Program Title title "<title_text>"

SUBTITLE Specify Program Subtitle subtitle "<sub_text>"

UDATA Begin uninitialized data section [<name>] udata [<address>]

Begins access uninitialized data


UDATA_ACS [<name>] udata_acs [<address>]
section

Begin overlayed uninitialized data


UDATA_OVR [<name>] udata_ovr [<address>]
section

Begin shared uninitialized data


UDATA_SHR [<name>] udata_shr [<address>]
section

variable
VARIABLE Declare Symbol Variable
<label>[=<expr>,...,<label>[=<expr>]]

Perform Loop While Condition is


WHILE while <expr>
True

ENDW End a While Loop endw


PIC Circuits Gallery
Ultrasonic Range Meter

On these pages, I will introduce the Ultrasonic Range Meter with PIC16F873.
As for the range meter which doesn't use PIC, refer to "Ultrasonic Range Meter".

With this circuit, the following features of PIC16F873 are used.


Capture The time which is reflected and returns to the object after sending out a ultrasonic
is measured.

A/D The propagation speed of the sound changes with the temperature.
converter I used A/D converter to revise a display.

Hardware Software
Circuit drawing List

Pattern drawing Processing explanation

Circuit explanation Improvement

Parts explanation Performance test


Circuit drawing
for Ultrasonic Range Meter
Pattern drawing
for Ultrasonic Range Meter
(Wiring side)

Olive-green line shows the wiring at the component side.


Pink lined parts shows the external parts.
Circuit explanation for Ultrasonic Range Meter

Receiver circuit
The receiver circuit is almost same
as the "Ultrasonic Range Meter"
which is not used PIC.

Signal amplification circuit


The ultrasonic signal which was
received with the reception sensor
is amplified by 1000 times(60dB)
of voltage with the operational
amplifier with two stages. It is 100
times at the first stage (40dB) and 10 times (20dB) at the next
stage.
As for the dB (decibel), refer to "Logarithm Table".
Generally, the positive and the negative power supply are
used for the operational amplifier. The circuit this time works
with the single power supply of +9 V. Therefore, for the
positive input of the operational amplifiers, the half of the
power supply voltage is appied as the bias voltage. Then the
alternating current signal can be amplified on 4.5V central
voltage. When using the operational amplifier with the
negative feedback, the voltage of the positive input terminal
and the voltage of the negative input terminal become equal
approximately. This is called virtual grounding. So, by this
bias voltage, the side of the
positive and the side of the
negative of the alternating current
signal can be equally amplified.
When not using this bias voltage,
the distortion causes the alternating
current signal. This technique is
often used when using the
operational amplifier which needs
two kinds of powers in the single
power.
As for the operation of the
operational amplifier, refer to
"Operation explanation of the triangular wave oscillator".

Detection circuit
The detection is done to detect the received ultrasonic signal. This is the half-wave rectification circuit
with Shottky barrier diodes. The DC voltage according to the level of the detection signal is output to
the capacitor behind the diode. The Shottky barrier diodes are used because the high frequency
characteristic is good.
As for the Shottky barrier diode, refer to "Diodes".

Signal detector
This circuit is the circuit which detects the ultrasonic which returned from the measurement object. The
output of the detection circuit is detected using the comparator. At the circuit this time, the operational
amplifier of the single power supply is used instead of the comparator. The operational amplifier
amplifies and outputs the difference between the positive input and the negative input.
In case of the operational amplifier which doesn't have the negative feedback, the output becomes the
saturation state by a little input voltage. Generally, the operational amplifier has over 10000 times of
mu factors. So, when the positive input becomes higher a
little than the negative input, the difference is tens of
thousands of times amplified and the output becomes the
same as the power supply almost.(It is the saturation state)
Oppositely, when the positive input becomes lower a little
than the negative input, the difference is tens of thousands of
times amplified and the output becomes 0 V almost.(It is in
the OFF condition) This operation is the same as the
operation of the comparator. However, because the inner
circuit of the comparator is different from the operational
amplifier, the comparator can not be used as the operational
amplifier.

At the circuit this time, the output of the detection circuit is connected with the positive input of the
signal detector and the voltage of the negative input is made constant.
Vrf = ( Rb x Vcc )/( Ra + Rb )
= ( 47K-ohm x 9V )/( 1M-ohm + 47K-ohm )
= 0.4V

So, when the rectified ultrasonic signal becomes more than 0.4 V, the output of the signal detector
becomes the H level (Approximately 9V).
This output is lowered with the resistor to make fit with the input of signal holding circuit (TTL:0V to
5V).

Signal holding circuit

This is the holding circuit of detected signal. SR ( Set and Reset ) flip-flop is used. For the details of
SR-FF, refer to "The operation explanation of the D-type flip-flop".
The detector is made to be not operate in the constant time(About 1.5 milliseconds) after sending out a
transmission pulse to prevent from the wrong detection which is due to the influence of the transmission
pulse. This operation is controlled with the software of PIC.

When using the capture feature of PIC, this circuit isn't indispensable. Capture operation is done by the
change of the capture input in the once. The reason why I am using this circuit is to confirm signal
detection operation within the reflected signal detection time(About 65 milliseconds). When sending
out next ultrasonic pulse, the output of this circuit is checked. And when the output is L level, an error
display is done because the reflected signal could not be detected.
Transmitter circuit

The inverter is used for the drive of the ultrasonic sensor. The two inverters are connected in parallel
because of the transmission electric power increase.
The phase with the voltage to apply to the positive terminal and the negative terminal of the sensor has
been 180 degrees shifted. Because it is cutting the direct current with the capacitor, about twice of
voltage of the inverter output are appied to the sensor.

The power supply voltage of this drive circuit is +9V. It is converting voltage with the transistor to
make control at the operating voltage of PIC(+5V). Because C-MOS inverters are used, it is possible to
do ON/OFF at high speed comparatively.

7 segment LED display circuit

Three 7 segment LEDs are used for 3-digit display. As for the lighting-up of the LED, 1 digit is
displayed in the order with the software of PIC.
At the circuit this time, I
make light up it when the
terminal of PIC is L level.
So, ANODE
COMMON type is used
as the LED. The anode
common type is the type
which the side of the
positive(Anode) of the LED
is connected inside. It lights
up when grounding(L level)
a cathode in the segment to
want to make light up.
As the 7 segment LED, the others have a cathode common type. When you buy them, the specification
of the type should be checked.

Temperature revision voltage generating circuit


The sound wave propagation speed in air is changed by the temperature. At 0°C, it is 331.5m/sec. At
40°C, it is 355.5m/sec.
For the details of the propagation speed, refer to "The sound wave propagation speed in the air".
This range meter calculates a distance by dividing the propagation time which was measured by the
capture feature.
I will explain that it does the case of the distance measurement of 1m in the 0°C environment as for the
example. The time which the sound wave takes to go and return is 2m/331.5m/sec = 0.006033 seconds =
6.033 milliseconds. The contents of the counter by the capture feature is 6033 within 1 microsecond.
For the conversion of this to distance (cm), it divides by 60. It is 6033/60=100.55. The following of the
decimal point is cut off. It becomes a measurement error.
This conversion value (60) depends on the temperature. It isn't related with the distance to measure. In
case of 9 m, it is 54298/60=904.9. The conversion error becomes big when the distance becomes long.
This is because it isn't possible to do conversion below the decimal point.
In case of 40°C, it is 2m/355.5m/sec = 5625 microseconds and the conversion value is 56.
The conversion value should be changed by the ambient temperature.

At this range meter, a conversion value is generated using the A/D conversion feature. The A/D
converter converts input voltage into the 10-bit digital data. This time, I am using upper 3 bits. So, the
A/D conversion result from 0V to 5V is the value from 0 to 7. And 54 is added to this value.
Then, the conversion value range is from 54 to 61.

Resonator
I used 4-MHz resonator.
I used 4 MHz in the relation of the timer in the count time.
When using 4-MHz clock, it is 1 microsecond per count for
the counter count up time. Timer1 to use for capture is a
maximum of 65535 counts(16 bits). So, a maximum of
65.535 milliseconds count is made.
The propagation speed of the sound in air is 343 m/second in
case of 20°C. In the time which goes and returns in the 10-m
distance, it is 20m/343m/sec = 0.0583 seconds (58.3
milliseconds). As the range meter this time, it is an exactly
good value.

Power supply circuit


The voltage of +5V and +9V are made with +12V power supply using the 3 terminal regulator.
+9V are used for the transmitter and the receiver. 100-mA type is used because few needed electric
currents.
In other circuit, +5V is used. +5V voltage is used for the lighting-up of LEDs, because they are
controlled by PIC. The about 10-mA electric current per segment flows through the LED. So, it
becomes about 80 mA when all segments(eight) light up.
Because few electric currents of the other IC occur, I think that you can use a 100-mA type, too. I used
a 1A type for the safety.
Parts explanation for Ultrasonic Range Meter

Ultrasonic sensor
I used the ultrasonic sensor for the air which is made by the Nippon Ceramic
company. This sensor separates into the two kinds for the transmitter and the
receiver. For the transmitter, it is T40-16 and for the receiver, it is R40-16. T
shows the thing for the transmitter and R shows the thing for the receiver. 40
shows the resonant frequency of the ultrasonic.(40kHz) 16 shows the diameter of
the sensor.
Because the one of the terminal is connected with the case, when grounding, the
terminal on the side of the case should be used.

The brief specification of the ultrasonic sensor is shown below.


Item Spec
Frequency(KHz) 40
Sound pressure
115 <
level (dB)
Sensitivity (dB) -64 <
Diameter 16.2
Size
(mm) Height 12.2
Interval 10.0

As for the detail specification, refer to "The specification of the ultrasonic sensor".
PIC1
6F87
3
In the
circuit
this
time,
capture
feature
and
A/D
convert
er
feature
are
used.

Data sheet for PIC16F873

Low noise operational amplifiers ( LM833N )

This IC is the low noise operational amplifier. It is used for the


amplification of the received ultrasonic signal.
The low noise type operational amplifier should be used because it does the about 60dB (1000 times)
amplification.

Data sheet for LM833

Low power operational amplifiers ( LM358 )

This IC is the single power supply-type operational amplifier. This IC is used for the detection of the received
signal.
The comparator can be used.

Data sheet for LM358


NAND gates ( 4011B )

As for this IC, the four NAND circuits of 2 inputs


are accommodated. It is used to compose SR-FF
and to hold the detection condition of the
ultrasonic.

Data sheet for 4011B

Inverters ( 4069UB )

This IC is the IC of the CMOS which the six inverters


are housed in.
At the transmitter circuit, it is used for the drive circuit of
the ultrasonic sensor.

Data sheet for 4069UB

3 terminal voltage regulator for +5 V ( 7805 )

This regulator is used to make the stable power of +5V.


The maximum output current is 1A.

Data sheet for 7805

3 terminal voltage regulator for +9 V ( 78L09 )

The stable +9V can be gotten from +12V input by this IC.
The maximum output current is 100 mA.

Data sheet for 78L09


Transmitter drive transistor ( 2SC1815 )

This is the transistor to drive the C-MOS inverter which works at 9V with
the output of PIC. The output of PIC is from 0V to 5V. This transistor converts into the voltage from 0V to
9V to control the inverter.

Data sheet for 2SC1815

LED control transistor ( 2SA1015 )

This transistor is used to control the 7 segment LED. PNP type is used for controlling the anode side of the
LED.

Data sheet for 2SA1015

Shottky barrier
diode ( 1SS106 )
These diodes are used to
detect the received ultrasonic.
The ultrasonic frequency is about 40KHz, so, the diode
with the good high frequency characteristic is used.

Data sheet for 1SS106

7 segment LED

I use SL-1199 made by Sanyo Electric Co in Japan.


The size is 18.8mm(H) x 12mm(W) x 8mm(D).

Installation stand of 7 segment LED


I assumed that a range meter was put in the case and ma
an LED installation stand.
It is the one to have bent a 2-mm thickness acrylic board
has 11mm(H), 40mm(W), 13mm(D).
Because the thickness is 2 mm, the board is the followin
size.

IC socket
PIC16F873 is 28 pins of the slim type. When you can no
get a slim-type 28 pin socket, two sockets of 14 pins can
used. In the circuit this time, I used two 14 pin sockets.

Resonator

I used 4-MHz resonator.


At the circuit this time, the timer value is important and can not be used except 4 MHz.

Variable resistor for display proofreading

I used B type.
Resistor

I used 1/8W as all resistors.

Ceramic capacitor

These are the disk-type ceramic capacitors.


Because the high frequency characteristic is good, these are used as the coupling capacitors(It cuts the direct
current but it lets through the alternating current) of the ultrasonic signal amplification.

Multilayer ceramic capacitor


These capacitors are used to bypass the high frequency noise of the input and
output of the power supply.

Electrolytic capacitor
This capacitor is used as the ripple filter
capacitor of the power circuit.
There is polarity. So, Be careful so as not to make a mistake
when mounting it.

Printed board
I used the universal board with the 25 x 30 holes.
Wiring terminal
This terminal is used to connect power supply wire and wire for the variable
resistor for display proofreading.

Stud

These studs are used to install the equipment in the case.


Source code file of Ultrasonic Range Meter
001 ;********************************************************
002 ;
003 ; Ultrasonic Range Meter
004 ;
005 ; Divice : PIC16F873
006 ; Author : Seiichi Inoue
007 ;********************************************************
008
009 list p=pic16f873
010 include p16f873.inc
011 __config _hs_osc & _wdt_off & _pwrte_on & _lvp_off
012
013 ;**************** Label Definition ********************
014 cblock h'20'
015 s_count ;Send-out pulse count adr
016 s_adj ;Adjustment data address
017 s_adj_count ;Rotate value save adr
018 s_digit ;Digit cont work address
019 g_time1 ;Guard timer address 1
020 g_time2 ;Guard timer address 2
021 p_countl ;Propagation L cnt adr
022 p_counth ;Propagation H cnt adr
023 digit_cnt ;Digit counter head adr
024 disp_ha ;Digit head address
025 disp_u ;1st digit address
026 disp_t ;10th digit address
027 disp_h ;100th digit address
028 seg7_ha ;7 segLED table head adr
029 seg70 ;Pattern 0 set adr
030 seg71 ;Pattern 1 set adr
031 seg72 ;Pattern 2 set adr
032 seg73 ;Pattern 3 set adr
033 seg74 ;Pattern 4 set adr
034 seg75 ;Pattern 5 set adr
035 seg76 ;Pattern 6 set adr
036 seg77 ;Pattern 7 set adr
037 seg78 ;Pattern 8 set adr
038 seg79 ;Pattern 9 set adr
039 seg7a ;Pattern A set adr
040 seg7b ;Pattern B set adr
041 endc
042
043 ra1 equ h'01' ;RA1 port designation
044 ra2 equ h'02' ;RA2 port designation
045 ra3 equ h'03' ;RA3 port designation
046 ra5 equ h'05' ;RA5 port designation
047
048 ccp1 equ h'02' ;CCP1(RC2) designation
049
050 seg7_0 equ b'01000000' ;-gfedcba Pattern 0
051 seg7_1 equ b'01111001' ; Pattern 1
052 seg7_2 equ b'00100100' ; Pattern 2
053 seg7_3 equ b'00110000' ; Pattern 3
054 seg7_4 equ b'00011001' ; Pattern 4
055 seg7_5 equ b'00010010' ; Pattern 5
056 seg7_6 equ b'00000010' ; Pattern 6
057 seg7_7 equ b'01111000' ; Pattern 7
058 seg7_8 equ b'00000000' ; Pattern 8
059 seg7_9 equ b'00010000' ; Pattern 9
060 seg7_a equ b'01111111' ; Detect error
061 seg7_b equ b'00100011' ; Illegal int
062
063 ;**************** Program Start ***********************
064 org 0 ;Reset Vector
065 goto init
066 org 4 ;Interrupt Vector
067 goto int
068
069 ;**************** Initial Process *********************
070 init
071
072 ;*** Port initialization
073 bsf status,rp0 ;Change to Bank1
074 movlw b'00000001' ;AN0 to input mode
075 movwf trisa ;Set TRISA register
076 clrf trisb ;RB port to output mode
077 movlw b'00000100' ;RC2/CCP1 to input mode
078 movwf trisc ;Set TRISC register
079
080 ;*** Ultrasonic sending period initialization (Timer0)
081 movlw b'11010111' ;T0CS=0,PSA=0,PS=1:256
082 movwf option_reg ;Set OPTION_REG register
083 bcf status,rp0 ;Change to Bank0
084 clrf tmr0 ;Clear TMR0 register
085
086 ;*** Capture mode initialization (Timer1)
087 movlw b'00000001' ;Pre=1:1 TMR1=Int TMR1=ON
088 movwf t1con ;Set T1CON register
089 clrf ccp1con ;CCP1 off
090
091 ;*** A/D converter initialization
092 movlw b'01000001' ;ADCS=01 CHS=AN0 ADON=ON
093 movwf adcon0 ;Set ADCON0 register
094 bsf status,rp0 ;Change to Bank1
095 movlw b'00001110' ;ADFM=0 PCFG=1110
096 movwf adcon1 ;Set ADCON1 register
097 bcf status,rp0 ;Change to Bank0
098
099 ;*** Display initialization (Timer2)
100 movlw disp_u ;Set digit head address
101 movwf disp_ha ;Save digit head sddress
102 movlw h'0a' ;"Detect error" data
103 movwf disp_u ;Set 1st digit
104 movwf disp_t ;Set 10th digit
105 movwf disp_h ;Set 100th digit
106 movlw d'3' ;Digit counter
107 movwf digit_cnt ;Set digit counter
108 movlw seg70 ;Set 7seg head address
109 movwf seg7_ha ;Save 7seg head address
110 movlw seg7_0 ;Set 7segment pattern 0
111 movwf seg70 ;Save pattern 0
112 movlw seg7_1 ;Set 7segment pattern 1
113 movwf seg71 ;Save pattern 1
114 movlw seg7_2 ;Set 7segment pattern 2
115 movwf seg72 ;Save pattern 2
116 movlw seg7_3 ;Set 7segment pattern 3
117 movwf seg73 ;Save pattern 3
118 movlw seg7_4 ;Set 7segment pattern 4
119 movwf seg74 ;Save pattern 4
120 movlw seg7_5 ;Set 7segment pattern 5
121 movwf seg75 ;Save pattern 5
122 movlw seg7_6 ;Set 7segment pattern 6
123 movwf seg76 ;Save pattern 6
124 movlw seg7_7 ;Set 7segment pattern 7
125 movwf seg77 ;Save pattern 7
126 movlw seg7_8 ;Set 7segment pattern 8
127 movwf seg78 ;Save pattern 8
128 movlw seg7_9 ;Set 7segment pattern 9
129 movwf seg79 ;Save pattern 9
130 movlw seg7_a ;Set 7segment pattern A
131 movwf seg7a ;Save pattern A
132 movlw seg7_b ;Set 7segment pattern B
133 movwf seg7b ;Save pattern B
134 movlw b'00011110' ;OPS=1:4,T2=ON,EPS=1:16
135 movwf t2con ;Set T2CON register
136 bsf status,rp0 ;Change to Bank1
137 movlw d'157' ;157x64=10048usec
138 movwf pr2 ;Set PR2 register
139 bsf pie1,tmr2ie ;TMR2IE=ON
140 bcf status,rp0 ;Change to Bank0
141
142
143 ;*** Interruption control
144 movlw b'11100000' ;GIE=ON,PEIE=ON,T0IE=ON
145 movwf intcon ;Set INTCON register
146
147 wait
148 goto $ ;Interruption wait
149
150 ;*************** Interruption Process *****************
151 int
152 movfw pir1 ;Read PIR1 register
153 btfsc pir1,ccp1if ;Capture occurred ?
154 goto capture ;Yes. "Capture"
155 btfsc pir1,tmr2if ;TMR2 time out ?
156 goto led_cont ;Yes. "LED display"
157 movfw intcon ;Read INTCON register
158 btfsc intcon,t0if ;TMR0 time out ?
159 goto send ;Yes. "Pulse send"
160
161 ;*************** Illegal interruption *****************
162 illegal
163 movlw h'0b' ;Set Illegal disp digit
164 addwf seg7_ha,w ;Seg7 H.Adr + digit
165 movwf fsr ;Set FSR register
166 movfw indf ;Read seg7 data
167 movwf portb ;Write LED data
168 bcf porta,ra1 ;RA1=ON
169 bcf porta,ra2 ;RA2=ON
170 bcf porta,ra3 ;RA3=ON
171 goto $ ;Stop
172
173 ;************ END of Interruption Process **************
174 int_end
175 retfie
176
177 ;*************** Pulse send-out Process ****************
178 send
179 bcf intcon,t0if ;Clear TMR0 int flag
180 clrf tmr0 ;Timer0 clear
181
182 ;*** Received Pulse detection check
183 movfw portc ;Read PORTC register
184 btfsc portc,ccp1 ;Detected ?
185 goto detect_off ;Yes. Detected
186 movlw h'0a' ;"Detect error" data
187 movwf disp_u ;Set 1st digit
188 movwf disp_t ;Set 10th digit
189 movwf disp_h ;Set 100th digit
190
191 ;*** Receive pulse detector off
192 detect_off
193 bcf porta,ra5 ;Set detector OFF
194
195 ;*** Capture start
196 clrf tmr1h ;Clear TMR1H register
197 clrf tmr1l ;Clear TMR1L register
198 clrf ccpr1h ;Clear CCPR1H register
199 clrf ccpr1l ;Clear CCPR1L register
200 movlw b'00000101' ;CCP1M=0101(Capture)
201 movwf ccp1con ;Set CCP1CON register
202 bsf status,rp0 ;Change to Bank1
203 bsf pie1,ccp1ie ;CCP1 interruptin enable
204 bcf status,rp0 ;Change to Bank0
205 bcf pir1,ccp1if ;Clear CCP1 int flag
206
207 ;*** 40KHz pulse send ( 0.5 msec )
208 movlw d'20' ;Send-out pulse count
209 movwf s_count ;Set count
210 s_loop
211 call pulse ;Call pulse send sub
212 decfsz s_count,f ;End ?
213 goto s_loop ;No. Continue
214
215 ;*** Get adjustment data
216 bsf adcon0,go ;Start A/D convert
217 ad_check
218 btfsc adcon0,go ;A/D convert end ?
219 goto ad_check ;No. Again
220 movfw adresh ;Read ADRESH register
221 movwf s_adj ;Save converted data
222
223 movlw d'5' ;Set rotate value
224 movwf s_adj_count ;Save rotate value
225 ad_rotate
226 rrf s_adj,f ;Rotate right 1 bit
227 decfsz s_adj_count,f ;End ?
228 goto ad_rotate ;No. Continue
229 movfw s_adj ;Read rotated value
230 andlw b'00000111' ;Pick-up 3 bits
231 addlw d'54' ;(0 to 7) + 54 = 54 to 61
232 movwf s_adj ;Save adjustment data
233
234 ;*** Capture guard timer ( 1 milisecound )
235 movlw d'2' ;Set loop counter1
236 movwf g_time1 ;Save loop counter1
237 g_loop1 movlw d'124' ;Set loop counter2
238 movwf g_time2 ;Save loop counter2
239 g_loop2 nop ;Time adjust
240 decfsz g_time2,f ;g_time2 - 1 = 0 ?
241 goto g_loop2 ;No. Continue
242 decfsz g_time1,f ;g_time1 - 1 = 0 ?
243 goto g_loop1 ;No. Continue
244
245 ;*** Receive pulse detector on
246 bsf porta,ra5 ;Set detector ON
247
248 goto int_end
249
250 ;*************** Pulse send-out Process ****************
251 pulse
252 movlw b'00010000' ;RC4=ON
253 movwf portc ;Set PORTC register
254 call t12us ;Call 12usec timer
255 clrf portc ;RC4=OFF
256 goto $+1
257 goto $+1
258 nop
259 return
260
261 ;*************** 12 microseconds timer *****************
262 t12us
263 goto $+1
264 goto $+1
265 goto $+1
266 goto $+1
267 nop
268 return
269
270 ;****************** Capture Process ********************
271 capture
272 bcf pir1,ccp1if ;Clear CCP1 int flag
273
274 clrf p_countl ;Clear L count
275 clrf p_counth ;Clear H count
276 clrf ccp1con ;CCP1 off
277
278 division
279 movfw s_adj ;Read adjustment data
280 subwf ccpr1l,f ;Capture - adjust
281 btfsc status,z ;Result = 0 ?
282 goto division2 ;Yes. "R = 0"
283 btfsc status,c ;Result < 0 ?
284 goto division1 ;No. "R > 0"
285 goto division3 ;Yes."R < 0"
286
287 division1 ;( R > 0 )
288 movlw d'1' ;Set increment value
289 addwf p_countl,f ;Increment L count
290 btfss status,c ;Overflow ?
291 goto division ;No. Continue
292 incf p_counth,f ;Increment H count
293 goto division ;Jump next
294
295 division2 ;( R = 0 )
296 movfw ccpr1h ;Read CCPR1H
297 btfss status,z ;CCPR1H = 0 ?
298 goto division1 ;No. Next
299 movlw d'1' ;Set increment value
300 addwf p_countl,f ;Increment L count
301 btfss status,c ;Overflow ?
302 goto digit_set ;Jump to digit set
303 incf p_counth,f ;Increment H count
304 goto digit_set ;Jump to digit set
305
306 division3 ;( R < 0 )
307 movfw ccpr1h ;Read CCPR1H
308 btfss status,z ;CCPR1H = 0 ?
309 goto division4 ;No. Borrow process
310 goto digit_set ;Jump to digit set
311
312 division4
313 decf ccpr1h,f ;CCPR1H - 1
314 movlw d'255' ;Borrow value
315 addwf ccpr1l,f ;CCPR1L + 255
316 incf ccpr1l,f ;CCPR1L + 1
317 goto division1 ;Next
318
319 ;**************** Digit Set Process ********************
320 digit_set
321 clrf disp_u ;Clear 1st digit
322 clrf disp_t ;Clear 10th digit
323 clrf disp_h ;Clear 100th digit
324
325 ;*** 100th digit
326 digit_h
327 movlw d'100' ;Divide value
328 subwf p_countl,f ;Digit - divide
329 btfsc status,z ;Result = 0 ?
330 goto digit_h2 ;Yes. "R = 0"
331 btfsc status,c ;Result < 0 ?
332 goto digit_h1 ;No. "R > 0"
333 goto digit_h3 ;Yes."R < 0"
334
335 digit_h1 ;( R > 0 )
336 incf disp_h,f ;Increment 100th count
337 goto digit_h ;Jump next
338
339 digit_h2 ;( R = 0 )
340 movfw p_counth ;Read H counter
341 btfss status,z ;H counter = 0 ?
342 goto digit_h1 ;No. Next
343 incf disp_h,f ;Increment 100th count
344 goto digit_t ;Jump to 10th digit pro
345
346 digit_h3 ;( R < 0 )
347 movfw p_counth ;Read H counter
348 btfss status,z ;H counter = 0 ?
349 goto digit_h4 ;No. Borrow process
350 movlw d'100' ;Divide value
351 addwf p_countl,f ;Return over sub value
352 goto digit_t ;Jump to 10th digit pro
353
354 digit_h4
355 decf p_counth,f ;H counter - 1
356 movlw d'255' ;Borrow value
357 addwf p_countl,f ;L counter + 255
358 incf p_countl,f ;L counter + 1
359 goto digit_h1 ;Next
360
361 ;*** 10th digit
362 digit_t
363
364 ;*** Range over check
365 movfw disp_h ;Read 100th digit
366 sublw d'9' ;9 - (100th digit)
367 btfsc status,z ;Result = 0 ?
368 goto digit_t0 ;Yes. "R = 0"
369 btfsc status,c ;Result < 0 ?
370 goto digit_t0 ;No. "R > 0"
371 movlw h'0a' ;"Detect error" data
372 movwf disp_u ;Set 1st digit
373 movwf disp_t ;Set 10th digit
374 movwf disp_h ;Set 100th digit
375 goto int_end
376
377 digit_t0
378 movlw d'10' ;Divide value
379 subwf p_countl,f ;Digit - divide
380 btfsc status,z ;Result = 0 ?
381 goto digit_t1 ;Yes. "R = 0"
382 btfsc status,c ;Result < 0 ?
383 goto digit_t1 ;No. "R > 0"
384 goto digit_t2 ;Yes."R < 0"
385
386 digit_t1 ;( R >= 0 )
387 incf disp_t,f ;Increment 10th count
388 goto digit_t ;Jump next
389
390 digit_t2 ;( R < 0 )
391 movlw d'10' ;Divide value
392 addwf p_countl,f ;Return over sub value
393 goto digit_u ;Jump to 1st digit pro
394
395 ;*** 1st digit
396 digit_u
397 movfw p_countl ;Read propagetion counter
398 movwf disp_u ;Save 1st count
399
400 goto int_end
401
402 ;**************** LED display control *****************
403 led_cont
404 bcf pir1,tmr2if ;Clear TMR2 int flag
405
406 movfw digit_cnt ;Read digit counter
407 movwf s_digit ;Save digit counter
408 decfsz s_digit,f ;1st digit ?
409 goto d_check1 ;No. Next
410 bsf porta,ra1 ;RA1=OFF
411 bsf porta,ra2 ;RA2=OFF
412 bcf porta,ra3 ;RA3=ON
413 goto c_digit ;Jump to digit cont
414 d_check1
415 decfsz s_digit,f ;10th digit ?
416 goto d_check2 ;No. 100th digit
417 bsf porta,ra1 ;RA1=OFF
418 bcf porta,ra2 ;RA2=ON
419 bsf porta,ra3 ;RA3=OFF
420 goto c_digit ;Jump to digit cont
421 d_check2
422 bcf porta,ra1 ;RA1=ON
423 bsf porta,ra2 ;RA2=OFF
424 bsf porta,ra3 ;RA3=OFF
425
426 c_digit
427 decf digit_cnt,w ;Digit count - 1
428 addwf disp_ha,w ;Digit H.Adr + count
429 movwf fsr ;Set FSR register
430 movfw indf ;Read digit
431 addwf seg7_ha,w ;Seg7 H.Adr + digit
432 movwf fsr ;Set FSR register
433 movfw indf ;Read seg7 data
434 movwf portb ;Write LED data
435
436 decfsz digit_cnt,f ;Digit count - 1
437 goto int_end ;Jump to interrupt end
438 movlw d'3' ;Initial value
439 movwf digit_cnt ;Set initial value
440 goto int_end ;Jump to interrupt end
441
442 ;********************************************************
443 ; END of Ultrasonic Range Meter
444 ;********************************************************
445
446 end
Processing explanation of Ultrasonic Range Meter

This range meter detects a reflected wave from the object after sending out a ultrasonic pulse.
By measuring the time which returns after emitting a sound wave, a distance to the object is measured.

The operation of the following figure is repeatedly executed.


LED display processing is executed in parallel with this operation.

Label definition
;**************** Label Definition ********************
cblock h'20'
s_count ;Send-out pulse count adr

endc
I used CBLOCK directive for the definition of the workarea.
When using this directive, workareas which were defined between CBLOCK and ENDC are
automatically allocated in the order from the address which was specified by the operand of
CBLOCK. It is convenient because it is possible to prevent the double allocation of the area.
To confirm an allocated address, you confirm it by the assembly result.

Lighting-up segment data for 7 segments LED are designated by EQU.


The data from 0 to 9 is used for digital display. However, the 10th is used for the detection
error display.
At first, I make light up only center segment. But I turned off all segments because the display
was confusing.

The 11th is used for the interruption error display. It is for the debugging.

Environment designating and others


As for LIST and INCLUDE directive and Program start, refer to "Light controller".

The following specification is done as configuration word.


Oscillator : HS
Watchdog Timer : OFF
Power-up Timer : enabled
Low Voltage : OFF
ICSP (RB3 can not be used for the input/output port when not making this
OFF).

The result is 3F72h.

Initialization process
;**************** Initial Process *********************
Port initialization
Because the RA0/AN0 port is used for input of A/D converter, it is set to input mode.
Other A ports are set to the output. All B ports are set to output because it is used for
the LED segment control.
RC2/CCP1 of C port is set to the input mode because it is used for input of capture.

Ultrasonic transmission period timer(TMR0) initialization


The transmission period of the ultrasonic is controlled using timer0. Because timer0 is
a timer with byte, the count value is up to 256. However, it is making count 65535 by
setting the prescaler to 256. (256 x 256 = 65535) This time, because it is using 4 MHz
for the oscillator, 1 count is 1 microsecond. (1/(4 x 106))x4=10-6 seconds
So, the time-out time of timer0 is about 65 milliseconds.

Capture mode initialization


Timer1 is used for capture. Timer1 is initialized.
At the time of the initialization, it makes CCP1 OFF to prevent from a malfunction.

A/D converter initialization


Channel 0 is set as the converter input. Because the clock to use this time is 4 MHz,
Fosc/8 is set to A/D conversion clock.
Because the higher rank side of the A/D converted result are used, the storage of the
result is made right justification (ADFM=0).
Because A porta are used for the output of the digit specification of the LED, ports
except RA0/AN0 are made digital specification.

LED display period timer(TMR2) initialization


Display data for 7 segments LED are set to workarea. The initial value of the display
is "the error code".
The time-out of timer2 is about 10 milliseconds.
The interruption eable bits of the capture and timer2 are set.

Interruption initialization
It makes timer0 interruption, peripheral device interruption, global interruption
possible.
The interruption of the capture and timer2 doesn't occur when not making peripheral
device interruption possible.
By this process, interruption operation is started.
When the initialization process ends, the interruption is waited for. It executes same address
repeatedly.
Interruption process
;*************** Interruption Process *****************
Capture interruption, timer2 interruption, timer0 interruption are checked. The kind of the
interruption is judged by each interruption flag. After that, it jumps to the corresponding
interruption process.
When the kind of the interruption is unsettled, processing is stopped. To confirm illegal
interruption with the actual circuit, an in-circuit simulator is needed. There is a way of
resetting but it isn't improved because it does the same operation even if it resets.
A global interruption enable bit (the GIE bit) is automatically cleared when the interruption
occurs. So, the interruption never occurs while processing in the interruption.

Illegal interruption process


;*************** Illegal interruption *****************
It displays an interruption error to the LED when the illegal interruption occurs.
This process is the process for debugging and is usable with the other checking, too.

Interruption ending process


;************ END of Interruption Process **************
As for the software this time, all processing is done by the interruption except the initialization
processing. The common registers(W register, Status register) are not used in the interrupted
process (Main process). So, the saving and resaving process for them isn't need.
In the interruption ending process, GIE bit is set by RETFIE instruction to enable interruption.

Ultrasonic pulse sending-out process


;*************** Pulse send-out Process ****************
In the pulse sending-out process, the following process is done.

Clear the interruption display


The interruption flag of TMR0 is cleared. When not clearing this flag, the interruption
occurs at once when interruption processing is ended without waiting a regular time-
out.
I clear the count area of timer0 because of the sure operation.

Check the detection error


When the detection of the reflected wave isn't done from the pulse sending-out in the
last time until the pulse sending-out this time, it means measurement impossible and
display is turned off. The previous data is displayed in the measurement impossible
condition when not doing this process and the mistake occurs to the measurement.

Stop the reflected wave detector


Immediately after letting out a transmission pulse, the influence occurs to the receiver
circuit and there is possibility to do wrong detection. To prevent from this, the
operation of the reflected wave detector is stopped. The RA4 port is an open type and
an external resistor is needed. So, I used RA5.
Start the capture operation
The count area of timer1 and the contents of the capture register are cleared. the rising
edge detection mode capture is set and a capture interruption enable bit is set. And an
interruption flag is cleared because of the sure operation.

Send-out the 40KHz pulse


The 40KHz pulse is the pulse which has 12.5 µ-sec as ON time and 12.5 µ-sec as
OFF time in 1 cycle.
Because 4-MHz clock is used at the circuit this time, the instruction execution time is
1 microsecond. So, correct 40KHz can not be sent out. When doing ON, OFF
respectively with the 12 µ-sec, it is 41.7KHz. In case of 13 µ-sec, it is 38.5KHz. This
time is adjusted by changing the number of the steps in the pulse sending-out
processing.
It is 0.5 milliseconds when sending out 20 pulses. (20pulses x 0.025milliseconds/pulse)

Take-in the display revision data


To make operate A/D converter, the GO bit of the ADCON0 register is set. When
switching the input channel of A/D converter, after switching the input, about 20
microseconds waiting time is needed. This time, because the input channel is fixed on
0, waiting time isn't necessary. The completion of the A/D conversion is judged by
the checking the GO bit. When GO bit is cleared, the conversion is completion. The
upper 3 bits is picked up and add 54 as the conversion value.

Error detection prevention


A detector is stopped until the influence ends to the receiver after sending out a pulse.
I set this time to about 1 millisecond. When few influences occur, it is to be OK even
if it is shorter. When many influences occur, it is necessary to make longer.

Start the reflected wave detection


After the wrong detection prevention time elapse, it is made a enable condition in the
reflected wave detection.

Capture interruption process


;****************** Capture Process ********************
In the capture interruption process, the following process is done.

Clear the interruption display


Capture interruption flag is cleared.

Distance conversion processing


The count value of the timer0 which was stopped by the capture operation is
proportional to the propagation time of the sound wave. It isn't possible to use for the
display just as it is. In the processing this time, division by some value is done and is
converted into the distance numerical value.
For example, I will explaine in case to have been reflected from the 1-m distance.
In the time that the sound wave goes and returns in 1 m, it is 2m/343m/sec=5831
microseconds in case of 20°C. Because the clock of timer0 is 1µ-sec/count, the value
of the timer0 when a capture is done is 5831. It is to be OK if using 58 as the divisor
to make display this value as 100(It displays 1 m). The value to take in by the A/D
converter is used for a divisor. So, when the temperature is different, the display can
be revised if changing the input voltage to the A/D converter. But, because it is
changed in the digital, it isn't possible to do fine adjustment.
Display setting processing
Because the type of distance value which is converted is binary, it can not be
displayed on the LED just as it is.
Binary number is converted into the decimal number and is set to each
workarea(100th, 10th, 1st).
When 100th digit exceeds 9, it makes error display.

LED display process


;**************** LED display control *****************
This is the process to display the distance numerical value which was gotten by the capture to
the LED.
One LED is controlled at each period. So, only 1 digit is displayed at the same time.
Display is done every 10 milliseconds using timer2. When the display flickers, you should
make the set value of timer2 more little and it quickens a period.
Improvement of Ultrasonic Range Meter

Actually, it doesn't work as assumed first when assembling a circuit and confirming operation.
I will explain the items which were improved including the point which wasn't normally worked when
making this circuit below.

RA4 port
At first, the control of the reception pulse detector(start/stop) was controlled by RA4 port.
The RA4 port is a special port in the PIC16F series and I have made same mistakes before.
The output of the RA4 port is an open type. So, when setting RA4 port to the H level
condition, it is only separated from the grounding and it doesn't become H level. To make RA4
H level, the pull-up resistor must be put outside.
Because mounting space of the printed board was limited at this circuit, I changed to use RA5
port.

Temperature revision data


The sound wave propagation speed in air changes with the ambient temperature. A distance
conversion value is made by A/D converted voltage whitch changed by variable resistor. The
change range with this conversion value is very narrow. At first, I used the way that little
voltage change by the variable resistor. However, in this way, it wasn't possible to make do
stable operation by the influence by the induced voltage from outside. Therefore, I made a
voltage change range by the variable resistor from 0 V to 5 V and to cope by the processing of
data after A/D conversion. Upper 3 bits of A/D converted data are used as the variable data.
With this, the influence of the induction from outside passed away.

Power supply voltage of the receiver circuit


At first, I made the power supply voltage of the receiver circuit 5V according to PIC.
However, I considered the voltage which generates with the receive sensor when receiving a
ultrasonic and changed the voltage of the receiver circuit into 9V. In case of 5V, I think that an
amplifier is saturated in the signal voltage and it isn't possible to do good detection operation. I
am not verifying 5V receiver operation in detail.
Because the signal holding circuit and PIC operate with 5V, the output of the signal
detector(0V-9V) is divided with the resistor and is changed into TTL(0V-5V).

Capture start timing


The capture function has the possibility to malfunction with the noise. In the first software, I
was setting capture operation at the initialization processing. However, in the case, the illegal
capture interruption occurred. Therefore, in the initialization processing, I made only the
initialization processing of the timer1 to use for the capture. The setting of capture operation is
done when starting capture operation (Immediately before the ultrasonic pulse sending-out).

Grounding
This circuit handles the analog signal of 40KHz. The level of the analog signal changes subtly
by the circuit wiring. For this circuit, the wiring by the printed board considered grounding is
better.
When installing this circuit in the acrylic case, it should install a circuit onto the brass board as
the ground board.
Adjustment of the transmission frequency
40KHz for the ultrasonic is generating by the software. The resonant frequency of the
transmission sonar is 40KHz. The transmission frequency must be adjusted to the resonant
frequency. The transmission efficiency declines when not fitting. The adjustment of the
frequency is done by the number of the steps of the software. It adjusts ON/OFF equally.
Connect a simple level meter with the node of D1 and D2 and adjust soft steps for a level to be
maximized. It is necessary to do while rewriting software using programmer. The equipment
and the reflection board must be fixed to compare in the same environment. It isn't possible to
compare when the reflected quantity has changed. This is a little bit hard work.

Length of the transmission pulse


I set the length of the transmission pulse of this equipment in the 0.5 milliseconds. When the
time of the pulse is long, the energy of the ultrasonic is big and the long-range measurement
becomes possible. However, when making a transmission pulse long, the signal which
influences a receiver increases. Therefore, the guard time must be made long and it becomes
not possible to do the measurement of the short distance. The shortest measurement distance is
decided by total value of guard time and the pulse sending-out time.(In this circuit, it's 1.5
milliseconds) This time, about 30 cm are the shortest measurement distance.

Calculation for 10th


There was a mistake in the calculation of the 10th digit in the process which changes the
captured distance value into the 100th, 10th, 1st digit. The 10th wasn't increased in case of the
1st digit value is 0, i.e. 10, 20, 30 ··· 90. Therefore, the result becomes the value which is
insufficient in 10. For example, when making a measuring distance short little by little from
112, it changes like 112, 111, 100(should be 110), 109, 108. This is the cause of the mistake of
the following source code.
381 goto digit_u ;Yes. "R = 0"
In this code, when the value(R) that 10 was subtracted is 0, it jumps to the 1st digit process
without adding 1 to the 10th count area(disp_t).
The correction cord is hereinafter.
381 goto digit_t1 ;Yes. "R = 0"
When the value that 10 was subtracted is 0, it makes jump to the process for adding 1 to disp_t.
Thank you for Mr. Ooi.
Performance test of Ultrasonic Range Meter

I confirmed the performance of the


Ultrasonic Range Meter.

Detection operation
confirmation
The photograph on the left is the one
to have observed the signal when
measuring a 2.36m distance.
Observation points are shown below.
(1) is 1st pin of IC1 ( It is a signal
after the amplification with the
operational amplifier. )
(2) is 8th pin of IC3 ( It is a detection
holding circuit gate signal by PIC. )
(3) is 11th pin of IC3 ( It is an output
signal of the detection holding circuit.
)

When (2) is an L level, the detector stops. You can find that a malfunction by the transmission pulse is
prevented. The prevention time of this circuit is about 1.5 milliseconds. There is possibility to
malfunction when short any more.

Some feeble reflection signals are received until it detects a reception pulse. Because the threshold
voltage of the signal detector of IC2 is working effectively, those feeble signals are not detected.

The signal of (3) changes to H level from L level when detecting a reception pulse. This signal is
detected by the capture feature of PIC and the propagation time of the ultrasonic is measured.

Measuring range
The ultrasonic transmission time of this Meter is 0.5 milliseconds. So, it isn't possible to do
long-range measurement.
Most short : 29 cm
distance This distance is decided by the time to prevent from an influence by
the transmission pulse.
When measuring a long distance, the sending-out time of the
transmission pulse must be expanded. In this case, it is necessary to
expand in the prevention time, too, and the shortest measurement
distance becomes long.
Most long distance : 3.6 m
This distance is decided by the length of the transmission pulse. The
ultrasonic energy becomes big when the transmission time is long
and the long-range measurement is possible. However, as the
explaining at the most short distance, the shortest measurement
distance becomes long.

When wanting to do long-range measurement, it is possible to change software even if it


doesn't change hardware of it. In this case, I think that it is better when putting a sound horn to
concentrate a ultrasonic.
Temperature calibration feature

I confirmed a display in distance measurement of 1 m.

Dial Temperature
Display
condition for displaying 1.00

Full turn
to right 0.98 8.6°C

Full turn
to left 1.11 83.0°C

The temperature to display 1.00 is a calculation value.


At this equipment, it isn't possible to do an adjustment with
detailed calibration value. It is 8 steps. So, it is a reference value.
To change a calibration range, the change of the software
processing by the value which A/D converted is needed.

When doing this confirmation, I found the opposite connection of the calibration resistor. The
connection in the center is right but the connection in the both edges is opposite. I intended to turn to
the right when the ambient temperature was high. However, the actual operation is opposite. Because it
is not in the problem in case of practical use, I don't change it. A schematic and a pattern drawing are
corrected.

You might also like