You are on page 1of 11

DIRECTIVAS DEL PREPROCESADOR DE C PARA PROGRAMACIN DE PICS

#include<nombre fichero>: incluye un fichero en la compilacin. #byte identificador=x: crea identificadores para una posicin de memoria. #bit identificador=x.y: crea identificadores para un bit de una posicin de memoria. #device chip opciones: indica los modificadores del microcontrolador. #define identificador texto: reemplaza el identificador del preprocesador por texto. #fuses opciones: determina los fusibles que deben activarse o desactivarse. #org principio, final: delimita un rea de memoria para una funcin. #use delay(clock=frecuenciaHz): especifica la frecuencia de trabajo. #use rs232(baud=baudios,bits=nbits,parity=s/n,xmit=pin,rcv=pin): directiva para configurar la comunicacin serie. #use i2c(master/slave, sda=pin,scl=pin,address=nn, fast/slow, restart_wdt): activa las funciones para la comunicacin I2C. #device adc=nbits: especifica el nmero de bits empleados en la funcin read adc().

FUNCIONES DE C PARA PROGRAMACIN DE PICS


Manipulacin de bits/bytes
input(pin): retorna el valor del pin indicado. output_bit(pin,valor): saca un valor (0-1) en el pin indicado. output_high(pin): pone a 1 el pin indicado. output_low(pin): pone a 0 el pin indicado. input_x(valor): retorna el byte del puerto indicado por x. output_x(valor): saca un byte al puerto indicado por x. port_b_pullups(valor): activa o desactiva las resistencias de pull-up del puerto B. set_tris_x(valor): configura como entradas (1) salidas (0) el puerto indicado por x. bit_clear(var,bit): borra el bit indicado de la variable. bit_set(var,bit): pone a 1 el bit indicado de la variable. bit_test(var,bit): retorna el valor del bit indicado de la variable. rtate_left(address,bytes): efecta rotacin a izquierda de los bits de una estructura (Puerto) indicada en address y de tantos bits como indique bytes.

rtate_right(address,bytes): efecta rotacin a derecha de los bits de una estructura (Puerto). shift_left(address,byte,valor): efecta desplazamiento a izquierda de los bits de una estructura (Puerto). shift_right(address,byte,valor): efecta desplazamiento a derecha de los bits de una estructura (Puerto). swap(valor): intercambia los 4 bits (nible) de mayor peso con los 4 de menor peso de un byte.

Retardo
delay_cycles(count): realiza retardos de ciclo de instruccin segn el valor count. delay_us(time): realiza retardos en microsegundos. delay_ms(time): realiza retardos en milisegundos.

PWM
setup_timerX(modo,period,postscale): habilita el timerX para el mdulo PWM. setup_ccpX(modo): indica el modo de funcionamiento de este mdulo (PWM). set_pwmX_duty(valor): establece el ciclo de trabajo de la parte alta.

Periodo= [Tpwm / (4*Tclock*modo)]-1 Pulso= talto / (Tosc*modo)

Interrupciones
enable_interrupts(tipo ): habilita las interrupciones indicadas en tipo. disable_interrupts(tipo ): deshabilita las interrupciones indicadas en tipo. Ext_Int_Handler( ): funcin asociada a la interrupcin.

Tipos que deben ser incluidas como directivas del preprocesador:

#INT GLOBAL, globales (es necesaria independientemente de las particulares). #INT_EXT, externa. #INT_RTCC, desbordamiento del TMR0. #INT_RB, cambio en uno de los pines RB4-7. #INT_AD, conversion AD completa. #INT_ADOF, conversion AD fuera de tiempo. #INT_EEPROM, completada la escritura en EEPROM. #INT_TIMER1, desbordamiento en el TMR1. #INT_TIMER2, desbordamiento en el TMR2. #INT_CCP1, captura/comparacin en CCP1. #INT_CCP2, captura /comparacin en CCP2. #INT_SSP, Puerto serie en modo SSP. #INT_TBE, dato serie transmitido. #INT_RDA, dato serie recibido. #INT_COMP, comparador de interrupciones. #INT_RC, cambio en un pin del Puerto C. #INT_I2C, comunicacin I2C. #INT_BUTTON, pulsador del 14000.h #INT_LCD, LCD del tipo 92XX.

*Despus de la directiva del preprocesador que indica el tipo de interrupcin , por tanto antes del main(), debe ir definida la funcin que se realiza tras la interrupcin. Las interrupciones se habilitan en el main().

Conversin A/D
setup_adc(mode): indica el modo de trabajo del reloj en la conversin. ADC_OFF ADC_CLOCK_DIV_2 ADC_CLOCK_DIV_8

ADC_CLOCK_DIV_32 ADC_CLOCK_DIV_INTERNAL

setup_adc_ports(valor): define las lneas utilizadas. ALL_ANALOG NO_ANALOGS RA0_RA1_RA3_ANALOG RA0_RA1_ANALOG_RA3_REF

set_adc_channel(nmero): indica el canal a leer para la conversin. read_adc( ): especifica el nmero de bits que deben ser retornados (8 16).

TIMERS
setup_timer_x(modo): configura el timerX. RTCC_INTERNAL, RTCC_EXT_L_TO_H, RTCC_EXT_H_TO_L, RTCC_DIV_2, 4, 8, 16, 32,64, 128, 256. get_timer_x(valor): retorna el valor de la cuenta. Para los Timers 1 y 3 son 16 bits. set_timer_x(valor): establece el valor de la cuenta.

Comunicacin RS232
getc(): recoge un carcter del Puerto serie. putc(): enva un carcter por el Puerto serie. Kbhit(): indica si se ha recibido un carcter por el puerto serie. gets(): recoge una cadena de caracteres por el puerto serie. puts(): enva una cadena de caracteres por el puerto serie. Printf(): presenta la informacin en una pantalla.

Comunicacin I2C
i2c_start(): condicin arranque modo i2c

i2c_write(dato): escribe un byte en el interface I2C que puede ser direccin o dato. i2c_read(): lee un byte del interface I2C. i2c_stop(): para comunicacin I2C.

EEPROM INTERNA
read_eeprom(direccin): lee el byte de la direccin de eeprom indicada. write_eeprom(direccin, valor): escribe el dato indicado en la direccin de la eeprom. Esta instruccin tarda varios milisegundos en ejecutarse (10ms).

PROGRAMA PARA ENCENDER UN LED EN RC3 #include<16F876A.h> #use delay(clock=4000000,RESTART_WDT) #fuses XT,NOPROTECT,NOWDT,NOBROWNOUT,NOLVP //PROGRAMA LA GRABACIN #byte port_c=7 #bit led=7.3 //LED TESTIGO CONECTADO A RC3 main() { set_tris_c(0x00); led=1; delay_ms(1000); led=0; }

//CONFIGURA PUERTOC COMO SALIDAS //ENCIENDE LED //RETARDA 1s //APAGA LED

PROGRAMA PARA ROTAR POR RA0

LEDS POR EL PUERTO B DEPENDIENDO DE LO QUE ENTRE

#include<16F876A.h> #use delay(clock=4000000,RESTART_WDT) #fuses XT,NOPROTECT,NOWDT,NOBROWNOUT,NOLVP #byte port_b=6

//PROGRAMA LA GRABACIN

main() { set_tris_b(0x00); //CONFIGURA PUERTOB COMO SALIDAS port_b=1; //CARGA PUERTOB CON 00000001 while(1) { if(input(PIN_A0)) //ROTA IZQUIERDA SI RA0=1 { rotate_left(&port_b,1); } else

{ rotate_right(&port_b,1); } delay_ms(500); }

//ROTA DERECHA SI RA0=0 //RETARDA 0,5s

PROGRAMA PARA SACAR POR EL PUERTO B DEL 0 AL 9 EN UN DISPLAY DE 7 SEGMENTOS CTODO COMN #include<16F876A.h> #use delay(clock=4000000,RESTART_WDT) #fuses XT,NOPROTECT,NOWDT,NOBROWNOUT,NOLVP //PROGRAMA LA GRABACIN #byte port_b=6 unsigned int const display[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x27,0x7f,0x6f}; //SE DEFINE EL ENCENDIDO DE LOS SEGMENTOS DEL 0 AL 9, UN 1 LO ENCIENDE main() { int x=0; //NDICE TABLA VALORES set_tris_b(0x00); //CONFIGURA PUERTOB COMO SALIDAS port_b=0; //BORRA PUERTOB while(1) { X++; if(X>9) X=1; // si ha llegado al 9 vuelve al 1 port_b=display[x]; // SACA AL DISPLAY delay_ms(500); //RETARDA 0,5s } } PROGRAMA PARA TRATAMIENTO DE INTERRUPCIONES. EL MICRO ESTAR EN SLEEP Y CADA VEZ QUE ENTRE UNA INTERRUPCIN POR LA PATILLA 21(RB0/INT, PASA DE "1" A "0") UN LED CONECTADO A RB7 HACE TRES INTERMITENCIAS, VOLVIENDO NUEVAMENTE AL ESTADO DE REPOSO SLEEP. #include<16F876A.h> #use delay(clock=4000000,RESTART_WDT) #fuses XT,NOPROTECT,NOWDT,NOBROWNOUT,NOLVP //PROGRAMA LA GRABACIN #byte port_b=6 #bit LED=6.7 #INT_EXT Ext_Int_Handler() //FUNCIN ASOCIADA A LA INTERRUPCIN {

int x; for(x=0;x<3;x++) { LED=1; delay_ms(500); LED=0; delay_ms(500); } }

//REALIZA 3 INTERMITENCIAS DE 0,5S

main() { set_tris_b(0x01); //CONFIGURA RB1-7 COMO SALIDAS Y RB0 COMO ENTRADA port_b=0; //BORRA PUERTOB enable_interrupts(INT_EXT); //HABILITA ESTA INTERRUPCIN enable_interrupts(GLOBAL); //HABILITA INTERRUPCIONES GLOBALES while(1) sleep(); } PROGRAMA PARA VISUALIZAR MENSAJES FIJOS POR UN LCD RB0 enable RB1 rs RB2 r/w RB4 D4 RB5 D5 RB6 D6 RB7 D7 #include<16F876A.h> #include<lcd.c> //LIBRERA DE LAS FUNCIONES DEL LCD #include<string.h> //LIBRERA PRESENTACIN EN PANTALLA (printf) #use delay(clock=4000000,RESTART_WDT) #fuses XT,NOPROTECT,NOWDT,NOBROWNOUT,NOLVP //PROGRAMA LA GRABACIN #byte port_b=6 main() { set_tris_b(0x00); //CONFIGURA PUERTO B COMO SALIDAS port_b=0; //BORRA PUERTOB lcd_init(); //INICIALIZA LCD lcd_putc("\fIES PALMERAL OS SALUDA\n"); delay_ms(3000); } PROGRAMA PARA VISUALIZAR POR UN LCD LA TECLA PULSADA POR UN TECLADO. UTILIZACIN DE LAS PATILLAS DEL LCD #include<16F876A.h> #include<Lcd.c> //LIBRERA DE LAS FUNCIONES DEL LCD #include<kbd.c> //LIBRERA DE LAS FUNCIONES DEL TECLADO #include<String.h> //LIBRERA PRESENTACIN EN PANTALLA (printf) #use delay(clock=4000000) #fuses XT,NOPROTECT,NOWDT,NOBROWNOUT,NOLVP //PROGRAMA LA GRABACIN #byte port_b=6 char tecla=0; main()

{ lcd_init(); kbd_init();

//INICIALIZA LCD //INICIALIZA EL TECLADO

while(1) { tecla=0; lcd_putc("PULSA UNA TECLA \n"); lcd_gotoxy(8,2); while(tecla==0) { tecla=kbd_getc(); } printf(lcd_putc,"%c",tecla); delay_ms(2000); lcd_putc("\f"); } //CENTRO SEGUNDA LINEA //TOMA TECLA PULSADA //ENVO AL LCD

} PROGRAMA QUE CONTROLA EL TIMER0 COMO TEMPORIZADOR EN UN LCD.

Y PRESENTA LA LECTURA

#include<16F876A.h> #include<Lcd.c> //LIBRERA DE LAS FUNCIONES DEL LCD #include<String.h> //LIBRERA PRESENTACIN EN PANTALLA (printf) #use delay(clock=4000000) #fuses XT,NOPROTECT,NOWDT,NOBROWNOUT,NOLVP #byte port_b=6 #byte port_c=7 #bit parar=7.1 #bit led1=7.2 #bit led2=7.4 //DECLARACIN DE VARIABLES unsigned int tiempo; main() { set_tris_b(0x00); set_tris_c(0x02); port_b=0; port_c=0; led2=1; delay_ms(1000); led2=0; delay_ms(500); //DIRECCIONES DE LOS PUERTOS //PATILLA PARA PARAR EL TIMER //SALIDAS PARA LEDS TESTIGOS

//PUERTO B COMO SALIDAS //PUERTO C COMO SALIDAS Y RC1 COMO ENTRADA //LOS PUERTOS A CERO //TEST DE INICIO DE PROGRAMA

lcd_init(); //INICIALIZA LCD setup_timer_0(RTCC_DIV_256|RTCC_INTERNAL); //CONFIGURA EL TIMER0 CON EL //RELOJ INTERNO Y DIVX256 set_timer0(176); //EL REBOSE DEL TIMER0 (256-176=80x256(div)= UNOS 20ms while(1) { do

led1=1; //LED TESTIGO lcd_gotoxy(5,1); lcd_putc(" Pulsa\n"); }while(parar==0); tiempo=get_timer0(); //PASA EL VALOR DEL TIMER0 A LA VARIABLE tiempo led1=0; lcd_putc("\f"); //BORRA LCD lcd_gotoxy(5,1); //JUSTIFICA EN LA PRIMERA LINEA lcd_putc(" TIEMPO\n"); lcd_gotoxy(10,2); //JUSTIFICA EN LA SEGUNDA LINEA printf(lcd_putc,"%u",tiempo); //ENVA VALOR delay_ms(1500); lcd_putc("\f"); //BORRA LCD delay_ms(200); } } PROGRAMA PARA PRESENTAR EN UN LCD LA LECTURA DE UN SENSOR DE PRESIN QUE ENTREGA SEAL ANALGICA DE 0-40mV (1mV=1,25kPa) #include<16F876A.h> #include<Lcd.c> #include<String.h> //LIBRERA DE LAS FUNCIONES DEL LCD //LIBRERA PRESENTACIN EN PANTALLA (printf)

#use delay(clock=4000000) #fuses XT,NOPROTECT,NOWDT,NOBROWNOUT,NOLVP #byte port_b=6 #byte port_a=5 #bit led=6.3 //DIRECCIONES DE LOS PUERTOS //TESTIGO CONECTADO A RB3

//DECLARACIN DE VARIABLES unsigned int sensor,valor; main() { set_tris_b(0x00); set_tris_a(0xFF); setup_adc_ports(ALL_ANALOG); setup_adc(ADC_CLOCK_INTERNAL); lcd_init(); port_b=0; led=1; delay_ms(500); led=0; delay_ms(500); while(1) { led=1; set_adc_channel(0); sensor=read_adc(); delay_us(50); led=0;

//PUERTO B COMO SALIDAS //PUERTO A COMO ENTRADAS //LNEAS PUERTOA ANALGICAS //RELOJ INTERNO LA FRECUENCIA DE CONVERSIN //INICIALIZA LCD

//pone a cero el puertoB //testeA el inicio de programa

//testigo de adquisicin datos //CANAL A LEER ENTRADA RA0 //LECTURA DE LA SEAL DEL SENSOR //TIEMPO DE ADQUISICIN

valor=30*sensor; //x20 para resolucin (5/256) x1,5 de mv a kPa. lcd_gotoxy(6,1); //CENTRO PRIMERA LINEA printf(lcd_putc,"%u",valor);//ENVA VALOR EN kPa AL LCD lcd_putc(" kPa\n"); delay_ms(300); //RETARDA PARA ACTUALIZAR VALOR PRESIN lcd_putc("\f"); } }

PROGRAMA DE CONTROL DE LA MEMORIA 24FC256I EN COMUNICACIN I2C. SE ALMACENARN DATOS A PARTIR DE LA DIRECCIN DE MEMORIA 1 Y SERN LEDOS PARA PRESENTASRLOS EN UN LCD. EL CHIP TENDR LA DIRECCIN 000 (A0=A1=A2=0)
#include<16F876A.h> #include<Lcd.c> //LIBRERA DE LAS FUNCIONES DEL LCD #include<String.h> //LIBRERA PRESENTACIN EN PANTALLA (printf) #use delay(clock=4000000) #use i2c(master,sda=PIN_C4,scl=PIN_C3) //DIRECTIVA COMUNICACIN I2C #fuses XT,NOPROTECT,NOWDT,NOBROWNOUT,NOLVP //SE PROGRAMA LA GRABACIN #byte port_b=6 #byte port_C=7 #bit LED1=7.7 #bit LED2=6.3 int dato1,dato2,dato3; //VARIABLES main() { set_tris_b(0x00); set_tris_c(0x08); port_b=0; lcd_init();

//CONFIGURA PUERTO B COMO SALIDAS //PUERTO C COMO SALIDAS,RC4-SDA:ENTRADA DATOS //BORRA PUERTOB //INICIALIZA LCD

while(1) { LED1=1; delay_ms(300); LED1=0; i2c_start(); i2c_write(0xA0); i2c_write(0x00); i2c_write(0x01); i2c_write(0x01); i2c_write(0x02); i2c_write(0x07); i2c_stop(); //FIN LED2=1; delay_ms(300); LED2=0;

//TESTIGO INICIO ESCRITURA

//CONDICIN ARRANQUE MODO I2C //BYTE CONTROL ESCRITURA EN CHIP //BYTE_H DIRECCIN ESCRITURA //BYTE_L DIRECCIN ESCRITURA //DATOS A ESCRIBIR ESCRITURA DE DATOS //TESTIGO INICIO LECTURA

i2c_start(); //ARRANQUE MODO I2C i2c_write(0xA0); //BYTE CONTROL ESCRITURA EN CHIP i2c_write(0x00); //BYTE_H DIRECCIN LECTURA i2c_write(0x01); //BYTE_L DIRECCIN LECTURA i2c_start(); //ARRANQUE LECTURA i2c_write(0xA1); //BYTE CONTROL LECTURA EN CHIP dato1=i2c_read(); //LECTURA BYTE DIR 1 dato2=i2c_read(); //LECTURA BYTE DIR 2 dato3=i2c_read(); //LECTURA BYTE DIR 3 delay_ms(50); i2c_stop(); //PARA COMUNICACIN I2C printf(lcd_putc,"\fBTE1-2-3:%d-%d-%d",dato1,dato2,dato3); delay_ms(2000); lcd_putc("\f"); //BORRA LCD } }

You might also like