Sei sulla pagina 1di 71

Introduccin

Lenguaje C desarrollado por Bell Labs (Lucent Technologies) en 1979 por D. Ritchie Lenguaje estructurado Portatil De alto nivel A pesar de ser un lenguaje de alto nivel se puede acceder a el hardware de bajo nivel

Definicin - Programa

Est constituido por un conjunto de instrucciones que se ejecutan generalmente de modo secuencial.

Caracteristicas de uso de lenguajes de alto nivel

Los lenguajes de alto nivel son ms o menos comprensibles para el usuario, pero no para el procesador. Los programas de alto nivel deben ser traducidos para que el procesador los pueda entender se usa un compilador.

Niveles de Programacin
Lenguaje C Alto nivel Compilador Cdigo Objeto Binario Lenguaje Ensamblador Bajo nivel

Ensamblador

Estructura de los Programas en lenguaje C


Directivas al preprocesador. Declaracin de variables, funciones, tipos, Globales. Definicin de Variables Globales. Funciones.

Directivas al preprocesador.

Son comandos especificos al compilador Por ejemplo: #include <stdio.h> cargar los prototipos de la funciones standard de entrada salida. #device pic16f877a definir el microcontrolador a usar. #include<16f877a.h> cargar las definiciones particulares del micro 17F877a

Tipos de varibles o datos


int1 int8 int16 int32 char float short Int long void

Define numeros de 1 bit Define numeros de 8 bits Define numeros de 16 bits Define numeros de 32 bits Define caracter de 8 bits Define numeros de 32 bits punto flotante Por defecto igual a int1 Por defecto igual a int8 Por defecto igual a int16 ningn tipo especifico.

Tipos de varibles o datos


Int1 0 -- 1 Int8 0 -- 255 Int16 0 -- 65536 Int32 0 -- 4294967296 char 0 -- 255 float -3.4x10-38 3.4x1038 Signed long -32768 -- 32767

Nombre de las variables (Identificadores)


Una variable se forma con una secuencia de letras (minsculas de la a a la z; maysculas de la A a la Z; y dgitos del 0 al 9). El carcter underscore (_) (piso) se considera como una letra ms. Un identificador no puede contener espacios en blanco, ni otros caracteres como (*,;.:-+, etc.).

Nombre de las variables (Identificadores)


El primer carcter de un identificador debe ser siempre una letra o un (_), es decir, no puede ser un dgito. Se hace distincin entre letras maysculas y minsculas. As, Masa es considerado como un identificador distinto de masa y de MASA. ANSI C permite definir identificadores de hasta 31 caracteres de longitud.

Nombre de las variables (Identificadores)


Ejemplos de identificadores vlidos son los siguientes: tiempo,distancia1,caso_A,PI velocidad_de_la_luz

Declaracion de nombres, variables, funciones.


Variables globales son declaradas fuera de las funciones. Variables locales son declaradas dentro de las funciones. Ejemplo: Int valor_puerto_a;

Declaracion de nombres, variables, funciones.

Generalmente al momento de declarar una variable esta puede ser definida al mismo tiempo. Int valor_puerto_a=8;

Valores numricos

Sistema decimal: Sistema binario :

57 0b111001

Sistema hexadecimal: 0x39 Caracter:


(Cdigo ASCII)

'9'

Cdigo ASCII

American Standard Code for Information Interexchange Cdigo de caracteres basado en alfabeto latino. Creado en 1963 por Bell Labs Incluye caracteres no imprimibles (cdigos de control)

Cdigo ASCII
Dec 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 Char ! " # $ % & ( ) * + , . / 0 Dec 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 Char 1 2 3 4 5 6 7 8 9 : ; < = > ? @ Dec 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 Char A B C D E F G H I J K L M N O P Dec 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 Char Q R S T U V W X Y Z [ \ ] ^ _ ` Dec 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 Char a b c d e f g h i j k l m n o p Dec 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 Char q r s t u v w x y z { | } ~ _

Funciones

Una funcin del lenguaje C es una porcin de cdigo o programa que realiza una determinada tarea. En otros leguajes es llamada subrutina, subprograma, procedimiento, etc.

Ventajas del uso de funciones

Permite la modularizacin del programa. Ahorra memoria y tiempo de desarrollo.


(memoria de programa y memoria de datos)

Independencia de datos y oculta informacin no necesaria par otras funciones.

Partes de una Funcin

Nombre Valor de retorno Argumentos de la funcin.

Valor_de_retorno NOMBRE(argumento1, argumento 2, etc){ }

Funcin Main

Todo programa en lenguaje C sin importar su tamao de tener una funcin principal o funci Main.

void main(void) { sentencia_1 sentencia_2 ... }

Ejemplo de programa
// directiva al preprocesador /* incluir prototipo de entrada salida standard */ #include <stdio.h> #define PI 3.142 // variable global float area; /* declaracin de funcin /* int cuadrado(int r);

Ejemplo de programa
// funcion main main() { // variable local int radio_cuadrado; int radio = 3; radio_cuadrado=cuadrado(radio); /* pasar valor a la funcin */

Ejemplo de programa
area = PI * radio_cuadrado; /* sentencia de asignacin */ printf(El area is %6.4f al cuadrado\n,area); } /* fin de la funcin main*/

Ejemplo de programa
int cuadrado(int r) /* funcin */ { int r_cuadrado; // variable local r_cuadrado = r * r; return(r_cuadrado); /* retornar valor /* }

Palabras claves

auto double break else case enum char extern const float continue for default goto do if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

Operadores Aritmticos

Suma: + Resta: Multiplicacin: * Divisin: / Resto: %

Ejemplo: 23%4 = 3 23/4 = 5.75 23%4 = 23 4x5 = 3

Operadores de incremento y decremento

Incremeto ++
a=a+1 a=a-1 a++ ++a

a++ a- -

Decremento Variaciones

opera y luego incrementa incrementa y luego opera

Operadores de incremento y decremento


Ejemplos: si k=2

a=++k*4 = 12 (3*4) k=3 b=4*k++ = 12 (4*3) k=4

Operadores de asignacin

Suma y asigna a=a+b Resta y asigna a=a-b Multiplica y asigna a=a*b Divide y asigna a=a/b

+= a+=b -= a-=b *= a*=b /= a/=b

Operadores relacionales

Igual que: Menor que: Mayor que: Menor o igual que: Mayor o igual que: Distinto que:

== < > <= >= !=

Operadores lgicos

Son usados en combinacin con los operadores relacionales Operador logico Y


if (a==b) && (b>=0) if (c<0) || (c>27)

&& || !

Operador lgico O Operador lgico NO

if(!a) if(a) si a es diferente de cero if(!a) si a es igual a cero

Operadores lgicos bitwise


Operaciones sobre cada bit Y & O | Or exclusiva ^ Complemento a 1 ~ Despalzar a la derecha >> Despazar a la izquierda <<
a = 0100 1101 b = 1001 1011 a & b = 0000 1001

(alt 038) (alt 124) (alt 094) (alt 126)

Operadores lgicos bitwise


a = 0100 1101 b = 1001 1011 a | b = 1101 1111 a=b>>3 Si b = 0100 1100 a= 0x09

b>>3 = 0000 1001

Sentencia if
if (expresion) sentencia_1; else sentencia_2;

Sentencia if
if (expresion){ sentencia_1; sentencia_2; } else{ sentencia_3; sentencia_4; }

Sentencia if
if (expresion) { sentencia_1; sentencia_2; } else { sentencia_3; sentencia_4; }

Sentencia switch
switch (expresion) { case expresion_cte_1: sentencia_1; case expresion_cte_2: sentencia_2; .... case expresion_cte_n: sentencia_n; default: sentencia; }

Sentencia switch*
switch (expresion) { case expresion_cte_1: sentencia_1; break; case expresion_cte_2: sentencia_2; break; .... case expresion_cte_n: sentencia_n; break; default: sentencia;

Sentencia for
for (inicializacion; expresion_de_control; actualizacion) sentencia; for(x=1;x<=19;x++) sentencia;

Sentencia for
for(x=1;x<=19;x++) { sentencia_1; sentencia_2; sentencia_3; }

Sentencia while
while(expresion) {

sentencia_1; sentencia_2;

Se verifica y luego se ejecuta

Sentencia Do while
do {

} while(expresion)

sentencia_1; sentencia_2;

Se ejecuta y luego se verifica

Funcin printf

Imprime sobre un dispositivo estandard


En PC dispositivo estandar es el monitor En PIC el dispositivo estandard es un puerto serial

printf("cadena_de_control", tipo arg1, tipo arg2, ...)

Funcin printf
e E f g G o s u x X p Scientific notation (mantise/exponent) using e character Scientific notation (mantise/exponent) using E character Decimal floating point Use the shorter of %e or %f Use the shorter of %E or %f Signed octal String of characters Unsigned decimal integer Unsigned hexadecimal integer Unsigned hexadecimal integer (capital letters) Pointer address Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored. A % followed by another % character will write % to stdout. 3.93E+002 3.93E+002 392.65 392.65 392.65 610 sample 7235 7fa 7FA B800:0000

n %

Funcin printf
printf ("Characters: %c %c \n", 'a', 65); Characters: a A printf ("Decimals: %d %ld\n", 1977, 650000); Decimals: 1977 650000 printf ("Preceding with blanks: %10d \n", 1977); Preceding with blanks: 1977

Funcin printf
printf ("Preceding with zeros: %010d \n", 1977); Preceding with zeros: 0000001977 printf ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100); Some different radixes: 100 64 144 0x64 0144

Funcin printf
printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416); floats: 3.14 +3e+000 3.141600E+000 printf ("%s \n", "A string"); A string

Bibliografia

Gracia de Jaln de la Fuente, Javier. Aprenda lenguaje Ansi C como si estuviera en primero, San Sebastian, 1998 Gardner,Nigel. PICmicro MCU C, An introduction to programming, The Microchip PIC in CCS C, Bluebird Electronics 2002. C Compiler Reference Manual, Custom Computer Services CCS, 2006

Puertos digitales del PIC


P7 P6 P5 P4 P3 P2 P1 P0 Puerto I/O T7 T6 T5 T4 T3 T2 T1 T0 0 Bit Programado como salida Registro Tris 1 Bit Programado como entrada

Instrucciones del CCS para Pics

set_tris_a-k(valor 1 byte)

Programa el registro Tris del puerto a-k Habilita o deshabilita las resistencias pullup del puerto B

port_b_pullups(valor 1 bit) (TRUE, FALSE)

Instrucciones para el manejo de bits (CCS)

input(pin)

Lee el bit indicado por pin Ejemplo: A = input(PIN_B4) ; (TRUE, FALSE) Las definiciones se encuentran en el archivo \..\picc\Devices\16f877a.h

Instrucciones para el manejo de bits (CCS)

bit_test(variable,bit)

Lee el bit indicado por bit de la variable o registro el resultado es TRUE, FALSE Ejemplo: A = bit_test(dato,5) ; (TRUE, FALSE)

Instrucciones para el manejo de bits (CCS)

output_bit(pin,valor)

Escribe bit indicado por pin Ejemplo: output_bit(PIN_B5,1) ;

valor 0,1

Las definiciones se encuentran en el archivo \..\picc\Devices\16f877a.h

Instrucciones para el manejo de bits (CCS)

output_float(pin)

Convierte el pin en entrada (Trispin =1) Ejemplo: output_float(PIN_B5) ; Las definiciones se encuentran en el archivo \..\picc\Devices\16f877a.h

Instrucciones para el manejo de bits (CCS)

output_high(pin)

Escribe en el pin un alto Ejemplo: output_high(PIN_B7) ; Las definiciones se encuentran en el archivo \..\picc\Devices\16f877a.h

Instrucciones para el manejo de bits (CCS)

output_low(pin)

Escribe en el pin un bajo Ejemplo: output_low(PIN_B7) ; Las definiciones se encuentran en el archivo \..\picc\Devices\16f877a.h

Instrucciones para el manejo de bits (CCS)

output_toggle(pin)

Escribe en el pin el valor negado al valor anterior Ejemplo: output_toggle(PIN_B4) ; Las definiciones se encuentran en el archivo \..\picc\Devices\16f877a.h

Instrucciones para el manejo de bits (CCS)

bit_set(variable,bit)
Ejemplo: bit_set(salida,5) ;

Escribe un alto en el bit de la variable o registro

Instrucciones para el manejo de bits (CCS)

bit_clear(variable,bit)
Ejemplo: bit_clear(salida,5) ;

Escribe un bajo en el bit de la variable o registro

Instrucciones para el manejo de bytes (CCS)

input_a-k()

lee el dato correspondiente al puerto a-k Ejemplo: a=input_b() ; luego de esta instruccin el Tris correspondiente se cambia a 0xff (todos como entrada)

Instrucciones para el manejo de bytes (CCS)

output_a-k(valor)
Ejemplo: output_c(0x24) ;

Escribe el valor correspondiente al puerto a-k

luego de esta instruccin el Tris correspondiente se cambia a 0x00 (todos como salida)

Instrucciones para el manejo de reatardos (CCS)

delay_us(x)

ejecuta un retardo de softwarede x microsegundos Ejemplo: delay_us(10) ;

Instrucciones para el manejo de reatardos (CCS)

delay_ms(x)

ejecuta un retardo de softwarede x milisegundos Ejemplo: delay_ms(500) ;

Configuracin del hardware ejemplo Convertidor ADC

Convertidor de 10 bits de aproximaciones sucesivas 8 canales analgicos de entrada Configuracin del las refrencias de tensin
(FSR)

Tensin ADC = 1024*RFS/Dato ADC RFS Rango de full escala (Vref [+] - Vref[-])

PIC16F87X
FIGURE 11-1: A/D BLOCK DIAGRAM
CHS2:CHS0

111 110 101 100 VAIN (Input voltage) 011 010 A/D Converter 001

RE2/AN7(1) RE1/AN6(1) RE0/AN5(1) RA5/AN4 RA3/AN3/VREF+ RA2/AN2/VREFRA1/AN1

VDD VREF+ (Reference voltage) PCFG3:PCFG0

000 RA0/AN0

VREF(Reference voltage) VSS PCFG3:PCFG0 Note 1: Not available on 28-pin devices.

11.1

A/D Acquisition Requirements

For the A/D converter to meet its specified accuracy, the charge holding capacitor (CHOLD) must be allowed to fully charge to the input channel voltage level. The analog input model is shown in Figure 11-2. The source impedance (RS) and the internal sampling switch (RSS) impedance directly affect the time required to charge the capacitor CHOLD. The sampling switch (RSS) impedance varies over the device voltage (VDD), Figure 11-2. The maximum recommended impedance for analog sources is 10 k. As the impedance is decreased, the acquisition time may be decreased. After the analog input channel is selected (changed), this acquisition must be done before the conversion can be started.

To calculate the minimum acquisition time, Equation 11-1 may be used. This equation assumes that 1/2 LSb error is used (1024 steps for the A/D). The 1/2 LSb error is the maximum error allowed for the A/D to meet its specified resolution. To calculate the minimum acquisition time, TACQ, see the PICmicro Mid-Range Reference Manual (DS33023).

DS30292B-page 114

1999 Microchip Technology Inc.

PIC16F87X
REGISTER 11-2: ADCON1 REGISTER (ADDRESS 9Fh)

U-0 ADFM bit7

U-0

R/W-0

U-0

R/W-0 PCFG3

R/W-0 PCFG2

R/W-0 PCFG1

R/W-0 PCFG0 bit0 R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR reset

bit 7:

ADFM: A/D Result format select 1 = Right Justified. 6 most significant bits of ADRESH are read as 0. 0 = Left Justified. 6 least significant bits of ADRESL are read as 0. Unimplemented: Read as 0 PCFG3:PCFG0: A/D Port Configuration Control bits

bit 6-4: bit 3-0:

PCFG3: PCFG0 0000 0001 0010 0011 0100 0101 011x 1000 1001 1010 1011 1100 1101 1110 1111

AN7(1) RE2 A A D D D D D A D D D D D D D

AN6(1) RE1 A A D D D D D A D D D D D D D

AN5(1) RE0 A A D D D D D A A A A D D D D

AN4 RA5 A A A A D D D A A A A A D D D

AN3 RA3 A VREF+ A VREF+ A VREF+ D VREF+ A VREF+ VREF+ VREF+ VREF+ D VREF+

AN2 RA2 A A A A D D D VREFA A VREFVREFVREFD VREF-

AN1 RA1 A A A A A A D A A A A A A D D

AN0 RA0 A A A A A A D A A A A A A A A

VREF+ VDD RA3 VDD RA3 VDD RA3 VDD RA3 VDD RA3 RA3 RA3 RA3 VDD RA3

VREFVSS VSS VSS VSS VSS VSS VSS RA2 VSS VSS RA2 RA2 RA2 VSS RA2

CHAN / Refs(2) 8/0 7/1 5/0 4/1 3/0 2/1 0/0 6/2 6/0 5/1 4/2 3/2 2/2 1/0 1/2

A = Analog input D = Digital I/O Note 1: These channels are not available on the 28-pin devices. 2: This column indicates the number of analog channels available as A/D inputs and the numer of analog channels used as voltage reference inputs.

DS30292B-page 112

1999 Microchip Technology Inc.

PIC16F87X
11.0 ANALOG-TO-DIGITAL CONVERTER (A/D) MODULE
The A/D module has four registers. These registers are: A/D Result High Register (ADRESH) A/D Result Low Register (ADRESL) A/D Control Register0 (ADCON0) A/D Control Register1 (ADCON1)

The Analog-to-Digital (A/D) Converter module has five inputs for the 28-pin devices and eight for the other devices. The analog input charges a sample and hold capacitor. The output of the sample and hold capacitor is the input into the converter. The converter then generates a digital result of this analog level via successive approximation. The A/D conversion of the analog input signal results in a corresponding 10-bit digital number. The A/D module has high and low voltage reference input that is software selectable to some combination of VDD, VSS, RA2 or RA3. The A/D converter has a unique feature of being able to operate while the device is in SLEEP mode. To operate in sleep, the A/D clock must be derived from the A/Ds internal RC oscillator.

The ADCON0 register, shown in Register 11-1, controls the operation of the A/D module. The ADCON1 register, shown in Register 11-2, configures the functions of the port pins. The port pins can be configured as analog inputs (RA3 can also be the voltage reference) or as digital I/O. Additional information on using the A/D module can be found in the PICmicro Mid-Range MCU Family Reference Manual (DS33023).

REGISTER 11-1: ADCON0 REGISTER (ADDRESS: 1Fh)


R/W-0 ADCS1 bit7 R/W-0 ADCS0 R/W-0 CHS2 R/W-0 CHS1 R/W-0 CHS0 R/W-0 GO/DONE U-0 R/W-0 ADON bit0 R = Readable bit W = Writable bit U = Unimplemented bit, read as 0 - n = Value at POR reset

bit 7-6:

ADCS1:ADCS0: A/D Conversion Clock Select bits 00 = FOSC/2 01 = FOSC/8 10 = FOSC/32 11 = FRC (clock derived from an RC oscillation) CHS2:CHS0: Analog Channel Select bits 000 = channel 0, (RA0/AN0) 001 = channel 1, (RA1/AN1) 010 = channel 2, (RA2/AN2) 011 = channel 3, (RA3/AN3) 100 = channel 4, (RA5/AN4) 101 = channel 5, (RE0/AN5)(1) 110 = channel 6, (RE1/AN6)(1) 111 = channel 7, (RE2/AN7)(1) GO/DONE: A/D Conversion Status bit If ADON = 1 1 = A/D conversion in progress (setting this bit starts the A/D conversion) 0 = A/D conversion not in progress (This bit is automatically cleared by hardware when the A/D conversion is complete) Unimplemented: Read as '0' ADON: A/D On bit 1 = A/D converter module is operating 0 = A/D converter module is shutoff and consumes no operating current

bit 5-3:

bit 2:

bit 1: bit 0:

Note 1: These channels are not available on the 28-pin devices.

1999 Microchip Technology Inc.

DS30292B-page 111

Instrucciones para la configuracin del convertidor ADC (CCS)

setup_adc(valor);

(configuracin de parte del registro ADCON0) Las definiciones se encuentran en el archivo \..\Picc\Devices\16f877a.h

Instrucciones para la configuracin del convertidor ADC (CCS)

setup_adc(valor);

(configuracin del registro ADCON0) // Constants used for SETUP_ADC() are: #define ADC_OFF 0 // ADC Off #define ADC_CLOCK_DIV_2 0x10000 #define ADC_CLOCK_DIV_4 0x4000 #define ADC_CLOCK_DIV_8 0x0040 #define ADC_CLOCK_DIV_16 0x4040 #define ADC_CLOCK_DIV_32 0x0080 #define ADC_CLOCK_DIV_64 0x4080 #define ADC_CLOCK_INTERNAL 0x00c0

Instrucciones para la configuracin del convertidor ADC (CCS)


ADCON0[7:6] #define ADC_OFF 0 // ADC Off Bit ADON = 0 (bit0) #define ADC_CLOCK_DIV_2 0x10000 0000 0000 #define ADC_CLOCK_DIV_8 0x0040 0100 0000 #define ADC_CLOCK_DIV_32 0x0080 1000 0000 #define ADC_CLOCK_INTERNAL 0x00c0 1100 0000

Instrucciones para la configuracin del convertidor ADC (CCS)

Es recomendable utilizar la informacin dada por el manual del 16F877a #byte ADCON0 =0x1f
ADCON0=0x33; bit_set(ADCON0,2);

#bit ADON =0x1f.0 #bit ON_DONE = 0x1f.2 while(ON_DONE){ }

Potrebbero piacerti anche