Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
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
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
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.
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
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.).
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.
Variables globales son declaradas fuera de las funciones. Variables locales son declaradas dentro de las funciones. Ejemplo: Int valor_puerto_a;
Generalmente al momento de declarar una variable esta puede ser definida al mismo tiempo. Int valor_puerto_a=8;
Valores numricos
57 0b111001
'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.
Funcin Main
Todo programa en lenguaje C sin importar su tamao de tener una funcin principal o funci Main.
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
Operadores Aritmticos
Incremeto ++
a=a+1 a=a-1 a++ ++a
a++ a- -
Decremento Variaciones
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
Operadores relacionales
Igual que: Menor que: Mayor que: Menor o igual que: Mayor o igual que: Distinto que:
Operadores lgicos
&& || !
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
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;
Sentencia Do while
do {
} while(expresion)
sentencia_1; sentencia_2;
Funcin printf
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
set_tris_a-k(valor 1 byte)
Programa el registro Tris del puerto a-k Habilita o deshabilita las resistencias pullup del puerto B
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
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)
output_bit(pin,valor)
valor 0,1
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
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
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
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
bit_set(variable,bit)
Ejemplo: bit_set(salida,5) ;
bit_clear(variable,bit)
Ejemplo: bit_clear(salida,5) ;
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)
output_a-k(valor)
Ejemplo: output_c(0x24) ;
luego de esta instruccin el Tris correspondiente se cambia a 0x00 (todos como salida)
delay_us(x)
delay_ms(x)
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
000 RA0/AN0
11.1
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
PIC16F87X
REGISTER 11-2: ADCON1 REGISTER (ADDRESS 9Fh)
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
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+
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
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).
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:
DS30292B-page 111
setup_adc(valor);
(configuracin de parte del registro ADCON0) Las definiciones se encuentran en el archivo \..\Picc\Devices\16f877a.h
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
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
Es recomendable utilizar la informacin dada por el manual del 16F877a #byte ADCON0 =0x1f
ADCON0=0x33; bit_set(ADCON0,2);