Está en la página 1de 51

Control Inalmbrico de un brazo de

Robot a travs de un RF pic

Resumen
La presente prctica tiene como objetivo implementar un control inalmbrico por
RF utilizando el Flash Starter Kit de Microchip de manera que se obtenga
movilidad de un brazo de robot en el cual se sustituir el mdulo que contiene los
botones de control y programar un algoritmo de control para los cinco grados de
libertad del brazo mediante el transmisor del RFPIC12f675.
Posteriormente se disear y programar un algoritmo para recibir la seal
de control enviada a fin de implementar una interfase lgica y de potencia para
enviar la seal de control recibida.

Dispositivos y lista de equipo


RFPIC flash starter kit
Fuente de poder GW Dual Tracking Modelo: GPC-3030D.
Multmetro Fluke 175 Series 170.
Robotic Arm Trainer de OwiKit 007.
PIC16F676

Resistencias de 100, 330 y 1k


TIP111 y TIP115

CD4515B

Marco Terico
Espectro RF
Muchos productos de consumo e industriales hacen uso de la energa electromagntica.
Un tipo de energa electromagntica que est aumentando en importancia a nivel mundial
es la energa de radiofrecuencia (RF), incluyendo ondas de radio y microondas, las cuales
son usadas para proveer comunicaciones y radiodifusin y otros servicios. Las ondas de
radio y microondas son formas de energa electromagntica que son comnmente
descritas por el trmino de radiofrecuencia o RF. Las emisiones de RF y los fenmenos
asociados pueden ser discutidos en trminos de energa, radiacin o campos. La
radiacin es definida como la propagacin de energa a travs del espacio en forma de
ondas o partculas. La radiacin electromagntica puede ser descrita como ondas de
energa elctrica y magntica movindose conjuntamente a travs del espacio. Est
ondas son generadas por el movimiento de cargas elctricas tales como en un objeto
conductor metlico o antena por ejemplo, el movimiento alternante de cargas en una
antena usado para la difusin de radio y televisin o en la antena de una estacin de base
celular generan ondas electromagnticas que son radiadas desde el transmisor y que son
recibidas por una antena tal como una antena de techo, antena de radio de automvil o
una antena de telfono celular. El trmino campo magntico es usado para indicar la
presencia de energa electromagntica en un lugar dado. El campo RF puede ser descrito
en trminos de potencia de campo elctrico y/o magntico en un lugar dado.

Figura 1. Caractersticas de una onda

El trmino radiofrecuencia, tambin denominado espectro de radiofrecuencia o RF,


se aplica a la porcin del espectro electromagntico en el que se pueden generar ondas
electromagnticas aplicando corriente alterna a una antena. Dichas frecuencias se
pueden dividir en ELF, SLF, ULF, VLF, LF, MF, HF, VHF, UHF, SHF y EHF.
Segn las especificaciones del fabricante se puede decir que en esta prctica se
usaron frecuencias UHF.
Nombre

Abreviatura
inglesa

Banda
ITU

Frecuencias

Longitud de onda

Extra baja frecuencia Extremely low


frequency
Super baja frecuencia Super low frequency

ELF

Inferior a 3
Hz
3-30 Hz

> 100.000 km

SLF

30-300 Hz

Ultra baja frecuencia Ultra low frequency

ULF

3003000 Hz

Muy baja frecuencia Very low frequency

VLF

330 kHz

Baja frecuencia Low frequency


Media frecuencia Medium frequency

LF
MF

5
6

10 km 1 km
1 km 100 m

Alta frecuencia High frequency


Muy alta frecuencia Very high frequency

HF
VHF

7
8

30300 kHz
3003000
kHz
330 MHz
30300 MHz

Ultra alta frecuencia Ultra high frequency

UHF

1 m 100 mm

Super alta frecuencia Super high frequency

SHF

10

3003000
MHz
3-30 GHz

Extra alta frecuencia Extremely high


frequency

EHF

11

30-300 GHz

10 mm 1 mm

Por encima
de los 300
GHz

< 1 mm

100.000 km
10.000 km
10.000 km
1000 km
1000 km 100
km
100 km 10 km

100 m 10 m
10 m 1 m

100 mm 10 mm

Tabla 1. Espectro de RF.

Robotic Arm Trainer


Dado que el objetivo de esta prctica era implementar el control inalmbrico del Brazo
Mecnico (Robotic Arm Trainer), por Radio Frecuencia, utilizando el rfPIC Development
Kit 1 de Microchip, lo primero que se requiri fue familiarizarse con el control de los
movimientos de dicho brazo.

Figura 2. Robotic Arm Trainer Kit.

El OWI-007 ROBOTIC ARM TRAINER es un kit que muestra los principios bsicos
de mocin y sensado robtico. El kit incluye un control de 5 interruptores conectado al
brazo mediante un cable de 8 hilos.
Como primer paso se desconect el control de la parte trasera y se retir la tapa
de la base inferior, con lo que qued al descubierto el compartimiento de las bateras. En
la figura siguiente se puede observar que la alimentacin proporcionada por las bateras
se conecta con una terminal de 8 pines de color blanco (parte superior) que sirve para
conectar el control.

Figura 3 .Compartimiento de Bateras en la base del Brazo.

Visto de frente (con la base apoyada) los pines corresponden a 5 motores, 2 niveles de
voltaje y 1 tierra como se muestra en la siguiente tabla:

Figura 4. Conector de 8 pines

PIN
1
2
3
4
5
6
7
8

Control o Voltaje
- 3Vcc (con Pilas)
Motor de los Dedos
Motor del Codo
Motor de la Base
Todos los Motores (Comn 0V)
Motor del Hombro
Motor de la Mueca
+ 3Vcc (con Pilas)
Tabla 2. Relacin de los Pines y los Motores del Brazo de Robot.

Los voltajes en las terminales 1 y 8 slo existen en presencia de las 4 bateras.


stas a su vez son necesarias cuando el movimiento del robot es dirigido por el control.
Sin embargo en el experimento las bateras fueron removidas y para suministrar la
potencia se conectaron las terminales de la fuente de voltaje Leader regulada a +3 y -3 a
travs de un arreglo de transistores.

Diagramas Esquemticos

Teclado
TX

RX

Control

Etapa de
potencia

Figura 5. Diagrama a bloques del sistema para llevar a cabo el control inalmbrico del brazo.

Para poder lograr el control de los motores implementamos un switch electrnico


de potencia, usando transistores TIP 111 y TIP 115. Cada par de transistores se usa para
controlar un motor.

Figura 6. Conexin de 1 Motor.

El funcionamiento del circuito es el siguiente: Como un demultiplexor cambia a la


salida solamente un bit por combinacin (en este caso hace 0 mientras que los dems
siguen en 1), en el circuito anterior no se pueden encender los optoacopladores al
mismo tiempo sino uno a la vez. En la parte izquierda, cuando a la salida del CD4515B
es 1 (5 volts) no hay diferencia de potencial y entonces no hay corriente por el
optoacoplador por lo que se encuentra apagada esa parte, cuando llega 0 del
demultiplexor existe diferencia de voltaje y entonces hay corriente por el LED lo cual
enciende al optotransistor y entonces existe una corriente de colector a emisor, al estar
conectado el emisor del optoacoplador a la base del TIP111, existe una corriente en la
base de ste ltimo y entonces lo enciende generando una corriente que va de colector a

emisor del TIP por ser npn y entonces existe corriente en el motor la cual genera un
voltaje en l con polaridad + - de arriba hacia abajo, haciendo girar al motor en un sentido.
Cuando la parte positiva es la que recibe el 0 por parte del demultiplexor, hay una
corriente en el LED lo cual enciende al optotransistor y genera una corriente de colector a
emisor del optotransistor, la cual a su vez genera una corriente en la base del TIP115 por
estar conectado a ella, al haber una corriente de base, sta logra que se encienda el TIP
generando corriente de emisor a colector por ser pnp y entonces hay una corriente a
travs del motor polarizndolo con un voltaje - + visto de arriba hacia abajo, entonces al
tener polaridad contraria a la vista cuando se enciende la parte izquierda, el motor girar
en direccin contraria a la primera.
El mismo diagrama se repite otras 4 veces, una vez por cada motor, de modo que
generando las seales de control adecuadas el brazo puede moverse en los 5 grados de
libertad.
Como podr verse si ambas seales de control se activan al mismo tiempo, se
producir un corto circuito en las terminales del emisor. Del mismo modo, dado que la
fuente de alimentacin para todos los motores sera la misma, la corriente disminuir en
cada motor que se active por eso no es recomendable que se active ms de un motor a la
vez.

Funcionamiento del Circuito.


Bsicamente una vez enviada la informacin mediante por RF, la informacin que se
obtiene de las salidas del Pic del Receptor son codificadas para tener una salida de 16
bits, lo cual hace posible que mediante el cambio de 1 slo bit, se pueda activar el motor
del brazo robtico correspondiente.
En la etapa de transmisin, se tienen dos controles, mediante los cuales se puede
seleccionar el movimiento que se espera realice el brazo y otra para enviar la seal de
activacin/desactivacin. Esto se hace mediante una modulacin ASK a 315 MHz, que es
el rango en el cual trabaja el transmisor y el receptor del RF Pic.

La etapa de recepcin, simplemente recibe la seal enviada por el transmisor, la


remodula y entrega a la salida un cdigo de 4 bits, o en su defecto de 12 bits mediante un
arreglo matricial. Es precisamente de esta salida que entrega el receptor de donde se
toma la informacin para controlar los cinco grados de libertad del brazo robtico.
El mdulo PICkit TM FLASH Starter kit, cuenta con expansion Header (J3), en el
cual se puede introducir el mdulo de transmisin: rfPIC 12F675. Se remueve el
PIC16F67, tal como se indica en la siguiente imagen, y por medio del cable USB y con el
programa de transmisin (que ms adelante se explicar) se programa este mdulo
transmisor.

rfPIC PIC 12F675


El mdulo rfPIC 12f675 se muestra en la siguiente imagen.

Consta de un pic soldado, pines de conexin, dos potencimetros GP0 y GP1, y dos
botones GP3 y GP4. Adems contiene un jumper para poder seleccionar alimentacin del
pickit o alimentacin de la bateria que se encuentra en la parte posterior.
A continuacin se muestra el siguiente diagrama esquemtico para ste ltimo mdulo:

A continuacin se muestra el siguiente programa que fue modificado para logar lo


siguiente:
Por medio de GP3 se envi palabras binarias que en el receptor se recibiran como
cdigo para selector de movimiento del brazo robot. Al no presionar el botn PB3 se envi
esta informacin, y al momento de presionarlo se dejara de transmitir. Si se presionaba
PB4, se enviara un bit de seleccin on/off para cada motor. Este programa se muestra a

continuacin, y se documenta por medio de recuadros que indican las partes modificadas
y agregadas para poder lograr la transmisin tal como se explic.

Algoritmos de TX y RX.
Transmisin.
;---------------------------------------------------------------------;
Software License Agreement
;
; The software supplied herewith by Microchip Technology Incorporated
; (the "Company") for its PICmicro Microcontroller is intended and
; supplied to you, the Companys customer, for use solely and
; exclusively on Microchip PICmicro Microcontroller products.
;
; The software is owned by the Company and/or its supplier, and is
; protected under applicable copyright laws. All rights are reserved.
; Any use in violation of the foregoing restrictions may subject the
; user to criminal sanctions under applicable laws, as well as to
; civil liability for the breach of the terms and conditions of this
; license.
;
; THIS SOFTWARE IS PROVIDED IN AN "AS IS" CONDITION. NO WARRANTIES,
; WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
; TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
; IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
; CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
;
;---------------------------------------------------------------------;
; Filename:
xmit.asm
; Date:
April 25, 2003
; File Version:
1.0
; Assembled using: MPASM 03.30 Released
; Author:
Steven Bible
; Company:
Microchip Technology Inc.
;---------------------------------------------------------------------; Files required:
p12f675.inc
;---------------------------------------------------------------------;
; Program Description
;
; This program demonstrates simple command & control and analog
; application demonstrations. To see each demonstration the user must
; load the appropriate receiver code examples:
;
; rcvr_demo.asm
;
; When a push button on the transmitter module is depressed, the
; corresponding LED is lit on the PICkit(tm) 1 FLASH Starter Kit.
; Pressing transmitter module push button GP3 lights LED D0 on the
; PICkit(tm) 1. Pressing push button GP4 lights LED D1.
;
; rcvr_analog_display.asm
;
; Pressing transmitter module push button GP3 lights LEDs D0-D7 on
; the PICkit(tm) 1 with the upper 8-bit value read from the

10

; transmitter module 10-bit A/D channel 0 connected to potentiometer


; GP0. Pressing push button GP4 lights LEDs D0-D7 with the upper
; 8-bit value read from A/D channel 1 connected to potentiometer GP1.
;
; The protocol is a simplified KeeLoq(r) protocol compatible with
; the HCS101 fixed code products. This receive code was adapted from
; Microchip Technology application note AN740.
;
; The 10-bit analog value is placed into the 16-bit counter field of
; the simplified KeeLoq(r) protocol.
;
;---------------------------------------------------------------------list
p=12f675
; list directive to define processor
#include <p12f675.inc> ; processor specific variable definitions
errorlevel -302

; suppress message 302 from list file

__CONFIG _CPD_OFF & _CP_OFF & _BODEN_OFF & _MCLRE_OFF & _PWRTE_OFF & _WDT_OFF &
_INTRC_OSC_NOCLKOUT
;---------------------------------------------------------------------; Variables (Section 2.2 Data Memory Organization)
;---------------------------------------------------------------------;
;
;
;

Data Memory Organization (Section 2.2)


Register locations 0x20 to 0x5F (64 bytes) are General Purpose
registers, implemented as static RAM and are mapped across both
banks.

cblock 0x20
w_temp
status_temp

; used for context saving


; used for context saving

TEMP

; General Purpose Temporary register

CSR0
CSR1
CSR2
CSR3
CSR4
CSR5
CSR6
CSR7
CSR8

; TX buffer shift register

Estos son los Registros que


utiliza el programa para
enviarlos, los cuales el receptor
recibe y enva al Pic de manera
serial.

Count
Count2
BitCount
TimeHi
TimeLo
FuncBits

; Function Bits

endc
;---------------------------------------------------------------------; Defines
;---------------------------------------------------------------------;
;
;
;
;
;
;
;

Set up GPIO Port (Section 3.0)


Function of GPIO pins depend on:
Configuration Bits (CONFIG) (Section 9.1)
Weak Pull-up Register (WPU) (Section 3.2.1)
Interrupt-on-change GPIO Register (IOCB) (Section 3.2.2)
Option Register (OPTION_REG) (Register 4-1)
TIMER1 Control Register (T1CON) (Register 5-1)
Comparator Control Register (CMCON) (Section 6.0)

11

; A/D Control Register (ADCON0) (Section 7.0) (PIC12F675 Only)


#define
#define
#define
#define
#define
#define
;
;
;
;
;
;
;

POT0 GPIO, 0
POT1 GPIO, 1
TXD
GPIO, 2
PB3
GPIO, 3
PB4
GPIO, 4
RFENA GPIO, 5

; (Analog Input) Potentiometer GP0


; (Analog Input) Potentiometer GP1
; (Output) Transmit Data
; (Input Only) Push button switch GP3
; (Input) Push button switch GP4
; (Output) RF Enable

Define for TRISIO Register (Section 3.1)


GPIO is an 6-bit wide, bi-directional port. The corresponding data
direction register is TRISIO. Setting a TRISIO bit (= 1) will make
the corresponding GPIO pin and input. Clearing a TRISIO bit (= 0)
will make the corresponding GPIO pin an output. The exception is
GP3, which is input only and its TRIS bit will always read as a '1'.

; GPIO Pins = xx543210


#define GPTRIS B'00011011'
; delays/timings
#define TGUARD D'46'
#define PREAMB D'16'

; 46 X TE
; Preamble length = 16 pulses

;---------------------------------------------------------------------; Program Memory


;---------------------------------------------------------------------; Program Memory Organization (Section 2.1)
ORG

0x000

; RESET Vector

nop
; for ICD use
goto INITALIZE
; goto INITALIZE
ORG
0x004
; Interrupt Vector
movwf w_temp
; save W register
swapf STATUS, W
; swap status to be saved into W
bcf
STATUS, RP0
; ---- Select Bank 0 ----movwf status_temp
; save STATUS register
;---------------------------------------; Interrupt Service Routine (ISR)
;
; Description:
;
;---------------------------------------;
;
;
;
;
;
;
;
;

Interrupt-on-change (Section 3.2.2 and 9.4.3)


An input change on GPIO change sets the GPIF bit. The interrupt can
be enabled/disabled be setting/clearing the GPIE bit. Individual pins
are configured through the IOC register (see INITIALIZATION below).
Clear the IOC interrupt by:
a) Any read or write of GPIO. This will end the mismatch condition.
b) Clear the flag bit GPIF
movfw GPIO
bcf
INTCON, GPIF

; read GPIO

;---------------------------------------swapf
movwf
swapf
swapf

status_temp, W
; swap status_temp into W, sets bank to original state
STATUS
; restore STATUS register
w_temp, F
w_temp, W
; restore W register

12

retfie
;---------------------------------------------------------------------; Subroutine DATA_EEPROM_READ
;
; Description: To read an EEPROM data memory location, the address is
; written to the EEADR register and set control bit RD (EECON1<0>) to
; initiate a read. Data is available in the EEDATA register the next
; clock cycle.
;
; Constants: none
;
; Global Variables: none
;
; Initialization: W contains EEPROM address to be read
;
; Output: W contains EEPROM data
;
;---------------------------------------------------------------------DATA_EEPROM_READ
bsf

STATUS, RP0

; ---- Select Bank 1 -----

movwf EEADR
bsf
EECON1, RD
movf EEDATA, W

; move EEPROM address in W to EEADR


; initiate EEPROM read
; move data to W

bcf

; ---- Select Bank 0 -----

STATUS, RP0

return
;---------------------------------------------------------------------; Subroutine DATA_EEPROM_WRITE
;
; Description: To write an EEPROM data memory location, the address is
; written to the EEADR register, data to the EEDATA register, then
; execute a required sequence of instructions.
;
; CAUTION: Interrupts are disable during this subroutine
;
; Constants: none
;
; Global Variables: none
;
; Initialization: Address = EEADR, Data = EEDATA
;
; Output: none
;
;---------------------------------------------------------------------DATA_EEPROM_WRITE
bsf

STATUS, RP0

; ---- Select Bank 1 -----

bsf
bcf

EECON1, WREN
; EEPROM Write Enable: allow write cycles
INTCON, GIE
; disable global interrupts
; *** required sequence, do not alter ***
movlw 0x55
movwf EECON2
movlw 0xAA
movwf EECON2
bsf
EECON1, WR
; initiate EEPROM write
; *** end required sequence ***
bsf
INTCON, GIE
; enable global interrupts
bcf
EECON1, WREN
; EEPROM Write Enable: inhibit write cycles

13

bcf

STATUS, RP0

; ---- Select Bank 0 -----

return
;---------------------------------------------------------------------; Subroutine READ_ANALOG_AN0; READ_ANALOG_AN1
;
; Description: Read analog channel 0 (AN0) or 1 (AN1).
;
; Constants: none
;
; Global Variables: none
;
; Initialization: none
;
; Output: ADRESH and ADRESL contain 10-bit A/D result justified
; according to ADCON0, ADFM bit.
;
;---------------------------------------------------------------------READ_ANALOG_AN0
bcf

ADCON0, CHS1
; select analog channel AN0
bcf
ADCON0, CHS0

goto

READ_ANALOG

** Cuando no se presiona el
botn PB3, se llama esta funcin
para despus ir a
READ_ANALOG

READ_ANALOG_AN1
bcf
bcf

ADCON0, CHS1
ADCON0, CHS0

; select analog channel AN1

READ_ANALOG
bsf

ADCON0, ADON

; Turn on ADC module

; After selecting a new channel, allow for sufficent sample time.


; The amount of sample time depends on the charging time of the
; internal charge holding capacitor (Section 7.2).
movlw D'6'
movwf TEMP
decfsz TEMP, F
goto $-1
bsf

ADCON0, GO

btfsc ADCON0, GO
goto $-1
bcf

ADCON0, ADON

; At 4 MHz, a 22us delay


; (22us = 2us + 6 * 3us + 1us)

En esta funcin se
configura el modulo
ADC para lograr la
adquisicin por medio
del potencimetro G3.
El valor adquirido se
guarda en ADRESH

; start A/D conversion


; has A/D conversion completed?
; Turn off ADC module (consumes no operating current)

return
;---------------------------------------------------------------------; Subroutine: WaitxTE
;
; Description:
;
; Constants:
;
; Global Variables:
;
; Initialization: W x 400us length of delay required
;
; Output: Count, Count2 as decrementing counters
;

14

;---------------------------------------------------------------------WaitxTE
movwf Count2
waitxlp
movlw D'79'
movwf Count

; [1]
; [1]
; [1]

wait400lp
nop
; [1]
nop
; [1]
decfsz Count,F
; [1]
goto wait400lp ; [2]
;
-------;
79 x 5 = 395us
decfsz Count2,F ; [1]
goto waitxlp ; [2]
retlw 0
;
;
;

; [2]
total 2 (call) + W x (395 + 5) + 2 (return)
w = 1 -> 406us @4MHz
w = 2 -> 806us @4MHz

;---------------------------------------------------------------------; Initialize PICmicro (PIC12F675)


;---------------------------------------------------------------------INITALIZE
; Disable global interrupts during initialization
bcf

INTCON, GIE

; disable global interrupts

;---------------------------------------; Calibrating the Internal Oscillator (Section 9.2.5.1)


; Oscillator Calibration Register (Section 2.2.2.7)
;
; A calibration instruction is programmed into the last location of
; program memory. This instruction is a RETLW XX, where the literal is
; the calibration value. The literal is placed in the OSCCAL register
; to set the calibration of the internal oscillator.
bsf

STATUS, RP0

call 0x3FF
movwf OSCCAL
bcf

STATUS, RP0

; ---- Select Bank 1 ----; retrieve factory calibration value


; update register with factory cal value
; ---- Select Bank 0 -----

;---------------------------------------; GPIO Port (Section 3.0)


;
; Store GPTRIS value defined above into the TRISIO direction register
bsf

STATUS, RP0

; ---- Select Bank 1 -----

movlw GPTRIS
movwf TRISIO

; Write to TRISIO register

bcf

; ---- Select Bank 0 -----

STATUS, RP0

;---------------------------------------; Comparator Module (Section 6.0)


;

15

;
;
;
;
;
;
;

;
;
;

The PIC12F629/675 devices have one analog comparator. The inputs to


the comparator are multiplexed with the GP0 and GP1 pins. There is
an on-chip Comparator Voltage Reference that can also be applied to
an input of the comparator. In addition, GP2 can be configured as
the comparator output. The Comparator Control Register (CMCON)
contains bits to control the comparator. The Voltage Reference
Control Register (VRCON) controls the voltage reference module.
; Comparator Configuration (Figure 6-2)
bcf
CMCON, CINV
; Comparator Output Inversion: not inverted
bcf
CMCON, COUT
; Comparator Output bit: Vin+ < Vinbcf
CMCON, CIS
; Comparator Input Switch: Vin- connectos to Cin; CM2:CM0 = 111 - Comparator Off (lowest power)
bsf
CMCON, CM2
; Comparator Mode bit 2
bsf
CMCON, CM1
; Comparator Mode bit 1
bsf
CMCON, CM0
; Comparator Mode bit 0
; VRCON (Register 6-2)
bsf
STATUS, RP0
; ---- Select Bank 1 ----bcf

VRCON, VREN

; CVref circuit: powered down, no Idd drain

bcf

VRCON, VRR

; CVref Range Selection: High Range

;
;
;
;

bcf
bcf
bcf
bcf

VRCON,
VRCON,
VRCON,
VRCON,

;
;
;
;

bcf

VR3
VR2
VR1
VR0

STATUS, RP0

CVref
CVref
CVref
CVref

value
value
value
value

selection
selection
selection
selection

bit
bit
bit
bit

3
2
1
0

; ---- Select Bank 0 -----

;---------------------------------------; Analog-to-Digital Converter (A/D) Module (Section 7.0) (PIC12F675 Only)


;
; The analog-to-digital converter (A/D) allows conversion of an analog
; input signal to a 10-bit binary representation of that signal. The
; PIC12F675 has four analog inputs multiplexed into one sample and hold
; circuit. There are two registers to control the functions of the A/D
; module:
; A/D Control Register (ADCON0)
; Analog Select Register (ANSEL)
;
; Note: When using GPIO pins as analog inputs, ensure the TRISIO register
;
bits are set (= 1) for input.
bcf
bcf
bcf

ADCON0, ADFM
ADCON0, VCFG
ADCON0, ADON

bsf

STATUS, RP0

; A/D Result Formed: left justified


; Voltage Reference: Vdd
; ADC is shut-off and consumes no operating current
; ---- Select Bank 1 -----

; select A/D Conversion Clock Source: Fosc/8


bcf
ANSEL, ADCS2
; A/D Conversion Clock Select bit 2
bcf
ANSEL, ADCS1
; A/D Conversion Clock Select bit 1
bsf
ANSEL, ADCS0
; A/D Conversion Clock Select bit 0
; select GPIO pins that will be analog inputs: GP0/AN0, GP1/AN1
bcf
ANSEL, ANS3
; Analog Select GP4/AN3: digital I/O
bcf
ANSEL, ANS2
; Analog Select GP2/AN2: digital I/O
bsf
ANSEL, ANS1
; Analog Select GP1/AN1: analog input
bsf
ANSEL, ANS0
; Analog Select GP0/AN0: analog input
bcf

STATUS, RP0

; ---- Select Bank 0 -----

;----------------------------------------

16

; TIMER1 Module with Gate Control (Section 5.0)


;
; The TIMER1 Control Register (T1CON) is used to enable/disable TIMER1
; and select various features of the TIMER1 module.
bcf

T1CON, TMR1ON

; TIMER1: stopped

bcf

T1CON, TMR1CS

; TIMER1 Clock Source Select: Internal Clock (Fosc/4)

bcf

T1CON, NOT_T1SYNC ; TIMER1 External Clock Input Sync Control: Syncronize external clock input

; T1OSCEN only if INTOSC without CLKOUT oscillator is active, else ignored


bcf
T1CON, T1OSCEN
; LP Oscillator Enable Control: LP oscillator off
; TIMER1 Input Prescale Select: 1:1
bcf
T1CON, T1CKPS1
; TIMER1 Input Clock Prescale Select bit 1
bcf
T1CON, T1CKPS0
; TIMER1 Input Clock Prescale Select bit 0
; TMR1GE only if TMR1ON = 1, else ignored
bcf
T1CON, TMR1GE
; TIMER1 Gate Enable: on
;---------------------------------------; Weak Pull-up Register (WPU) (Section 3.2.1)
;
; Each of the GPIO pins, except GP3, has an individually configurable
; weak internal pull-up. Control bits WPUx enable or disable each
; pull-up. Refer to Register 3-1. Each weak pull-up is automatically
; turned off when the port pin is configured as an output. The pull-ups
; are disabled on a Power-on Reset by the NOT_GPPU bit (see OPTION_REG below).
bsf
;

STATUS, RP0

; ---- Select Bank 1 -----

GPIO Pins = xx54x210


movlw B'00010000'
movwf WPU
bcf

STATUS, RP0

; GP4 pull-up enabled


; ---- Select Bank 0 -----

;---------------------------------------; OPTION Register (OPTION_REG) (Section 2.2.2.2)


; TIMER0 Module (Section 4.0)
;
; The OPTION_REG contains control bits to configure:
; Weak pull-ups on GPIO (see also WPU Register above)
; External GP2/INT interrupt
; TMR0
; TMR0/WDT prescaler
bsf

STATUS, RP0

; ---- Select Bank 1 -----

bcf

OPTION_REG, NOT_GPPU ; GPIO pull-ups: enabled

bsf

OPTION_REG, INTEDG ; Interrupt Edge: on rising edge of GP2/INT pin

bcf
bcf

OPTION_REG, T0CS
OPTION_REG, T0SE

; TMR0 Clock Source: internal instruction cycle (CLKOUT)


; TMR0 Source Edge: increment low-to-high transition on GP2/T0CKI pin

bcf

OPTION_REG, PSA

; Prescaler Assignment: assigned to TIMER0

; TMR0 Prescaler Rate: 1:2


bcf
OPTION_REG, PS2
; Prescaler Rate Select bit 2
bcf
OPTION_REG, PS1
; Prescaler Rate Select bit 1
bcf
OPTION_REG, PS0
; Prescaler Rate Select bit 0
bcf

STATUS, RP0

; ---- Select Bank 0 -----

17

;---------------------------------------; Interrupt-on-Change Register (IOCB) (Section 3.2.2)


;
; Each of the GPIO pins is individually configurable as an interrupt; on-change pin. Control bits IOCBx enable or disable the interrupt
; function for each pin. Refer to Register 3-2. The interrupt-on-change
; is disabled on a Power-on Reset.
;
; Note: Global interrupt enables (GIE and GPIE) must be enabled for
;
individual interrupts to be recognized.
bsf

STATUS, RP0

; GPIO Pins = xx543210


movlw b'00011000'
movwf IOCB
bcf

STATUS, RP0

; ---- Select Bank 1 -----

; Interrupt-on-change enabled: GP3, GP4


; ---- Select Bank 0 -----

;---------------------------------------; Peripheral Interrupt Enable Register (PIE1) (Section 2.2.2.4)


;
; The PIE1 register contains peripheral interrupt enable bits.
;
; Note: The PEIE bit (INTCON<6>) must be set to enable any
;
peripheral interrupt.
bsf

STATUS, RP0

bcf
bcf
bcf
bcf

PIE1,
PIE1,
PIE1,
PIE1,

bcf

STATUS, RP0

EEIE
ADIE
CMIE
TMR1IE

; ---- Select Bank 1 ----; EE Write Complete Interrupt: disabled


; A/D Converter Interrupt (PIC12F675 Only): disabled
; Comparator Interrupt: disabled
; TMR1 Overflow Interrupt: disabled
; ---- Select Bank 0 -----

;---------------------------------------; Interrupt Control Register (INTCON) (Section 2.2.2.3)


;
; The INTCON register contains enable and disable flag bits for TMR0
; register overflow, GPIO port change and external GP2/INT pin
; interrupts.
bcf
bcf
bcf
bsf
;

bcf

INTCON, PEIE
INTCON, T0IE
INTCON, INTE
INTCON, GPIE
INTCON, GIE

; disable Peripheral Interrupt Enable bit


; disable TMR0 Overflow Interrupt Enable bit
; disable GP2/INT External Interrupt Enable bit
; enable Port Change Interrupt Enable bit
; disable global interrupts

;---------------------------------------------------------------------;---------------------------------------------------------------------; Main Program


;---------------------------------------------------------------------;---------------------------------------------------------------------MAIN
bcf
bsf

RFENA
; Disable Transmitter
INTCON, GIE
; enable global interrupts

;---------------------------------; Scan push buttons


;----------------------------------

En esta parte checamos si


el botn PB3 de la tarjeta
del TX se encontraba
presionado. Mientras no se
presionara, se mandaba a
traer el valor analgico por
medio de:
CALL
READ_ANALOG_AN0
***

SCANPB

18

movlw 0x00
movwf FuncBits

; load zero into W


; clear Function Bits register

btfss PB3
; Push Button GP3 pressed?
goto SPB2
movlw 0x23
; Function S0 selected
iorwf FuncBits, F
call READ_ANALOG_AN0 ; read analog channel AN0
;SPB1
;

Todas estas lneas se colocaron


como comentario ya que no
necesitaramos el botn PB4.

btfsc PB4
; Push Button GP4 depressed?
;
goto SPB2
; no, jump over
; movlw 0x43
; Function S1 selected
; iorwf FuncBits, F
;call READ_ANALOG_AN1 ; read analog channel AN1

SPB2
movlw 0xFF
andwf FuncBits, W
; Was any switch depressed?
btfss STATUS, Z
goto XMIT
; Yes, transmit buffer
bcf
RFENA
sleep
goto SCANPB

Se checa si se logr
que el botn PB3 no
fuera presionado.

; No, disable Transmitter


; Put PICmicro to sleep
; Upon wake-up on pin change, scan push buttons

En esta funcin se
Si se adquiri el
habilita el transmisor.
valor analgico
por no presionar
Se enva el valor de la
PB3, se realiza:
adquisicin del
GOTO XMIT ++
potencimetro en CSR1

;---------------------------------; fill in transmission buffer


;---------------------------------XMIT
bsf

RFENA

; Enable Transmitter

movlw 0x73
movwf CSR0

; send Serial number

movfw FuncBits
movwf CSR1
;
;
;
;
;

; send Function Bits

send 16-bit Counter


send analog value (this is modified from the fixed
KeeLoq(r) protocol; these two fields are normally
used for 16-bit counter value)

Despus checamos si
presionamos el botn
PB4. Si esta
presionado se va a
PRENDIDO. Si no
esta presionado se va a
APAGADO.

;***************************
;
;
;

bsf
STATUS, RP0
CLRF
ADRESL
bcf
STATUS, RP0

BTFSC
GOTO
GOTO

; ----- Select Bank 1 ----; ADRESL Result


; ----- Select Bank 0 -----

PB4
APAGADO
PRENDIDO

PRENDIDO
;BSF

STATUS,RP0

; ----- Select Bank 1 -----

MOVLW b'10000000'
GOTO
APAGADO

CONTINUA

Se asigna al WREG, si fue


presionado:
WREG= b1000000
Si no fue presionado
WREG=b00000000

19

;BSF

STATUS,RP0

; ----- Select Bank 1 -----

MOVLW b'00000000'
;*********************************
CONTINUA

movwf CSR2
movfw ADRESH
movwf CSR3

; ADRESH Result

movlw 0x56
movwf CSR4

; send 32-bit serial number 1 (ignored by receiver)

movlw 0x34
movwf CSR5
movlw 0x12
movwf CSR6
movlw 0x20
movwf CSR7
movlw 0x55
movwf CSR8

; send Flags

Este valor del WREG, ya sea que


fue presionado, o no presionado,
se mueve CSR2. De esta manera
en el RECEPTOR, al recuperar
este valor, sabremos si el botn
PB4 fue presionado o no, para
poder realizar la accin de
control de on/off de los motores.

;---------------------------------; Transmission Loop


;---------------------------------TXLoop
; send preamble (50% duty cycle)
Preamble
movlw PREAMB
movwf BitCount
PreL

bsf
TXD
movlw 1
call WaitxTE
bcf
TXD
movlw 1
call WaitxTE
decfsz BitCount,F
goto PreL

; init number of preamble bits


; ON
; delay
; OFF
; delay
; loop

; sync pause
TXloop
movlw D'10'
call WaitxTE

; Theader = 10 x Te

; send 72 bit pattern


movlw CSR0
movwf FSR

; lsb first

TXNextByte
movlw D'8'
movwf BitCount
TXNextBit
rrf
INDF,W

; 8 bit rotate

20

rrf
INDF,F
; Carry contain lsb
BC
ONE
ZERO
movlw 2
;
movwf TimeHi
; +---+---+ +-movlw 1
; |
| |
movwf TimeLo
;---+
+---+
goto Trasm_BIT
; | 2Te Te |
ONE
movlw
movwf
movlw
movwf

1
;
TimeHi
; +---+
+-2
; | |
|
TimeLo
;---+ +---+---+
; | Te 2Te |

Trasm_BIT
bsf
TXD
; ON
movf TimeHi,W
call WaitxTE

bcf
TXD
; OFF
movf TimeLo,W
call WaitxTE
decfsz BitCount,F
goto TXNextBit
incf FSR,F
movlw CSR8+1
xorwf FSR,W
andlw 0x1F
BNZ
TXNextByte

; loop on bits
; check if finished

; guard time
movlw TGUARD
call WaitxTE
goto

SCANPB

; go back and scan for push button presses

;---------------------------------------------------------------------; Data EEPROM Memory (Section 8.0)


;
; PIC12F629/675 devices have 128 bytes of data EEPROM with address
; range 0x00 to 0x7F.
; Initialize Data EEPROM Memory locations
;
;

ORG 0x2100
DE 0x00, 0x01, 0x02, 0x03

;---------------------------------------------------------------------; Calibrating the Internal Oscillator (Section 9.2.5.1)


; Oscillator Calibration Register (OSCCAL) (Section 2.2.2.7)
;
; The below statements are placed here so that the program can be
; simulated with MPLAB SIM. The programmer (PICkit or PROMATE II)
; will save the actual OSCCAL value in the device and restore it.
; The value below WILL NOT be programmed into the device.
org
0x3ff
retlw 0x80
;---------------------------------------------------------------------end
; end of program directive
;----------------------------------------------------------------------

21

Recepcin.
;---------------------------------------------------------------------;
;
Software License Agreement
;
; The software supplied herewith by Microchip Technology Incorporated
; (the "Company") for its PICmicro Microcontroller is intended and
; supplied to you, the Companys customer, for use solely and
; exclusively on Microchip PICmicro Microcontroller products.
;
; The software is owned by the Company and/or its supplier, and is
; protected under applicable copyright laws. All rights are reserved.
; Any use in violation of the foregoing restrictions may subject the
; user to criminal sanctions under applicable laws, as well as to
; civil liability for the breach of the terms and conditions of this
; license.
;
; THIS SOFTWARE IS PROVIDED IN AN "AS IS" CONDITION. NO WARRANTIES,
; WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
; TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
; PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
; IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
; CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
;
;---------------------------------------------------------------------;
; Filename:
rcvr_analog_display.asm
; Date:
April 25, 2003
; File Version:
1.0
; Assembled using:
;
; Author:
Steven Bible
; Company:
Microchip Technology Inc.
;
;
;---------------------------------------------------------------------;
; Files required:
;
p16f676.inc
;
;
;---------------------------------------------------------------------;
; Program Description
;
; This program demonstrates a simple command and control application.
; When a push button on the transmitter module is depressed, the
; corresponding LED is lit on the PICkit(tm) 1 FLASH Starter Kit.
;
; Pressing transmitter module push button GP3 lights LEDs D0-D7 on
; the PICkit(tm) 1 with the upper 8-bit value read from the
; transmitter module 10-bit A/D channel 0 connected to potentiometer
; GP0. Pressing push button GP4 lights LEDs D0-D7 with the upper
; 8-bit value read from A/D channel 1 connected to potentiometer GP1.
;
; The protocol is a simplified KeeLoq(r) protocol compatible with
; the HCS101 fixed code products. This receive code was adapted from
; Microchip Technology application note AN740.

22

;
; The 10-bit analog value is placed into the 16-bit counter field of
; the simplified KeeLoq(r) protocol.
;
;---------------------------------------------------------------------list
p=16f676
; list directive to define processor
#include <p16f676.inc> ; processor specific variable definitions
errorlevel -302

; suppress message 302 from list file

; --------------------------------------------------------------------; Configuration Bits (Section 9.1 Configuration Bits)


; --------------------------------------------------------------------;
; Data Memory Code Protection bit:
; _CPD_ON = Enabled
; _CPD_OFF = Disabled
;
; Program Memory Code protection:
; _CP_ON = Enabled
; _CP_OFF = : Disabled
;
; Brown-out Detection Enable bit:
; _BODEN_ON = Enabled
; _BODEN_OFF = Disabled
;
; GP3/MCLR pin function select:
; _MCLRE_ON = GP3/MCLR pin function is /MCLR
; _MCLRE_OFF = GP3/MCLR pin function is digital I/O,
;
/MCLR internally tied to Vdd
;
; Power-up Timer Enable bit:
; _PWRTE_ON = Enabled
; _PWRTE_OFF = Disabled
;
; Watchdog Timer Enable bit:
; _WDT_ON = Enabled
; _WDT_OFF = Disabled
;
; Oscillator Selction bits:
; _EXTRC_OSC_NOCLKOUT = CLKOUT function on GP4 pin, RC on GP5 pin.
; _EXTRC_OSC_CLKOUT = I/O function on GP4 pin, RC on GP5 pin.
; _INTRC_OSC_CLKOUT = Internal oscillator, CLKOUT function on GP4 pin,
;
I/O function on GP5 pin.
; _INTRC_OSC_NOCLKOUT = Internal oscillator, I/O function on GP4 and GP5 pins.
; _EC_OSC = I/O function on GP4 pin, CLKIN on GP5 pin.
; _HS_OSC = High speed crystal/resonator on GP4 and GP5 pins.
; _XT_OSC = Crystal/resonator on GP4 and GP5 pins.
; _LP_OSC = Low power crystal on GP4 and GP5 pins.
;
;
; --------------------------------------------------------------------__CONFIG _CPD_OFF & _CP_OFF & _BODEN_OFF & _MCLRE_OFF & _PWRTE_OFF & _WDT_OFF &
_INTRC_OSC_NOCLKOUT
;---------------------------------------------------------------------; Variables (Section 2.2 Data Memory Organization)
;---------------------------------------------------------------------; Data Memory Organization (Section 2.2)

23

;
; Register locations 0x20 to 0x5F (64 bytes) are General Purpose
; registers, implemented as static RAM and are mapped across both
; banks.
cblock 0x20
w_temp
status_temp

; used for context saving


; used for context saving

TEMP
DATA0
DATA1
DATA2
DATA3
ORIGIN
SX1TMR
SX2TMR
TMRLOW
TMRHIGH
HIGHWDTH
LOWWDTH
STATECNTR
BITCNTR
FLAGS
COUNTR

; General Purpose Temp register


; 1st byte of received data
; 2nd byte of received data
; 3rd byte of received data
; 4th byte of received data
; a reference used to increment TMRLOW
; LED timer (low order)
; LED timer (high order)
; pulse width timer (low order)
; pulse width timer (high order)
; high pulse width
; low pulse width
; program state counter
; data stream bit counter
; flags
; misc. counter

LEDREG
LEDREGBUF
LEDSTATE

; LED Array Register


; LED Array Register Buffer
; LED Array State Counter

endc
ACTUAL
EQU
0x37
PASADO
EQU
0x38
;---------------------------------------------------------------------; Defines
;----------------------------------------------------------------------

Declaracin de registros
ACTUAL y PASADO, los
cuales sern de utilidad para
obtener una salida binaria
estable.
.

;-------------------; PORTA (Section 3.1)


;-------------------; PORTA is an 6-bit wide, bi-directional port. The corresponding data
; direction register is TRISA. Setting a TRISA bit (= 1) will make
; the corresponding PORTA pin and input. Clearing a TRISA bit (= 0)
; will make the corresponding PORTA pin an output. The exception is
; RA3, which is input only and its TRIS bit will always read as a '1'.
;
; Function of PORTA pins depend on:
; Configuration Bits (CONFIG) (Section 9.1)
; Weak Pull-up Register (WPU) (Section 3.2.1)
; Interrupt-on-change Register (IOCB) (Section 3.2.2)
; Option Register (OPTION_REG) (Register 4-1)
; TIMER1 Control Register (T1CON) (Register 5-1)
; Comparator Control Register (CMCON) (Section 6.0)
; A/D Control Register (ADCON0) (Section 7.0) (PIC16F676 Only)
#define RA0
#define RA1
#define RA2
#define LRNPB
#define RA4

PORTA, 0
PORTA, 1
PORTA, 2
PORTA, 3
PORTA, 4

; (Analog Input) Potentiometer RP1


; (Digital Input/Output) LEDs D6, D7
; (Digital Input/Output) LEDs D2, D3, D4, D5, D6, D7
; (Digital Input Only) Push Button SW1
; (Digital Input/Output) LEDs D0, D1, D2, D3

24

#define RA5

PORTA, 5

; (Digital Input/Output) LEDs D0, D1, D4, D5

; Define for TRISA Register (Section 3.1)


; PORTA Pins = xx543210
#define PORTATRIS b'00111111'
;-------------------; PORTC (Section 3.3)
; -------------------; PORTC is a general purpose I/O port consisting of 6 bi-directional
; pins. The pins can be configured for either digital I/O or analog
; input to A/D converter. For specific information about individual
; functions such as the comparator or the A/D.
#define RC0 PORTC, 0
#define RXDATA PORTC, 1
#define RC2 PORTC, 2
#define RC3 PORTC, 3
#define RC4 PORTC, 4
#define RC5 PORTC, 5

; (Digital Input/Output)
; (Digital Input/Output)
; (Digital Input/Output)
; (Digital Input/Output)
; (Digital Input/Output)
; (Digital Input) Receive Data

El puerto C (compuesto de 6
bits) es configurado en su bit
1 como entrada (donde recibe
la informacin serial). Los bits
2,3,4 y 5 son configurados
como salida y ah se depositar
la salida binaria. El bit 0 del
puerto
C
tambin
se
configurado como salida y
mandar el valor necesario para
activar el codificador (inhibit)
cuando en el transmisor sea
presionado un switch.

; PORTC Pins = xx543210


#define PORTCTRIS b'00000010'
;---------------------------------------; Program Defines
;---------------------------------------; Status Counter
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define

BEGN 0x00
BEGN1 0x01
HEADR 0x02
HEADR1
HIGHP 0x04
LOWP 0x05
RECRD 0x06
WAIT 0x07
VALID 0x08
IMPLMNT

Puerto A (constituido por 6


bits) es configurado como
entrada completamente al
inicio, tambin cambiar
posteriormente cuando se
requiera que este puerto sea
la salida para encender la
matriz de leds.

0x03

0x09

; Flags
#define LRNFLG FLAGS, 0
#define TOGFLG FLAGS, 1
#define HLFLG FLAGS, 2

; this flag is set when in learn mode


; toggle flag
; high-low flag

; LEDs
#define LED0
#define LED1
#define LED2
#define LED3
#define LED4
#define LED5
#define LED6
#define LED7

LEDREG, 0
LEDREG, 1
LEDREG, 2
LEDREG, 3
LEDREG, 4
LEDREG, 5
LEDREG, 6
LEDREG, 7

; S0 LED
; S1 LED
; S2 LED

#define LRNLED LED3


;

GPIO Pins = xx543210

25

#define LED0TRIS b'00001111'


#define LED1TRIS b'00001111'
#define LED2TRIS b'00101011'
#define LED3TRIS b'00101011'
#define LED4TRIS b'00011011'
#define LED5TRIS b'00011011'
#define LED6TRIS b'00111001'
#define LED7TRIS b'00111001'
#define LEDOFFTRIS b'00111111'
;

GPIO Pins = xx543210

#define LED0ON
#define LED1ON
#define LED2ON
#define LED3ON
#define LED4ON
#define LED5ON
#define LED6ON
#define LED7ON

b'00010000'
b'00100000'
b'00010000'
b'00000100'
b'00100000'
b'00000100'
b'00000100'
b'00000010'

;---------------------------------------------------------------------; Program Memory


;---------------------------------------------------------------------; Program Memory Organization (Section 2.1)
ORG

0x000

nop
goto

RESET

ORG

0x004

; RESET Vector
; for ICD use

movwf w_temp
swapf STATUS, W
bcf STATUS, RP0
movwf status_temp

; Interrupt Vector
; save W register
; swap status to be saved into W
; ---- Select Bank 0 ----; save STATUS register

;---------------------------------------; Interrupt Service Routine (ISR) (Section 9.4)


;
; Description: This program does not use interrupts
;
;---------------------------------------swapf
movwf
swapf
swapf

status_temp, W
STATUS
w_temp, F
w_temp, W

; swap status_temp into W, sets bank to original state


; restore STATUS register
; restore W register

retfie
;---------------------------------------------------------------------; Subroutine DATA_EEPROM_READ
;
; Description: To read an EEPROM data memory location, the address is
; written to the EEADR register and set control bit RD (EECON1<0>) to
; initiate a read. Data is available in the EEDATA register the next

26

; clock cycle.
;
; Constants: none
;
; Global Variables: none
;
; Initialization: W contains EEPROM address to be read
;
; Output: W contains EEPROM data
;
;---------------------------------------------------------------------DATA_EEPROM_READ
bsf STATUS, RP0
movwf EEADR
bsf EECON1, RD
movf EEDATA, W
bcf STATUS, RP0

; ---- Select Bank 1 ----; move EEPROM address in W to EEADR


; initiate EEPROM read
; move data to W
; ---- Select Bank 0 -----

return
;---------------------------------------------------------------------; Subroutine DATA_EEPROM_WRITE
;
; Description: To write an EEPROM data memory location, the address is
; written to the EEADR register, data to the EEDATA register, then
; execute a required sequence of instructions.
;
; CAUTION: Interrupts are disable during this subroutine
;
; Constants: none
;
; Global Variables: none
;
; Initialization: Address = EEADR, Data = EEDATA
;
; Output: none
;
;---------------------------------------------------------------------DATA_EEPROM_WRITE
bsf

STATUS, RP0

; ---- Select Bank 1 -----

bsf
bcf

EECON1, WREN
; EEPROM Write Enable: allow write cycles
INTCON, GIE
; disable global interrupts
; *** required sequence, do not alter ***
movlw 0x55
movwf EECON2
movlw 0xAA
movwf EECON2
bsf EECON1, WR
; initiate EEPROM write
; *** end required sequence ***

btfsc EECON1, WR
goto $-1

; has write completed?

bsf
bcf

; enable global interrupts


; EEPROM Write Enable: inhibit write cycles

INTCON, GIE
EECON1, WREN

27

bcf

STATUS, RP0

; ---- Select Bank 0 -----

return
;---------------------------------------------------------------------; Subroutine READ_ANALOG_AN0
;
; Description: Read analog channel 0 (AN0).
;
; Constants: none
;
; Global Variables: none
;
; Initialization: none
;
; Output: ADRESH and ADRESL contain 10-bit A/D result justified
; according to ADCON0, ADFM bit.
;
;---------------------------------------------------------------------READ_ANALOG_AN0
bsf

ADCON0, ADON

bcf
bcf

ADCON0, CHS1
ADCON0, CHS0

; Turn on ADC module


; select analog channel AN0

; After selecting a new channel, allow for sufficent sample time.


; The amount of sample time depends on the charging time of the
; internal charge holding capacitor (Section 7.2).
movlw 0x07
movwf TEMP
decfsz TEMP, F
goto $-1
bsf

; At 4 MHz, a 22 us delay
; (22us = 2us + 6 * 3us + 1us)

ADCON0, GO

btfsc ADCON0, GO
goto $-1
bcf

ADCON0, ADON

; start A/D conversion


; has A/D conversion completed?
; Turn off ADC module (consumes no operating current)

return
;---------------------------------------------------------------------; Initialize PICmicro (PIC12F675)
;---------------------------------------------------------------------INITIAL
; Disable global interrupts during initialization
bcf

INTCON, GIE

; disable global interrupts

;---------------------------------------; Calibrating the Internal Oscillator (Section 9.2.5.1)


; Oscillator Calibration Register (OSCCAL) (Section 2.2.2.7)
;

28

; A calibration instruction is programmed into the last location of


; program memory. This instruction is a RETLW XX, where the literal is
; the calibration value. The literal is placed in the OSCCAL register
; to set the calibration of the internal oscillator.
bsf

STATUS, RP0

call 0x3FF
movwf OSCCAL
bcf

; ---- Select Bank 1 ----; retrieve factory calibration value


; update register with factory cal value

STATUS, RP0

;---- Select Bank 0 -----

;---------------------------------------; PORTS A AND C (Section 3.0)


;
; Store GPTRIS value defined above into the TRISIO direction register
bsf

STATUS, RP0

; ---- Select Bank 1 -----

movlw PORTATRIS
movwf TRISA

; Write to TRISA register

movlw PORTCTRIS
movwf TRISC

; Write to TRISC register

bcf

STATUS, RP0

;---- Select Bank 0 -----

;---------------------------------------; Comparator Module (Section 6.0)


;
; The PIC16F630/676 devices have one analog comparator. The inputs to
; the comparator are multiplexed with the RA0 and RA1 pins. There is
; an on-chip Comparator Voltage Reference that can also be applied to
; an input of the comparator. In addition, RA2 can be configured as
; the comparator output. The Comparator Control Register (CMCON)
; contains bits to control the comparator. The Voltage Reference
; Control Register (VRCON) controls the voltage reference module.
;
;
;

; Comparator Configuration (Figure 6-2)


bcf CMCON, CINV
; Comparator Output Inversion: not inverted
bcf CMCON, COUT
; Comparator Output bit: Vin+ < Vinbcf CMCON, CIS
; Comparator Input Switch: Vin- connectos to Cin; CM2:CM0 = 111 - Comparator Off (lowest power)
bsf CMCON, CM2
; Comparator Mode bit 2
bsf CMCON, CM1
; Comparator Mode bit 1
bsf CMCON, CM0
; Comparator Mode bit 0
; VRCON (Register 6-2)
bsf STATUS, RP0
; ---- Select Bank 1 ----bcf

VRCON, VREN

; CVref circuit: powered down, no Idd drain

bcf

VRCON, VRR

; CVref Range Selection: High Range

;
;
;
;

bcf
bcf
bcf
bcf

VRCON, VR3
VRCON, VR2
VRCON, VR1
VRCON, VR0

; CVref value selection bit 3


; CVref value selection bit 2
; CVref value selection bit 1
; CVref value selection bit 0

29

bcf

STATUS, RP0

;---- Select Bank 0 -----

;---------------------------------------; Analog-to-Digital Converter (A/D) Module (Section 7.0) (PIC16F676 Only)


;
; The analog-to-digital converter (A/D) allows conversion of an analog
; input signal to a 10-bit binary representation of that signal. The
; PIC16F676 has eight analog inputs multiplexed into one sample and hold
; circuit. There are two registers to control the functions of the A/D
; module:
; A/D Control Register 0 (ADCON0)
; A/D Control Register 1 (ADCON1)
; Analog Select Register (ANSEL)
;
; Note: When using PORTA or PORTC pins as analog inputs, ensure the
;
TRISA or TRISC register bits are set (= 1) for input.
bcf
bcf

ADCON0, ADFM
ADCON0, VCFG

; A/D Result Formed: left justified


; Voltage Reference: Vdd

bcf

ADCON0, ADON

; ADC is shut-off and consumes no operating current

bsf

STATUS, RP0

; ---- Select Bank 1 -----

; select A/D Conversion Clock Source: Fosc/8


bcf ADCON1, ADCS2
; A/D Conversion Clock Select bit 2
bcf ADCON1, ADCS1
; A/D Conversion Clock Select bit 1
bsf ADCON1, ADCS0
; A/D Conversion Clock Select bit 0
; select GPIO pins that will be analog inputs: RA0/AN0
bcf ANSEL, ANS7
; Analog Select RC3/AN7: digital I/O
bcf ANSEL, ANS6
; Analog Select RC2/AN6: digital I/O
bcf ANSEL, ANS5
; Analog Select RC1/AN5: digital I/O
bcf ANSEL, ANS4
; Analog Select RC0/AN4: digital I/O
bcf ANSEL, ANS3
; Analog Select RA3/AN3: digital I/O
bcf ANSEL, ANS2
; Analog Select RA2/AN2: digital I/O
bcf ANSEL, ANS1
; Analog Select RA1/AN1/Vref: digital I/O
bsf ANSEL, ANS0
; Analog Select RA0/AN0: analog input
bcf

STATUS, RP0

;---- Select Bank 0 -----

;---------------------------------------; TIMER1 Module with Gate Control (Section 5.0)


;
; The TIMER1 Control Register (T1CON) is used to enable/disable TIMER1
; and select various features of the TIMER1 module.
bcf

T1CON, TMR1ON

; TIMER1: stopped

bcf

T1CON, TMR1CS

; TIMER1 Clock Source Select: Internal Clock (Fosc/4)

bcf

T1CON, NOT_T1SYNC ; TIMER1 External Clock Input Sync Control: Syncronize external clock input

; T1OSCEN only if INTOSC without CLKOUT oscillator is active, else ignored


bcf T1CON, T1OSCEN
; LP Oscillator Enable Control: LP oscillator off
; TIMER1 Input Prescale Select: 1:1
bcf T1CON, T1CKPS1 ; TIMER1 Input Clock Prescale Select bit 1
bcf T1CON, T1CKPS0 ; TIMER1 Input Clock Prescale Select bit 0

30

; TMR1GE only if TMR1ON = 1, else ignored


bcf T1CON, TMR1GE
; TIMER1 Gate Enable: on
;---------------------------------------; PORTA Weak Pull-up Register (WPUA) (Section 3.2.1)
;
; Each of the PORTA pins, except RA3, has an individually configurable
; weak internal pull-up. Control bits WPUAx enable or disable each
; pull-up. Refer to Register 3-1. Each weak pull-up is automatically
; turned off when the port pin is configured as an output. The pull-ups
; are disabled on a Power-on Reset by the /RAPU bit (see OPTION Register
; below).
bsf

STATUS, RP0

; PORTA Pins = xx54x210


movlw B'00000000'
movwf WPUA
bcf

STATUS, RP0

; ---- Select Bank 1 ----; no pull-ups enabled


;---- Select Bank 0 -----

;---------------------------------------; OPTION Register (OPTION_REG) (Section 2.2.2.2)


; TIMER0 Module (Section 4.0)
;
; The OPTION_REG contains control bits to configure:
; Weak pull-ups on GPIO (see also WPU Register above)
; External RA2/INT interrupt
; TMR0
; TMR0/WDT prescaler
bsf

STATUS, RP0

; ---- Select Bank 1 -----

bsf

OPTION_REG, NOT_GPPU ; GPIO pull-ups: disabled

bsf

OPTION_REG, INTEDG ; Interrupt Edge: on rising edge of RA2/INT pin

bcf
bcf

OPTION_REG, T0CS ; TMR0 Clock Source: internal instruction cycle (CLKOUT)


OPTION_REG, T0SE ; TMR0 Source Edge: increment low-to-high transition on GP2/T0CKI pin

bcf

OPTION_REG, PSA

; TMR0 Prescaler Rate: 1:4


bcf OPTION_REG, PS2
bcf OPTION_REG, PS1
bsf OPTION_REG, PS0
bcf

STATUS, RP0

; Prescaler Assignment: assigned to TIMER0


; Prescaler Rate Select bit 2
; Prescaler Rate Select bit 1
; Prescaler Rate Select bit 0

;---- Select Bank 0 -----

;---------------------------------------; PORTA Interrupt-on-Change Register (IOCA) (Section 3.2.2)


;
; Each of the PORTA pins is individually configurable as an interrupt; on-change pin. Control bits IOCAx enable or disable the interrupt
; function for each pin. Refer to Register 3-4. The interrupt-on-change
; is disabled on a Power-on Reset.
;
; Note: Global interrupt enables (GIE and GPIE) must be enabled for
;
individual interrupts to be recognized.

31

bsf

STATUS, RP0

clrf IOCA
bcf

; ---- Select Bank 1 ----; Interrupt-on-change disabled

STATUS, RP0

;---- Select Bank 0 -----

;---------------------------------------; Peripheral Interrupt Enable Register (PIE1) (Section 2.2.2.4)


;
; The PIE1 register contains peripheral interrupt enable bits.
;
; Note: The PEIE bit (INTCON<6>) must be set to enable any
;
peripheral interrupt.
bsf

STATUS, RP0

bcf
bcf
bcf
bcf

PIE1, EEIE
PIE1, ADIE
PIE1, CMIE
PIE1, TMR1IE

bcf

STATUS, RP0

; ---- Select Bank 1 ----; EE Write Complete Interrupt: disabled


; A/D Converter Interrupt (PIC12F675 Only): disabled
; Comparator Interrupt: disabled
; TMR1 Overflow Interrupt: disabled
;---- Select Bank 0 -----

;---------------------------------------; Interrupt Control Register (INTCON) (Section 2.2.2.3)


;
; The INTCON register contains enable and disable flag bits for TMR0
; register overflow, GPIO port change and external GP2/INT pin
; interrupts.
bcf
bcf
bcf
bcf

INTCON, PEIE
INTCON, T0IE
INTCON, INTE
INTCON, RAIE

; disable Peripheral Interrupt Enable bit


; disable TMR0 Overflow Interrupt Enable bit
; disable GP2/INT External Interrupt Enable bit
; disable Port Change Interrupt Enable bit

bcf

INTCON, GIE

; disable global interrupts

retlw 0

; exit INITIAL

;---------------------------------------------------------------------; Subroutine: TIMER


;
; Description: Continually updates two higher order timers (SX1TMR and
; SX2TMR) for use in LED timing.
;
; Constants: none
;
; Global Variables: SX1TMR, SX2TMR
;
; Initialization: none
;
; Output: SX1TMR, SX2TMR
;
;---------------------------------------------------------------------TIMER
btfss TOGFLG
goto TIMER1

; TOGGLE forces this routine to spend


; 1/2 of TMR0 in TIMER and 1/2 in TIMER1.

32

movlw B'01111111'
addwf TMR0, W
; TOGGLE toggles back and forth to a
btfss STATUS, C
; one the rate TMR0 overflows.
retlw 0
; TMR0 overflow ~= 1ms (2^8*4us)
bcf TOGFLG
incfsz SX1TMR, F
; SX1TMR resolution ~= 1ms
retlw 0
; SX1TMR overflow ~= 0.25sec (2^8*1ms)
incf SX2TMR, F
; SX2TMR resolution ~= 0.25sec
retlw 0
; SX2TMR overflw ~= 1min (2^8*0.23sec)
TIMER1
movlw B'01111111'
addwf TMR0, W
btfsc STATUS, C
retlw 0

; Timer routine spends half its time


; in TIMER1 waiting to set TOGGLE
; to one again

bsf TOGFLG
retlw 0
;---------------------------------------------------------------------; Subroutine: CLOCK
;
; Description: Continually updates TMRLOW and TMRHIGH.
;
; Constants: none
;
; Global Variables: ORIGIN
;
; Initialization: ORIGIN
;
; Output: TMRLOW, TMRHIGH
;
;---------------------------------------------------------------------CLOCK
movf ORIGIN, W
subwf TMR0, W
addwf TMRLOW, F
btfsc STATUS, C
incf TMRHIGH, F
nop
nop
nop
movlw 2
subwf TMR0, W
movwf ORIGIN
;
retlw 0

; TMRLOW is updated based on time passed since ORIGIN was set.


; TMRLOW resolution ~= 4us (like TMR0)
; TMRLOW overflow ~= 1ms (2^8*4ms)
; TMRHIGH resolution ~= 1ms
; TMRHIGH overflow ~= 0.24sec (2^8*1ms)

; NOP and subtraction commands ensure


; ORIGIN equals TMR0 as called upon
; in line 2 of CLOCK.
; (ORIGIN must be updated to equal the value
of TMR0 at time of operation with ORIGIN.)

;---------------------------------------------------------------------; Subroutine: LRNDTCT


;
; Description: When the LEARN pushbutton is pressed, this function places
; the program in LEARN mode by:
; - setting the LERN flag
; - setting the STATCNTR to BEGN
; - turning on the learn LED

33

; - clearing the higher order timers, SX1TMR and SX2TMR


;
; Constants:
;
; Global Variables:
;
; Initialization: none
;
; Output: LRNLED, LERN
;
;---------------------------------------------------------------------LRNDTCT
btfsc LRNFLG
retlw 0
movlw BEGN
movwf STATECNTR

; if not already in Learn Mode


; set STATCNTR to BEGN

bsf

LRNFLG

; set LERN flag

bsf

LRNLED

; turn on the Learn LED

clrf SX1TMR
clrf SX2TMR

; clear SX Timer Counter

retlw 0
;---------------------------------------------------------------------; Subroutine: LEARN
;
; Description: This routine learns the first two bytes of data received
; from the transmitter by storing these bytes in its internal EEPROM.
;
; Constants:
;
; Global Variables:
;
; Initialization: none
;
; Output: none
;
;---------------------------------------------------------------------LEARN
btfss SX2TMR, 5
goto LEARN1
bcf
bcf

LRNFLG
LRNLED

; If valid reception is completed within 8 seconds (2^5*0.25sec)


; goto LEARN1
; else exit LEARN mode

retlw 0
LEARN1
movlw VALID
; If the State Counter currently holds
xorwf STATECNTR, W
; the value for exectuting the
btfss STATUS, Z
; VALIDATE function, then a successretlw 0
; ful reception has occurred.
bsf

STATUS, RP0

; ---- Select Bank 1 -----

34

movlw 0x00
movwf EEADR

; EEPROM Address = 0x00

movfw DATA0
movwf EEDATA

; EEPROM Data = DATA0

bcf

; ---- Select Bank 0 -----

STATUS, RP0

call DATA_EEPROM_WRITE ; write first byte to EEPROM


bsf

STATUS, RP0

movlw 0x01
movwf EEADR

; ---- Select Bank 1 ----; EEPROM Address = 0x01

movfw DATA1
movwf EEDATA

; EEPROM Data = DATA1

bcf

; ---- Select Bank 0 -----

STATUS, RP0

call DATA_EEPROM_WRITE ; write second byte to EEPROM


bcf
bcf

LRNLED
LRNFLG

; exit learn mode

movlw BEGN
movwf STATECNTR
retlw 0

; set STATECNTR to BEGN

; exit subroutine LEARN

;---------------------------------------------------------------------; Subroutine: SETWATCH


;
; Description: Initialize the pulse width timer registers.
;
; Constants:
;
; Global Variables:
;
; Initialization: none
;
; Output: ORIGIN
;
;---------------------------------------------------------------------SETWATCH
movf TMR0, W
movwf ORIGIN
clrf TMRLOW
clrf TMRHIGH
retlw

; record TMR0's value in ORIGIN


; clear the low and high order timers

;---------------------------------------------------------------------; Subroutine: SXON


;
; Description: Turns off all LEDs when they timeout. When SX1TMR
; overflows, SX2TMR will increment to 1. Recall this will occur at
; 0.25 seconds (2^8*1ms) after SX1TMR is initiated.
;

35

; Constants: none
;
; Global Variables: LEDREG
;
; Initialization: SX2TMR
;
; Output: none
;
;---------------------------------------------------------------------SXON
btfss SX2TMR, 0
retlw 0
clrf

LEDREG

; turn LEDs off

retlw 0
;---------------------------------------------------------------------; Subroutine: LEDSTATEMACHINE
;
; Description: This is the state machine that cycles through the LED's
; Atates are incremented in the interrupt routine after an overflow on TMR0
;
; Constants:
;
; Global Variables:
;
; Initialization:
;
; Output:
;
;---------------------------------------------------------------------LEDStateMachine
movlw HIGH LEDStateMachineStart
movwf PCLATH
movf LEDSTATE, W
; Mask bits (should be only 8 states)
andlw B'00000111'
addwf PCL, F
LEDStateMachineStart
goto LEDSTATE0
goto LEDSTATE1
goto LEDSTATE2
goto LEDSTATE3
goto LEDSTATE4
goto LEDSTATE5
goto LEDSTATE6
goto LEDSTATE7
LEDSTATE0
call LITELED0
goto EndLEDStateMachine

LEDSTATE1

36

call LITELED1
goto EndLEDStateMachine
LEDSTATE2
call LITELED2
goto EndLEDStateMachine
LEDSTATE3
call LITELED3
goto EndLEDStateMachine
LEDSTATE4
call LITELED4
goto EndLEDStateMachine
LEDSTATE5
call LITELED5
goto EndLEDStateMachine
LEDSTATE6
call LITELED6
goto EndLEDStateMachine
LEDSTATE7
call LITELED7
EndLEDStateMachine
return
;----------------------------------------------------------------LITELED0
bsf STATUS, RP0
movlw LED0TRIS
movwf TRISA
bcf STATUS, RP0
movlw LED0ON
movwf PORTA

; ---- Select Bank 1 ----; ---- Select Bank 0 -----

;**********************************************************
BTFSC
PORTA,4
GOTO
SALIDA_BINARIA_0
REGRESO_0
;**********************************************************
return
LITELED1
bsf STATUS, RP0
movlw LED1TRIS
movwf TRISA
bcf STATUS, RP0
movlw LED1ON

; ---- Select Bank 1 ----; ---- Select Bank 0 -----

En la matriz de leds el
valor a la salida no es
constante, se encuentra
oscilando, por lo que
despus de cada rutina que
verifica si se debe
encender cada led, se
comprueba que en dicho
led se tenga en una
terminal el valor adecuado
para encenderlo. En las
subrutinas
SALIDA_BINARIA_X se
verifica la otra terminal y
si se cumplen los
requisitos se manda un 1
binario en el bit
correspondiente de los
cuatro disponibles (Puerto
A en los pines 2, 3, 4 y 5).
Se aplica lo mismo para
cuatro leds, en cada
recuadro con el smbolo:
*
37

movwf PORTA
;*************
BTFSS PORTA,4
GOTO SALIDA_BINARIA_1
REGRESO_1
;************

return
LITELED2
bsf STATUS, RP0
movlw LED2TRIS
movwf TRISA
bcf STATUS, RP0
movlw LED2ON
movwf PORTA

; ---- Select Bank 1 ----; ---- Select Bank 0 -----

;*************************************
BTFSC PORTA,4
GOTO SALIDA_BINARIA_2
REGRESO_2

;*************************************
return
LITELED3
bsf STATUS, RP0
; ---- Select Bank 1 ----movlw LED3TRIS
movwf TRISA
bcf STATUS, RP0
; ---- Select Bank 0 ----movlw LED3ON
movwf PORTA
BSF
PORTC,5
;***********************************
BTFSS PORTA,4
GOTO SALIDA_BINARIA_2
REGRESO_3

;***********************************
return
LITELED4
bsf STATUS, RP0
movlw LED4TRIS
movwf TRISA
bcf STATUS, RP0
movlw LED4ON
movwf PORTA
return
LITELED5
bsf STATUS, RP0
movlw LED5TRIS
movwf TRISA
bcf STATUS, RP0
movlw LED5ON
movwf PORTA
return

; ---- Select Bank 1 ----; ---- Select Bank 0 -----

; ---- Select Bank 1 ----; ---- Select Bank 0 -----

LITELED6

38

bsf STATUS, RP0


movlw LED6TRIS
movwf TRISA
bcf STATUS, RP0
movlw LED6ON
movwf PORTA
return
LITELED7
bsf STATUS, RP0
movlw LED7TRIS
movwf TRISA
bcf STATUS, RP0
movlw LED7ON
movwf PORTA

; ---- Select Bank 1 ----; ---- Select Bank 0 -----

; ---- Select Bank 1 ----; ---- Select Bank 0 -----

MOVF PASADO,W
SUBWF ACTUAL,W
BTFSS STATUS,Z
CLRF PORTC
BCF
STATUS,Z
MOVF ACTUAL,W
MOVWF PASADO
CLRF ACTUAL
return

;************************
; Subrutine: Salida binaria para cada led
;************
;************************
SALIDA_BINARIA_0
BTFSC PORTA,5
GOTO REGRESO_0
;*******************************
BSF
PORTC,2
BSF
ACTUAL,0
GOTO REGRESO_0
;*******************************

Al regresar de cada rutina de


encendido o no de cada led se
comparan los registros ACTUAL
con PASADO. Si no hubo cambio
entre ellos la salida (puerto C, bits
2, 3, 4 y 5). Si hubo cambio, se
borra el valor de la salida y carga el
valor actual. De esta forma se logra
el objetivo de una salida de 4 bits
constante.
Verificada
previamente
una
terminal de un led, se verifica la
otra y si se cumple lo necesario
para encenderlo, se manda un 1
lgico en el bit del registro
ACTUAL correspondiente (en este
caso el bit 0, es decir el menos
significativo). Si no se cumple la
otra condicin no se modifica este
bit. Se realiza lo mismo para cada
bit en los siguientes recuadros con
el signo:
**

SALIDA_BINARIA_1
BTFSS PORTA,5
GOTO REGRESO_1
;************************
BSF
PORTC,3
BSF
ACTUAL,1
GOTO REGRESO_1
;**********************
SALIDA_BINARIA_2
BTFSC PORTA,2
GOTO REGRESO_2
;*************************
BSF
PORTC,4
BSF
ACTUAL,2
GOTO REGRESO_2
;*************************
SALIDA_BINARIA_3

**
Para el bit 1.

**
Para el bit 2.

39

BTFSS PORTA,2
GOTO REGRESO_3
;************************
BSF
PORTC,5
BSF
ACTUAL,3
Para
GOTO REGRESO_3
;*************************
;************
;---------------------------------------------------------------------; Subroutine: Display
;
; Description: Displays Value Stored In LEDREGBUF On LED Array
; 1 bit is displayed during each call
; LEDREGBUF is reloaded with LEDREG after 8 calls of DISPLAY()
; D7..D4 LED'S show most significant nibble
; D3..D0 LED'S show least significant nibble
;
; Constants:
;
; Global Variables: LEDREG, LEDREGBUF
;
; Initialization:
;
; Output:
;
;---------------------------------------------------------------------DISPLAY
movf
btfsc
goto
btfss
goto

**
el bit 3.

LEDSTATE, W
STATUS, Z
; Are we at state 0?
BUFFERRESET
; Yes
LEDSTATE, 3
; No, did we pass the last state?
BUFFERLOADED
; No

BUFFERRESET
; Yes
movf LEDREG, W
btfss STATUS, Z
; is LEDREG = 0?
goto BUFFERRESET1
; no, jump over
; yes, turn off LEDs
bsf STATUS, RP0
; ---- Select Bank 1 ----movlw LEDOFFTRIS
movwf TRISA
bcf STATUS, RP0
; ---- Select Bank 0 ----clrf PORTA
BUFFERRESET1
movf LEDREG, W
movwf LEDREGBUF
; Reload with the current value in LEDREGISTER
clrf LEDSTATE
; Ensure State Zero
BUFFERLOADED
bcf STATUS, C
; Ensure Carry Is Clear
rrf LEDREGBUF, F
btfsc STATUS, C
; Is The Next Bit a '1'
goto UPDATELED
; Yes, Update The LED Array
goto CONTINUE
; No
UPDATELED
call LEDStateMachine

; Update LED Array

CONTINUE

40

incf LEDSTATE, F
return

; Point To Next State

;---------------------------------------------------------------------;---------------------------------------------------------------------; Main Program


;---------------------------------------------------------------------;---------------------------------------------------------------------RESET
clrf FLAGS
; clear flags
clrf PORTA
; initialize PORTA inputs and outputs
clrf PORTC
; initialize PORTC inputs and outputs
clrf LEDREG
clrf LEDSTATE
clrf LEDREGBUF
movlw BEGN
; setup the state counter to call BEGIN
movwf STATECNTR
call INITIAL
MAIN
call TIMER
call CLOCK
call DISPLAY
movlw B'00000111'
andwf LEDREG, W
btfss STATUS, Z
call SXON
btfss LRNPB
call LRNDTCT
btfsc LRNFLG
call LEARN

; Update LED Array (light LEDs)


; check if LEDs S0, S1, or S2 are set
; if set call SXON

; if learn button is pushed call


; LRNDTCT
; if in learn mode call LEARN

movlw HIGH STATEM


movwf PCLATH
movf STATECNTR, W
; Mask out the high order bits of
andlw B'00001111'
; STATECNTR (a noise guard)
addwf PCL, F
STATEM
goto BEGIN
goto BEGIN1
goto HEADER
goto HEADER1
goto HIGHPLSE
goto LOWPULSE
goto RECORD
goto WAIT4END
goto VALIDATE
goto IMPLEMNT
goto RESET
goto RESET
goto RESET
goto RESET
goto RESET
goto RESET

; The program clock (PCL) is incre; mented by STATECNTR in order


; to go to the appropiate routine

; These RESET commands correct


; erroneous values of STATECNTR
; not caught by the mask above.

;----------------------------------------------------------------------

41

; RECEIVE SEQUENCE
;---------------------------------------------------------------------;*********************** CODE WORD FORMAT ****************************
; _ _ _ _
_ __ _
__ _
_
; ||||||||
|| | ||| | |||
|
; | |_| |_| |_| |_____________| |__| |_| |_/ /_| |_| |_________|
;
/ /
; |--PREAMBLE---|---HEADER----|---------DATA------------|--GUARD--|
;
TIME
;*********************************************************************
;******************** RECEIVED DATA BREAKDOWN ************************
;
;bytes |
DATA1
|
DATA0
|
;bits | 7| 6| 5| 4| 3| 2| 1| 0| 7| 6| 5| 4| 3| 2| 1| 0|
;desc. |S2|S1|S0|S3| 0| 0| SERIAL NUMBER 3
|
;
;bytes |
DATA3
|
DATA2
|
;bits | 7| 6| 5| 4| 3| 2| 1| 0| 7| 6| 5| 4| 3| 2| 1| 0|
;desc. |
COUNTER
|
;
;* S3 Not used
;
;*********************************************************************
;---------------------------------------; BEGIN
;
This function looks for a possible start to the data stream.
;
;
Input Variables:
;
RXDATA
;
Output Variables:
;
none
BEGIN
btfsc RXDATA
incf STATECNTR, F
goto MAIN

; Make state BEGIN1

BEGIN1
btfsc RXDATA
goto MAIN
call SETWATCH
incf STATECNTR, F
goto

; Make state HEADER

MAIN

;---------------------------------------; HEADER
;
Detects a valid header.
;
;
Input Variables:
;
RXDATA
;
Output Variables:
;
none
HEADER
btfsc RXDATA
goto RESTART

; The program loops here until 1.25ms


; passes and if the data is still

42

btfss TMRHIGH, 0
; low. If both hold true -> HEADER1.
goto MAIN
; 1.25ms occurs when:
movlw D'64'
; TMRHIGH = 1 ~= 2^8*4us = 1ms
andwf TMRLOW, W
; TMRLOW = 64 ~= 64*4us = 0.25ms
btfsc STATUS, Z
goto MAIN
incf STATECNTR, F
goto

; Make state HEADER1

MAIN

HEADER1
movlw D'6'
; If the data goes high before 6ms
subwf TMRHIGH, W
; then the header is valid, else
btfss STATUS, C
; restart.
goto HEADER2
; TMRHIGH = 6 = 6*1ms = 6ms
goto

RESTART

HEADER2
btfss RXDATA
goto MAIN
call SETWATCH
movlw D'32'
; Initiate BITCNTR to 32 in order to
movwf BITCNTR
; receive 32 bits of the data stream.
incf STATECNTR, F
; Make state HIGHPLSE
goto

MAIN

;---------------------------------------; HIGHPLSE
;
Times the width of high pulses.
;
;
Input Variables:
;
RXDATA
;
Output Variables:
;
none
HIGHPLSE
btfsc TMRHIGH, 0
goto RESTART

; If TMRLOW overflows then RESTART

btfsc RXDATA
goto MAIN
movf TMRLOW, W
movwf HIGHWDTH
call SETWATCH
incf STATECNTR, F
goto

; Move the pulse width value to


; HIGHWDTH for later calculations.
; Make state LOWPULSE

MAIN

;---------------------------------------; LOWPULSE
;
Times the width of low pulses.
;
;
Input Variables:

43

;
;
;

none
Output Variables:
none

LOWPULSE
btfsc TMRHIGH, 0
goto LOW2

; If TMRLOW overflows then make


; state HEADER.

btfss RXDATA
goto MAIN
movf TMRLOW, W
movwf LOWWDTH
call SETWATCH
incf STATECNTR, F
goto

; Move the pulse width value to


; LOWWDTH for later calculations.
; Make state RECORD

MAIN

LOW2
movlw HEADR
movwf STATECNTR
; Make state HEADER if lowpulse is
; too long.
goto MAIN
;---------------------------------------; RECORD
;
Records each bit as it comes in from the data stream.
;
;
Input Variables:
;
RXDATA
;
Output Variables:
;
DATA0
;
DATA1
;
DATA2
;
DATA3
RECORD
movf HIGHWDTH, W
subwf LOWWDTH, W
; The state of the carry bit after
rrf DATA3, F
; this operation reflects the data
rrf DATA2, F
; logic. This is then rotated
rrf DATA1, F
; into the storage bytes.
rrf DATA0, F
movlw HIGHP
movwf STATECNTR
decfsz BITCNTR, F
goto MAIN
movlw D'4'
movwf COUNTR
movlw DATA0
movwf FSR
RECORD1
movlw 0xFF
xorwf INDF, W
btfss STATUS, Z
goto RECORD2

; Starting here and including RECORD1


; a check is made to make sure that
; the data is not composed entirely
; of 1s.

; Use indirect referencing to point to


; DATA0 -- DATA3 on subsequent loops
; in RECORD1.

44

incf FSR, F
decfsz COUNTR, F
goto RECORD1
goto

RESTART

RECORD2
movlw WAIT
movwf STATECNTR
goto

; Make state WAIT4END

MAIN

;---------------------------------------; WAIT4END
;
Wait for the guard time at the end of the code word before
;
attempting to receive another code word.
;
;
Input Variables:
;
RXDATA
;
Output Variables:
;
none
WAIT4END
btfsc HLFLG
goto WAIT1
btfsc RXDATA
goto MAIN
call
bsf
WAIT1
btfss
goto

; HIGHLOW is set to indicate that the


; data has transitioned from a high
; to a low.

SETWATCH
HLFLG
RXDATA
WAIT2

bcf

HLFLG

goto

MAIN

WAIT2
btfss TMRHIGH, 3
goto MAIN

; If the low period is greater than


; 8ms (2^3*1ms) then the guard time

bcf HLFLG
; has been reached.
incf STATECNTR, F
; Make state VALIDATE
goto

MAIN

;---------------------------------------; VALIDATE
;
Checks that the transmission received is from the valid
;
transmitter.
;
;
Input Variables:
;
DATA0
;
DATA1
;
Output Variables:
;
none

45

VALIDATE
movlw 0x00
; EEPROM Address = 0x00
call DATA_EEPROM_READ ; Get stored DATA0, EEDATA -> W
xorwf DATA0, W
btfss STATUS, Z
goto RESTART

; compare with received DATA0


; If first byte checks out then
; continue, else restart

movlw 0x01
; EEPROM Address = 0x01
call DATA_EEPROM_READ ; Get stored DATA1, EEDATA -> W
movwf TEMP
bsf STATUS, RP0
movf EEDATA, W
bcf STATUS, RP0
xorwf TEMP, F

; move received DATA1 -> TEMP


; ---- Select Bank 1 ----; ---- Select Bank 0 ----; compare with received DATA1

btfsc TEMP, 0
goto RESTART

; Do bits 8 and 9 of Serial Number 3


; check out?

btfsc TEMP, 1
goto RESTART
incf STATECNTR, F
goto

; Make state IMPLEMENT

MAIN

;---------------------------------------; IMPLEMNT
;
Implements the outputs specified by the received code word.
;
;
Input Variables:
;
DATA1
;
Output Variables:
;
S0
;
S1
;
S2
IMPLEMNT
;************************************************************************************voy a poner esto
; btfsc DATA1, 7
; bsf LED2
;
;

; set outputs in accordance with code


; word

btfss DATA1, 7
bcf LED2

; btfsc DATA1, 6
; bsf LED1
; btfss DATA1, 6
; bcf LED1
;

; btfsc DATA1, 5
bsf LED0

; btfss DATA1, 5
; bcf LED0

46

;********************************************************************************************
movf DATA3,W

; read received analog value

;************************************************************************
BTFSC DATA2,7
GOTO ENCENDIDO
En el registro
GOTO APAGADO
ENCENDIDO
BCF
GOTO

PORTC,0
CONTINUA

APAGADO
BSF
CONTINUA
movwf LEDREG
clrf SX1TMR
clrf SX2TMR
goto

PORTC,0
; save to LEDREG
; initialize the timers for the
; outputs

RESTART

;---------------------------------------; RESTART
;
Sets the State Counter to BEGIN so that the receive sequence
;
is restarted.
;
;
Input Variables:
;
none
;
Output Variables:
;
none
RESTART
movlw BEGN
movwf STATECNTR
goto

; restart receive sequence and return


; to MAIN

DATA2 en su bit
ms significativo (7) se es
enviada a partir del transmisor la
informacin de si el switch es
presionado. Si se lee un 1
lgico en dicho bit, quiere decir
que el switch ha sido presionado
y entonces se manda un 1
lgico en el bit 0 del puerto C,
dicha salida ir al inhibit del
codificador 4 a 16 y entonces
ste mandar una salida nica
para cada combinacin. Si el bit
7 del registro DATA2 tiene un
0 lgico quiere decir que el
switch 1 no fue presionado en el
transmisor y por lo tanto se
coloca un 0 lgico en el bit 0
del puerto C y al ir al inhibit del
codificador por lo que no lo
activar y no se tendr una salida
nica
para
diferentes
combinaciones.

MAIN

;---------------------------------------------------------------------; Data EEPROM Memory (Section 8.0)


;
; PIC12F629/675 devices have 128 bytes of data EEPROM with address
; range 0x00 to 0x7F.
; Initialize Data EEPROM Memory locations
ORG 0x2100
DE 0x73, 0x43, 0x02, 0x03
;---------------------------------------------------------------------; Calibrating the Internal Oscillator (Section 9.2.5.1)
; Oscillator Calibration Register (OSCCAL) (Section 2.2.2.7)
;
; The below statements are placed here so that the program can be
; simulated with MPLAB SIM or emulated with the ICD2 or ICE-2000.

47

;
; The programmer (PICkit or PROMATE II) will save the actual OSCCAL
; value in the device and restore it. The value below WILL NOT be
; programmed into the device.
org 0x3ff
retlw 0x40
;---------------------------------------------------------------------end
; end of program directive
;----------------------------------------------------------------------

Resultados.
Se logr realizar las modificaciones adecuadas para el control del brazo robtico, lo cual
se considera como un xito, pues los objetivos planteados por la prctica se alcanzaron y
se logr controlar de forma satisfactoria todos los movimientos del brazo. El alcance que
se calcul que exista entre el transmisor y el receptor es de aproximadamente 8 metros,
lo cual se considera bastante bueno ya que la potencia con la que se transmite no es
mucha.
La tabla No. 3 nos indica el valor de la salida digital del Pic del receptor y el
movimiento que se realiza cuando se activa:

A continuacin se muestran algunas imgenes que se tomaron una vez que se


tena implementado y funcionando todo el circuito.

48

Figura 7. Dispositivos utilizados

Figura 8. Etapa de potencia.

Figura 9. Circuito en funcionamiento.

49

Figura 10. Al frente: Transmisor y etapa de recepcin y potencia. Atrs Brazo y Pic Kit 1.

Conclusin y Comentarios.
Esta es una prctica con un mayor grado de dificultad en su desarrollo ya que es
necesario dedicarle mucho tiempo a entender el funcionamiento del programa de control y
realizar las modificaciones necesarias. La etapa de potencia no present dificultad alguna
ya que el diseo del circuito es muy bsico.
A esta prctica se podra agregar un teclado, en un trabajo extra a futuro, para
eliminar la necesidad de calibrar el potencimetro para la seleccin del movimiento
deseado.
Esta prctica permiti que se lograra una mejor interpretacin del lenguaje
ensamblador, lo cual resulta de gran utilidad ya que existen muchas cosas que ya estn
hechas y que simplemente es necesario adaptarlas a nuestras necesidades.

Bibliografa.
50

http://www.southwest.com.au/~jfuller/robotarm/arm.htm
http://www.super-science-fair-projects.com/owi007-robotic-armtrainer.html
http://www.datasheetcatalog.com
http://www.microchip.com

51

También podría gustarte