Вы находитесь на странице: 1из 18

Contador de abejas

Casa

Kits están disponibles para este proyecto desde


Electrónica parlante por $ 20.00 más gastos de envío.
Además, necesitarás:
Adaptador de 6 pines a 5 pines a $ 2.50

También necesitarás:
PIC2 USB Burner (MPASM y MPLAB vienen con PIC2) e incluye cable USB

Hoja de datos PIC12F629 (.pdf 4,926KB)


Conjunto de instrucciones para PIC12F629
Plantilla blank12F629.asm
PIC12F629.inc

Ver más proyectos usando micros:


Elektor, EPE, Chip de silicio

Notepad2.zip Notepad2.exe
Biblioteca de Sub-rutinas "Cortar y Pegar"
Biblioteca de rutinas: AE EP PZ.

Aquí están los archivos que necesitará:


BeeCounter.asm
BeeCounter-asm.txt
BeeCounter.hex

El diseño del proyecto proviene de un científico investigador de la Universidad.


Su requerimiento era contar el movimiento de una abeja en un tubo.
Se establecieron dos conjuntos de fotodetectores infrarrojos para que el movimiento desde un extremo
del tubo pudiera contarse cuando la abeja regrese al extremo opuesto del tubo. Es un simple requisito de
flip-flop o de palanca.

Contador de abejas en tablero de experimentación


Contador de abejas

Receptor IR y LED IR (Transmisor)

INSTRUCCIONES DE USO
Configure los dos detectores IR y los dos LED IR (transmisores) para que el circuito emita un pitido grave
cuando se interrumpe el detector izquierdo y un pitido agudo cuando se interrumpe el detector derecho.

El circuito
El circuito es muy simple. Son solo 2 LEDs IR, dos receptores IR, un interruptor para escuchar el conteo
(los pitidos de tonos bajos representan los 10 y los pitidos agudos representan los de 1) y un diafragma
piezoeléctrico. Todo el trabajo es realizado por el micro. Está alimentado por 4 células AAA.
CONSTRUCCIÓN
Puedes construir el circuito en placa matriz.
El kit de componentes incluye todas las piezas que necesita para que el proyecto funcione, incluido un
chip preprogramado y la placa de matriz.
Para modificar el programa, necesitará un programador PICkit-2, que viene con 2 CD que contienen todo
el software necesario para la programación en circuito.
También necesitará un cable (viene con PICkit-2) para conectar el programador a su ordenador portátil a
través del puerto USB y un adaptador que llamamos Adaptador de 6 pines a 5 pines para conectar el
PICkit-2 a su proyecto.

PROGRAMANDO EL CHIP
El kit viene con un chip PIC preprogramado, pero si desea programar su propio chip o modificar el
programa, el archivo .hex está disponible, así como el archivo de ensamblaje, para que pueda ver cómo se
ha escrito el programa y ver el Comentarios para cada línea de código.
El PIC12F629 es uno de los micros más pequeños de la gama, pero se sorprenderá de lo mucho que se
puede lograr con un micro tan pequeño.
El programa contiene sub-rutinas para producir retrasos, secuencias en la pantalla y tanto leer como
escribir EEPROM; los trabajos que requieren un código preciso, incluida una secuencia especial, se
denominan una secuencia de intercambio que evita que se escriba la EEPROM debido a problemas
técnicos.
Incluso un programa tan simple como este no es fácil de armar y para ayudar en esta área, hemos
proporcionado una gran cantidad de material de apoyo.
No solo proporcionamos una serie de programas con documentación completa, sino que nuestro
enfoque de la programación es simple.
Implica un método de "copiar y pegar" mediante el cual las subrutinas se toman de un código escrito
previamente y se copian en su programa. Las modificaciones se realizan en pasos muy pequeños para que
cada una pueda probarse antes de agregar más código.
Así es exactamente como producimos un proyecto complejo. Cada paso se escribe y se prueba antes de
agregar el siguiente paso.
Esto ahorra mucha frustración ya que es muy fácil agregar una línea de código que es incorrecta y
obtener un resultado insospechado.
Si sigue nuestras sugerencias, comprará un programador ("quemador") llamado PICkit-2 si está usando
una computadora portátil. Es el mejor y más barato del mercado y viene con un cable USB y 2 CD que
contienen los programas necesarios para "quemar" el chip. Si está utilizando un escritorio y / o una torre con
un puerto serie, puede usar un programador más económico llamado MultiChip Programmer de Talking
Electronics. También necesitarás NotePad2 para escribir tu programa .asm. Esto se puede descargar
desde el sitio web de Talking Electronics. Usará BeeCounter.asm o BeeCounter-asm.txt como base y es
mejor cambiar solo unas pocas líneas a la vez para ver qué efecto se crea. También necesitará un conector
de 6 a 5 pines que se ajuste entre el quemador y el proyecto. Esto también está disponible en el sitio web
de Talking Electronics.
Como dijimos anteriormente, este proyecto es para programadores de nivel medio a avanzado ya que es
muy compacto y no tiene patillas de programación en el circuito.
Para poder modificar el chip, necesitará un zócalo de programación y esto se puede obtener de uno de
nuestros otros proyectos que contiene los 5 pines para la programación en circuito. O puede construir un
zócalo de programación agregando un zócalo a una placa de PC de montaje en superficie y soldando 5
pines a un borde y conectando el zócalo a los pines.
A continuación, puede poner el chip en el zócalo y programarlo.

LENGUAJE DE PROGRAMACIÓN
Hay una serie de kits, programas y cursos en el mercado que afirman y sugieren que enseñan
Programación PIC.
La mayoría de estos módulos y cursos utilizan un microcontrolador PIC como el chip que lleva a cabo los
procesos, pero la programación real se realiza mediante un lenguaje patentado inventado por el diseñador
del curso.
Aunque estos cursos son maravillosos para ingresar a "Microcontroladores de programación", no utilizan
ninguno de los términos o códigos que se aplican a la familia de microcontroladores PIC.
Todos nuestros proyectos utilizan las 33 instrucciones que vienen con el microcontrolador PIC y son muy
fáciles de aprender.
Utilizamos toda la capacidad del micro y nuestro chip preprogramado es menor que el costo de hacerlo
de otra manera.
Además, cualquier cosa diseñada a través de nuestro método puede transferirse instantáneamente a un
dado PIC y producirse en masa. Y usamos todos los pines de entrada y toda la memoria del chip. Los otros
enfoques utilizan menos del 25% de la capacidad de la memoria y uno de los pines no está disponible.
De hecho, sería difícil reproducir este proyecto a través de cualquiera de los métodos de oposición.
Requeriría un chip más grande y más gasto.
Puedes usar nuestro método o la oposición. Solo ten en cuenta que los dos no son intercambiables.
La nuestra está clasificada como la "forma" (nivel) más baja de la programación, comúnmente llamada
código de máquina, inventada en los primeros días de los microprocesadores, y ahora llamada
programación mnemónica, ya que cada línea de código está formada por letras de un conjunto de palabras.
La oposición utiliza un lenguaje de nivel superior donde una instrucción puede realizar una operación similar
a una sub-rutina.
Pero tienes que aprender el "lenguaje de nivel superior" para crear un programa. Y esto requiere una
buena cantidad de habilidad y capacidad.
Suena genial y es una buena idea. Pero si quieres aprender programación PIC, no te ayuda. Es "un paso
eliminado" de aprender el lenguaje PIC. La otra desventaja de la oposición es la "sobrecarga". Los 1,000
espacios asignados para su programa están llenos de sub-rutinas escritas previamente. Es posible que solo
necesite 10 de estas sub-rutinas, pero TODAS se cargan en el espacio de la memoria. Y se llevan toda la
memoria.
No tienes espacio para tu propio programa.
Para evitar esto, la oposición usa los 128 bytes en EEPROM para entregar instrucciones sobre cómo
aplicar las subrutinas. Esto proporciona aproximadamente 30 instrucciones poderosas que usan su lenguaje
llamado BÁSICO (o un idioma similar).
Es un poco como vender un diario lleno de todos los párrafos que necesita para expresarse, y dejar
algunas páginas en blanco en la parte posterior para que escriba líneas simples, tales como: vea la página
24, párrafo 7, vea la página 63 párrafo 4, para Crea tus entradas de diario.
Depende de cuánto quieras estar a cargo de escribir un programa. Usar nuestro método es como escribir
tu propia auto-biografía. Usar la oposición es como conseguir un "escritor fantasma".
Al utilizar un lenguaje de nivel superior para crear un programa, no tiene absolutamente ninguna idea de
cómo se genera el código para el micro.
En algunos de los kits de desarrollo, el código está "bloqueado" y NUNCA puede acceder a él.
Todo funciona sin problemas hasta que aparece una falla. Con nuestro método puedes ver el código.
Con los otros métodos, no puede ver el código; es como hacer una cirugía de agujero de llave sin la ventaja
de un endoscopio iluminado para ver lo que está haciendo.
Todo tiene su lugar y nuestro método de ensamblaje a mano solo es adecuado para micros muy
pequeños y eventualmente necesitará "aprender un lenguaje de alto nivel". El PIC12F629 tiene más de
1,000 ubicaciones para el código y esto equivale a más de 20 páginas cuando se imprime, por lo que se
trata del límite para hacer las cosas a mano.
Pero nuestro impulso es mostrar cuánto se puede hacer con los dispositivos más simples del mercado, al
menor costo.
Cualquiera puede mostrarle alta tecnología a un alto precio, pero no es aquí donde comienza y no es
donde adquiere entusiasmo.
Te proporcionamos las cosas para que comiences. Esa es la diferencia.

El programa
El programa se inicia en un bucle para detectar cuándo se interrumpe el detector IR izquierdo. Luego
pasa a un segundo bucle para detectar cuándo se interrumpe el detector IR correcto. Cuando se interrumpe
un detector de IR, la salida se pone en ALTO. La sensibilidad se puede ajustar moviendo el LED IR más
cerca del receptor. También se incluye una olla de 10k para ajustar la sensibilidad.
Cuando se interrumpe el detector IR derecho, se incrementa un "archivo de conteo" y se produce una
salida de 10 ms a través de un transistor PNP. Una 100R en la salida protege al transistor de cualquier
cortocircuito.
Un LED indica que la salida ha sido enviada.
El proyecto mantiene una cuenta del número de "ciclos" y esto se puede "leer" presionando el interruptor.
El conteo se registra al escuchar los tonos bajos para representar los 10 y los tonos altos para
representar los 1.

Aquí están los archivos que necesitará:


BeeCounter.asm
BeeCounter-asm.txt
BeeCounter.hex

;**************************************************************
;; Contador de abejas .asm
;**************************************************************
; El IR izquierdo detecta y luego aumenta la cuenta en la detección del lado
derecho
; 12F629.asm
; 8-1-2012

lista p = 12F629
radix dec
incluye "p12f629.inc"

errorlevel -302; No te quejes de los registros BANK 1

__CONFIG _MCLRE_OFF & _CP_OFF


& _WDT_OFF & _INTRC_OSC_NOCLKOUT; osc. Interno

temp1 equ 20h;


temp2 equ 21h;
temp3 equ 22h;
unidades equivalen a 23h;
decenas igual 24h;
del_x equ 28h
del_y equ 29h
tempunits equ 2Ah
temptens equ 2Bh

; ************************************************** ***************
; Es igual a
; ************************************************** ***************
estado equ 0x03
rp1 equ 0x06
rp0 equ 0x05
GPIO equ 0x05

status equ 03h


option_reg equ 81h

; bits en GPIO

pin7 equ 0; GP0 dejó detector de IR - entrada


pin6 equ 1; GP1 baja para producir señal ALTA - salida
pin5 equ 2; la entrada GP2 Sw envía el conteo a la señal acústica - entrada
pin4 equ 3; detector de IR derecho GP3 - entrada
pin3 equ 4; señal acústica GP4 - salida
pin2 equ 5, GP5

bits

rp0 equ 5; bit 5 del registro de estado

; ************************************************** ***************
; Inicio del programa
; ************************************************** ***************
Iniciar org 0x00; restablecer dirección de vector
nop
nop
nop
nop; NOP para pasar la dirección de reinicio del vector
nop
nop; configurar para permitir el conteo desde un oscilador externo

Estado bsf de configuración, rp0; Banco 1


movlw b'11001001 '; Establecer TRIS
movwf trisio
estado bcf, rp0; banco 0
movlw 07h; Configurar W para desactivar los puertos del comparador
movwf CMCON; debe colocarse en el banco 0
clrf GPIO; Clear GPIO de basura
banderas de clrf
unidades de clrf; cuenta de inicialización = 0
clrf decenas; cuenta inicialización = 0
goto principal

; ************************************************** ***************
; * Retrasos
; ************************************************** ***************
_10mS movlw 0Ah
movwf temp2
D_a nop
decfsz temp1,1
goto D_a
decfsz temp2,1
goto D_a
retlw 00

; Delay 0.25 sec

D_250mS movlw 01h


movwf temp3
DelX decfsz temp1,1
Ir a DelX
decfsz temp2,1
Ir a DelX
decfsz temp3,1
Ir a DelX
retlw 00

; ****************************
; * Sub-rutinas *
; ****************************

; la salida produce pitidos largos por decenas


; y pitidos cortos para que las unidades signifiquen conteo.

unidades movf de salida, 0


tempunits movwf
movf decenas, 0
tentaciones movwf
temptens movf, 1; comprobar si hay cero
btfsc status, 2; cero indicador Se establecerá si el archivo es cero
goto $ + 4
Llama a Tensbe
tentaciones decfsz, 1
goto $ -2
llamada D_250mS
llamada D_250mS
llamada D_250mS
llamada D_250mS
tempunits movf, 1; comprobar si hay cero
btfsc status, 2; cero indicador Se establecerá si el archivo es cero
retlw 00
llamar a unidades beep
tempunits decfsz, 1
goto $ -2
retlw 00

; produce un "pitido" para indicar que la abeja se ha movido y sale a


la salida.

pitido corto
movlw 0ffh
movwf del_y
movlw .45
movwf del_x
nop
decfsz del_x, 1
goto $ -2
movlw b'00010000 '
xorwf gpio, 1; alternar GP4
decfsz del_y, 1
goto $ -8
llamada D_250mS
retlw 00

;bip corto para indicar unidades

unidades beep
movlw 80h
movwf del_y
movlw .45
movwf del_x
nop
decfsz del_x, 1
goto $ -2
movlw b'00010000'
xorwf gpio, 1; alternar GP4
decfsz del_y, 1
goto $ -8
llamada D_250mS
llamada D_250mS
retlw 00

bip de la izquierda
movlw 80h
movwf del_y
movlw .45
movwf del_x
nop
decfsz del_x, 1
goto $ -2
movlw b'00010000 '
xorwf gpio, 1; alternar GP4
decfsz del_y, 1
goto $ -8
llamada D_250mS
llamada D_250mS
retlw 00

; bip largo para indicar decenas

Tensión
movlw 0ffh
movwf del_y
movlw 0ffh
movwf del_x
nop
decfsz del_x, 1
goto $ -2
movlw b'00010000 '
xorwf gpio, 1; alternar GP4
decfsz del_y, 1
goto $ -8
llamada D_250mS
llamada D_250mS
retlw 00

beep derecho
movlw 0ffh
movwf del_y
movlw 0ffh
movwf del_x
nop
decfsz del_x, 1
goto $ -2
movlw b'00010000 '
xorwf gpio, 1; alternar GP4
decfsz del_y, 1
goto $ -8
llamada D_250mS
llamada D_250mS
retlw 00

Hasta unidades incf, 1


movlw 0Ah; poner 10 en w
Unidades xorwf, 0; compara el archivo de unidades con 10
btfss status, 2; se establecerá un indicador de cero si las unidades
son 10
retlw 00
unidades de clrf
dec dec, 1
movlw 0Ah; poner 10 en w
xorwf tens, 0; compara unidades de archivo con 10
btfss status, 2; se establecerá un indicador de cero si las decenas
son 10
retlw 00
diez decenas
retlw 00

; ************************************************** ***************
;* Principal *
; ************************************************** ***************
Estado bsf principal, rp0; Banco 1
movlw b'11101101 '; conmutadores y receptores IR GP0 GP2 GP3
movwf trisio
estado bcf, rp0; banco 0
bsf GPIO, 1; apagar el LED de salida

llamada D_250mS
btfss GPIO, 2; la entrada será BAJA cuando se pulsa sw
salida de llamada
nop
btfss GPIO, 0; la entrada será ALTA cuando se detecte una abeja
goto $ -5; el IR izquierdo no detecta
llamar a la izquierda
llamada D_250mS
btfss GPIO, 2; la entrada será BAJA cuando se pulsa sw
salida de llamada
nop
btfss GPIO, 3; la entrada será ALTA cuando se detecte una abeja
goto $ -5; no se detecta el IR derecho
llamada, cuenta de incremento
llamar a la derecha
bcf gpio, 1
llamar a _10mS
bsf gpio, 1
goto $ -18

fin

Lista de partes Contador de abejas


Costo: au $ 20 .00 más gastos de envío
Kits están disponibles

2 - resistencias 100R SM
2 - resistencias 330R SM
2 - resistencias 1k SM
3 - resistencias 2k2 SM
2 - resistencias 4k7 SM
1 - resistencia de 10k SM

2 - Mini potes de ajuste 10k


1 - condensador de 100n SM
2 - 1u electrolíticos SM
2 - 10u electrolíticos SM

1 - transistor BC847 SM
1 - transistor BC857 SM
1 - 1N4004 diodo SM
2 - LEDs IR (suministrados en el kit)
2 - Transistores IR (suministrados en kit)

1 - LED rojo de 3mm


1 - SPDT mini interruptor deslizante
1 - mini interruptor táctil
1 - conector de 8 pines IC
1 - chip PIC12F629 (rutina de abeja)
1 - diafragma piezoeléctrico
1 - 10mH choke
5 - pasadores de máquina para la programación en circuito
1 - 4 porta pilas AAA
1 - 30 cm de alambre esmaltado fino
Cable de malla fina de 3 m
20cm de soldadura muy fina
1 - Tablero de PC Experimentador

01/09/2012
BEE COUNTER
Home

Kits are available for this project from


Talking Electronics for $20.00 plus postage.
Plus you will need:
6pin to 5pin adapter @ $2.50

You will also need:


PIC2 USB Burner (MPASM and MPLAB come with PIC2) and it includes USB lead

PIC12F629 Data Sheet (.pdf 4,926KB)


Instruction Set for PIC12F629
blank12F629.asm template
PIC12F629.inc

See more projects using micros:


Elektor,EPE,Silicon Chip

Notepad2.zip     Notepad2.exe


Library of Sub-routines "Cut and Paste"
Library of routines:   A-E   E-P    P-Z

Here are the files you will need:


BeeCounter.asm
BeeCounter-asm.txt
BeeCounter.hex

The design for the project comes from a University research scientist.
His requirement was to count the movement of a bee in a tube.
Two sets of Infrared photo-detectors were set up so movement from one end of the tube could be
counted when the bee returns to the opposite end of the tube. It's a simple flip-flop or toggle requirement.

Bee Counter on experimenter board


Bee Counter

IR Receiver and IR LED (Transmitter)

INSTRUCTIONS FOR USE


Set-up the two IR detectors and two IR LEDs (transmitters) so the circuit produces a low-pitched beep
when the left detector is interrupted and a high-pitched beep when the right detector is interrupted.

The CIRCUIT
The circuit is very simple. It is just 2 IR LEDs, two IR receivers a switch to listen to the count (low-tone
beeps represent 10's and high-pitched beeps represent 1's) and a piezo diaphragm. All the work is done by
the micro. It is powered by 4 AAA cells.
CONSTRUCTION
You can build the circuit on matrix board.
The kit of components comes with all the parts you need to get the project working, including a pre-
programmed chip and the matrix board.
To modify the program you will need a PICkit-2 programmer and this comes with 2 CD's containing all the
software needed for In-Circuit Programming.
You will also need a lead (comes with PICkit-2) to connect the programmer to your lap top via the USB
port and an adapter we call 6pin to 5 pin Adapter to connect the PICkit-2 to your project.

PROGRAMMING THE CHIP


The kit comes with a pre-programmed PIC chip but if you want to program your own chip or modify the
program, the .hex file is available as well as the assembly file, so you can see how the program has been
written and view the comments for each line of code.
The PIC12F629 is one of the smallest micros in the range but you will be surprised how much can be
achieved with such a tiny micro.
The program contains sub-routines to produce delays, sequences on the display and both read and write
EEPROM; jobs that require accurate code - including a special sequence - called a handshaking sequence
that prevents the EEPROM being written due to glitches.
Even a program as simple as this is not easy to put together and to assist in this area, we have provided
a whole raft of support material.
Not only do we provide a number of programs with full documentation but our approach to programming
is simple.
It involves a method of "copy and paste" whereby sub-routines are taken from previously written code and
copied into your program. Any modifications are made in very small steps so that each can be tested before
adding more code.
This is exactly how we produce a complex project. Each step is written and tested before adding the next
step.
This saves a lot of frustration as it is very easy to add a line of code that is incorrect and get an
unsuspected result.
If you follow our suggestions you will buy a programmer ("burner") called a PICkit-2 if you are using a
laptop. It is the cheapest and best on the market and comes with a USB cable and 2 CD's containing the
programs needed to "burn" the chip. If you are using a desk-top and/or tower with a serial port, you can use
a cheaper programmer called MultiChip Programmer from Talking Electronics. You will also need
NotePad2 to write your .asm program. This can be downloaded from Talking Electronics website. You will
use BeeCounter.asm or BeeCounter-asm.txt as a basis and it is best to change only a few lines at a time to
see what effect is created. You will also need a 6 pin to 5 pin connector that fits between the burner and the
project. This is also available on Talking Electronics website.
As we said before, this project is for medium-to-advanced programmers as it is very compact and does
not have in-circuit programming pins.
To be able to modify the chip you will need a programming socket and this can be obtained from one of
our other projects that contains the 5 pins for in-circuit programming. Or you can build a programming socket
by adding a socket to a surface-mount PC board and solder 5 pins to one edge and connect the socket to
the pins.
You can then put the chip into the socket and program it.

PROGRAMMING LANGUAGE
There are a number of kits, programs and courses on the market that claim and suggest they teach PIC
Programming.
Most of these modules and courses use a PIC microcontroller as the chip carrying out the processes, but
the actual programming is done by a proprietary language invented by the designer of the course.
Although these courses are wonderful to get you into "Programming Microcontrollers" they do not use any
of the terms or codes that apply to the PIC microcontroller family.
All our projects use the 33 instructions that come with the PIC Microcontroller and these are very easy to
learn.
We use the full capability of the micro and our pre-programmed chip is less than the cost of doing it any
other way.
In addition, anything designed via our method can be instantly transferred to a PIC die and mass
produced. And we use all the input pins and all the memory of the chip. The other approaches use less than
25% of the capability of the memory and one of the pins is not available.
In fact it would be difficult to reproduce this project via any of the opposition methods. It would require a
larger chip and more expense.
You can use our method or the opposition. Just be aware that the two are not interchangeable.
Ours is classified as the lowest "form" (level) of programming - commonly called machine code - invented
in the early days of microprocessors - and now called mnemonic programming as each line of code is made
up of letters of a set of words. The opposition uses a higher level language where one instruction can carry
out an operation similar to a sub-routine.
But you have to learn the "higher level language" in order to create a program. And this requires a fair
amount of skill and capability.
It sounds great and it is a good idea. But if you want to learn PIC programming, it does not assist you. It is
"a step removed" from learning PIC language. The other disadvantage of the opposition is the "overhead."
The 1,000 spaces allocated for your program is filled with pre-written sub-routines. You may require only 10
of these sub-routines but ALL of them are loaded in the memory space. And they take up all the memory.
You have no room for your own program.
To get around this the opposition uses the 128 bytes in EEPROM to deliver instructions on how to apply
the sub-routines. This provides about 30 powerful instructions using their language called BASIC (or a similar
language).
It's a bit like selling a diary filled with all the paragraphs you need to express yourself, and leaving a few
blank pages at the back for you to write single lines such as: see page 24, paragraph 7, see page 63
paragraph 4, to create your diary entries.
It depends on how much you want to be in charge of writing a program. Using our method is like writing
your own auto-biography. Using the opposition is like getting a "ghost writer."
When using a higher level language to create a program, you have absolutely no idea how the code is
generated for the micro.
In some of the developmental kits, the code is "locked away" and you are NEVER able to access it.
Everything runs smoothly until a fault appears. With our method you can see the code. With the other
methods, you cannot see the code - it's like doing key-hole surgery without the advantage of an illuminated
endoscope to see what you are doing.
Everything has its place and our method of hand-assembly is only suitable for very small micros and you
will eventually need to "learn a high level language." The PIC12F629 has over 1,000 locations for code and
this equates to more than 20 pages when printed, so this is about the limit to doing things by hand.
But our drive is to show how much can be done with the simplest devices on the market, at the lowest
cost.
Anyone can show you high-technology at a high price but this is not where you start and this is not where
you get enthusiasm.
We provide the things to get you started. That's the difference.

The PROGRAM
The program starts in a loop to detect when the left IR detector is interrupted. It then goes to a second
loop to detect when the right IR detector is interrupted. When an IR detector is interrupted, the output goes
HIGH. The sensitivity can be adjusted by moving the IR LED closer to the receiver. A 10k pot is also included
to adjust the sensitivity.
When the right IR detector is interrupted, a "count file" is incremented and a 10mS output is produced via
a PNP transistor. A 100R on the output protects the transistor from any short-circuits.
A LED indicates the output has been sent.
The project keeps a tally of the number of "cycles" and this can be "read" by pressing the switch.
The count is recorded by listening to low-pitched beeps to represent 10's and high-pitched beeps to
represent 1's.

Here are the files you will need:


BeeCounter.asm
BeeCounter-asm.txt
BeeCounter.hex

;*************************************************************
; Bee Counter.asm
;*************************************************************
;Left IR detects then increments count on right-side detection
; 12F629.asm
; 8-1-2012

list p=12F629
radix dec
include "p12f629.inc"

errorlevel -302 ; Don't complain about BANK 1 registers

__CONFIG _MCLRE_OFF & _CP_OFF


& _WDT_OFF & _INTRC_OSC_NOCLKOUT ;Internal osc.
temp1 equ 20h ;
temp2 equ 21h ;
temp3 equ 22h ;
units equ 23h ;
tens equ 24h ;
del_x equ 28h
del_y equ 29h
tempunits equ 2Ah
temptens equ 2Bh

;****************************************************************
;Equates
;****************************************************************
status equ 0x03
rp1 equ 0x06
rp0 equ 0x05
GPIO equ 0x05

status equ 03h


option_reg equ 81h

; bits on GPIO
pin7 equ 0 ;GP0 left IR detector - input
pin6 equ 1 ;GP1 goes low to produce HIGH signal - output
pin5 equ 2 ;GP2 Sw input sends count to beeper - input
pin4 equ 3 ;GP3 right IR detector - input
pin3 equ 4 ;GP4 beeper - output
pin2 equ 5 ;GP5

;bits
rp0 equ 5 ;bit 5 of the status register

;****************************************************************
;Beginning of program
;****************************************************************
Start org 0x00 ;reset vector address
nop
nop
nop
nop ;NOPs to get past reset vector address
nop
nop ;set up to allow counting from external oscillator

SetUp bsf status, rp0 ;Bank 1


movlw b'11001001' ;Set TRIS
movwf TRISIO
bcf status, rp0 ;bank 0
movlw 07h ;Set up W to turn off Comparator ports
movwf CMCON ;must be placed in bank 0
clrf GPIO ;Clear GPIO of junk
clrf flags
clrf units ;initialise count = 0
clrf tens ;initialise count = 0
goto Main

;****************************************************************
;* Delays
;****************************************************************
_10mS movlw 0Ah
movwf temp2
D_a nop
decfsz temp1,1
goto D_a
decfsz temp2,1
goto D_a
retlw 00
;Delay 0.25 sec

D_250mS movlw 01h


movwf temp3
DelX decfsz temp1,1
goto DelX
decfsz temp2,1
goto DelX
decfsz temp3,1
goto DelX
retlw 00

;****************************
;* Sub-routines *
;****************************
;output produces long beeps for tens
;and short beeps for units to signify count.

output movf units,0


movwf tempunits
movf tens,0
movwf temptens
movf temptens,1 ;check for zero
btfsc status,2 ;zero flag Will be set if file is zero
goto $+4
call tensbeep
decfsz temptens,1
goto $-2
call D_250mS
call D_250mS
call D_250mS
call D_250mS
movf tempunits,1 ;check for zero
btfsc status,2 ;zero flag Will be set if file is zero
retlw 00
call unitsbeep
decfsz tempunits,1
goto $-2
retlw 00

;produces "beep" to indicate bee has moved and outputs to output.

shortbeep
movlw 0ffh
movwf del_y
movlw .45
movwf del_x
nop
decfsz del_x,1
goto $-2
movlw b'00010000'
xorwf gpio,1 ;toggle GP4
decfsz del_y,1
goto $-8
call D_250mS
retlw 00

;short beep to indicate units

unitsbeep
movlw 80h
movwf del_y
movlw .45
movwf del_x
nop
decfsz del_x,1
goto $-2
movlw b'00010000'
xorwf gpio,1 ;toggle GP4
decfsz del_y,1
goto $-8
call D_250mS
call D_250mS
retlw 00

leftbeep
movlw 80h
movwf del_y
movlw .45
movwf del_x
nop
decfsz del_x,1
goto $-2
movlw b'00010000'
xorwf gpio,1 ;toggle GP4
decfsz del_y,1
goto $-8
call D_250mS
call D_250mS
retlw 00

;long beep to indicate tens

tensbeep
movlw 0ffh
movwf del_y
movlw 0ffh
movwf del_x
nop
decfsz del_x,1
goto $-2
movlw b'00010000'
xorwf gpio,1 ;toggle GP4
decfsz del_y,1
goto $-8
call D_250mS
call D_250mS
retlw 00

rightbeep
movlw 0ffh
movwf del_y
movlw 0ffh
movwf del_x
nop
decfsz del_x,1
goto $-2
movlw b'00010000'
xorwf gpio,1 ;toggle GP4
decfsz del_y,1
goto $-8
call D_250mS
call D_250mS
retlw 00

Up incf units,1
movlw 0Ah ;put 10 into w
xorwf units,0 ;compare units file with 10
btfss status,2 ;zero flag will be set if units is 10
retlw 00
clrf units
incf tens,1
movlw 0Ah ;put 10 into w
xorwf tens,0 ;compare units file with 10
btfss status,2 ;zero flag will be set if tens is 10
retlw 00
clrf tens
retlw 00

;****************************************************************
;* Main *
;****************************************************************
Main bsf status, rp0 ;Bank 1
movlw b'11101101' ;switch and IR receivers GP0 GP2 GP3
movwf TRISIO
bcf status, rp0 ;bank 0
bsf GPIO,1 ;turn off output LED

call D_250mS
btfss GPIO,2 ;input will be LOW when sw pressed
call output
nop
btfss GPIO,0 ;input will be HIGH when bee detected
goto $-5 ;Left IR not detecting
call leftbeep
call D_250mS
btfss GPIO,2 ;input will be LOW when sw pressed
call output
nop
btfss GPIO,3 ;input will be HIGH when bee detected
goto $-5 ;right IR not detecting
call Up ;increment count
call rightbeep
bcf gpio,1
call _10mS
bsf gpio,1
goto $-18

end

Bee Counter Parts List


Cost: au$20.00 plus postage
Kits are available

2- 100R SM resistors
2- 330R SM resistors
2- 1k SM resistors
3- 2k2 SM resistors
2- 4k7 SM resistors
1- 10k SM resistor

2 - 10k mini trim pots

1 - 100n SM capacitor
2 - 1u SM electrolytics
2 - 10u SM electrolytics

1- BC847 SM transistor
1- BC857 SM transistor
1- 1N4004 SM diode
2- IR LEDs (supplied in kit)
2- IR transistors (supplied in kit)

1- 3mm red LED


1- SPDT mini slide switch
1- mini tactile switch
1- 8 pin IC socket
1 - PIC12F629 chip (Bee routine)
1 - piezo diaphragm
1 - 10mH choke
5 - machine pins for in-circuit-programming
1 - 4 AAA cell battery holder
1 - 30cm fine enamelled wire
3m fine screened lead
20cm very fine solder
1 - Experimenter PC board

9/1/2012

Вам также может понравиться