Autor Tema: Mini curso "Programación en XC8"  (Leído 588463 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado jukinch

  • Colaborador
  • PIC24F
  • *****
  • Mensajes: 608
Re: Mini curso "Programación en XC8"
« Respuesta #150 en: 26 de Septiembre de 2013, 23:31:55 »
Hola Angelgris. El tema viene por el problema que referís.

Recuerdo haber renegado con ello. Cito post

Con estas dos directivas se me fueron todos los unable to resolve identifiers :-/

#define __18CXX // con esta solucioné los de la libreria de los delays
#define __18F4550 // y con esta los de las funciones de la usart y de los adc

Pareciera que el IDE no define correctamente el pic seleccionado en el proyecto.  :5]
agregúe al principio de mi archivo  main.c estos dos defines



Creo que el problema está en que si no se los define a mano el preprocesador no expande el código correspondiente a nuestro pic dentro del archivo pconfig.h:

Código: [Seleccionar]
#ifdef   __18F4550
/*############################################################*/
/*          Configuration for device =  'PIC18F4550'          */
/*############################################################*/

/* ADC */
#define ADC_V5

/* ECC */
/*No configuration chosen for this peripheral*/

/* CC */
#define CC_V2

/* EPWM */
#define PWM_V5

/* PWM */
#define PWM_V5

/* PCPWM */
/*No configuration chosen for this peripheral*/

/* USART */
#define EAUSART_V5

/* SPI */
#define SPI_V1

/* I2C */
#define I2C_V1

/* TIMERS */
#define TMR_V2

/* EEPROM */
#define EEP_V2

/* PORT_B */
#define PTB_V1

/* ANCOMP */
#define ANCOM_V3

/* MWIRE */
#define MWIRE_V1

/* CTMU */
/*No configuration chosen for this peripheral*/

/* PPS */
/*No configuration chosen for this peripheral*/

/* RTCC */
/*No configuration chosen for this peripheral*/

/* DPSLP */
/*No configuration chosen for this peripheral*/

/* PMP */
/*No configuration chosen for this peripheral*/

/* FLASH */
#define FLASH_V1_2

#endif

Y por ello dentro de los headers de los periféricos se saltean los prototipos de las funciones.

Es necesario que estén definidas las versiones de cada uno de ellos por ejemplo en mi 4550 #define ADC_V5 . De lo contrario se saltean los prototipos de las funciones.

Como por ejemplo la de OpenADC en el header adc.h

Código: [Seleccionar]
#elif defined (ADC_V3) || defined (ADC_V4) || defined (ADC_V5) || defined (ADC_V6) ||\
      defined (ADC_V7) || defined (ADC_V7_1)|| defined (ADC_V12) || defined (ADC_V13)\
 || defined (ADC_V13_1) || defined (ADC_V13_2) || defined (ADC_V13_3) || \
 defined (ADC_V14) || defined (ADC_V14_1) || defined (ADC_V14_2) || defined (ADC_V14_3)

void OpenADC ( unsigned char ,
               unsigned char ,
               unsigned char );

"Divide las dificultades que examinas en tantas partes como sea posible para su mejor solución." -René Descartes

Desconectado elgarbe

  • Moderadores
  • PIC24H
  • *****
  • Mensajes: 2178
Re: Mini curso "Programación en XC8"
« Respuesta #151 en: 29 de Septiembre de 2013, 20:05:03 »
En estos día he estado trabajando en varios proyectos del colegio y ya los empecé a plantear en XC8. La verdad estoy muy conforme! Con esta guía, mas algunas cosas que me paso juknich pude hacer andar todo vastante rápido.

Pongo acá un ejemplo de uso del Enhanced CCP del PIC 16F883, utilizando el PWM para control de un motor de DC en modo full bridge. Esa capacidad del micro está muy, pero muy buena. Una vez configurado el PWM, solo hay que modificar 2 registros para cambiar el sentido de giro y el ciclo de trabajo. El módulo solo se encarga de activar un pin de salida, hacer PWM sobre el otro y desactivar los otros 2 en forward y vice verza en backward....

Dejo el código:

Código: [Seleccionar]
#define _XTAL_FREQ 4000000 // Indicamos a que frecuencia de reloj esta funcionando el micro
//Funciones para delay's. No son muy precisas por lo que vi en el osciloscopio
//REVISAR
#pragma intrinsic(_delay)
extern void _delay(unsigned long);
#define __delay_us(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000000.0)))
#define __delay_ms(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000.0)))

#include <stdio.h>
#include <stdlib.h>
#include <xc.h>         // Librería XC8. Este include termina incluyendo al 16F883.h
//#include <delays.h>     // Para utilizar demoras en nuestro código debemos incluir la librería delays.h.

//Includes locales, configuracion de fusibles y del IO
#include "configuracion_de_fuses.c"
#include "configuracion_hard.c"

unsigned char cont = 0;                   //Contador para destello de LED

/*------------------------DECLARACION DE FUNCIONES---------------------------*/

void conf_oscilador (void); // Configuracion del oscilador
void conf_puertos (void);   // Configuracion de puertos I/O
void conf_timer0 (void);    // Configuracion registros TIMER0
void conf_timer1 (void);    // Configuracion registros TIMER1
void conf_pwm (void);

/********** Funcion para la ISR (Rutina de Servicio de Interrupcion) **********/
void interrupt interrupciones (void) {
    //Verifico que interrupcion se disparó
    if (TMR0IE && TMR0IF){      // se verifica si la interrupcion es por TMR0

        //Destello de LED cada 20 * 65,535 mS -> 1,3Seg
        if(++cont == 20){
            cont=0;
            LED_tst ^= 1;
        }
        TMR0IF = 0;             // Pongo en 0 el Flag de interrupcion del TMR0
    }
/* el resto de las interrupciones utilizadas se deben analizar a coninuacion*/
}




/*************************** Programa Principal ******************************/
 void main(void) {
    conf_oscilador ();
    conf_puertos ();
    conf_timer0 ();
    conf_pwm();

    //conf_timer1 ();

    INTCONbits.TMR0IE = 1;       //Habilito interrupcion por TMR0
    INTCONbits.PEIE = 1;         //Habilito las interrupciones de los perifericos
    INTCONbits.GIE = 1;          //Habilito Interrupcion Global

    PORTC=0b00000000;
    int i=0;
    /*-------------------------- Bucle infinito ------------------------------*/
    do{
        CCP1CONbits.P1M=0b01;       //Motor en Forward
        CCPR1L=0;                   // DC en 0
        for(i=0; i<255; i+=5){      // Voy incrementando el DC de a 5
            CCPR1L = CCPR1L++;
            __delay_ms (50);
        }
        CCPR1L=0;                   // DC en 0
        CCP1CONbits.P1M=0b11;       // Motor en Backward
        for(i=0; i<255; i+=5){      // Voy incrementando el DC de a 5
            CCPR1L = CCPR1L++;
            __delay_ms (50);
        }
   }while(1);
}


/*------------------------------FUNCIONES------------------------------------*/

/* Funcion para la configuracion del oscilador del pic16f88 */
void conf_oscilador (void) {

    OSCCONbits.IRCF2 = 1;
    OSCCONbits.IRCF1 = 1;
    OSCCONbits.IRCF0 = 0; // IRCF <2:0> = 110 setea Fosc 4MHz

    OSCCONbits.SCS = 0; /* SCS = 0 Modo del oscilador definido por
                         * FOSC <2:0> en #pragma config FOSC = INTOSCIO */
}
/* Funcion para la configuracion de los puertos entrada salida del pic 16f88 */
void conf_puertos (void) {

    ANSEL=0x00;         //Todos entrada/salida digitales - Puerto A.
    ANSELH=0x00;        //Todos entrada/salida digitales - Puerto B.
    TRISA=0b00101010; //RA0, 2 y 4 Salidas. RA1, 3 y 5 Entradas-
    TRISB=0x00; //Todos como SALIDAS.
    TRISC=0x0F; //RC0-3 Entrada. RC4-7 Salida
    PORTC=0;
    PORTB=0;
}

/* Funcion para la configuracion del modulo Timer0 como temporizador */
void conf_timer0 (void) {

    // Configuración del timer 0. Con Osc de 4MHz la frecuencia de entrada del TMR
    // es 1MHz, con el prescaler en 256 tenemos una cuenta cada 256uSeg. Al ser
    // de 8 bits tenemos interrupcion cada 65,535 mSeg.
    TMR0 = 0;
    OPTION_REGbits.PS0 = 1;
    OPTION_REGbits.PS1 = 1;
    OPTION_REGbits.PS2 = 1;     //Prescaler en 256
    OPTION_REGbits.PSA = 0;     //Prescaler al TMR0 y no al WDT
    OPTION_REGbits.T0CS = 0;    //Clock Source es el Ciclo de Instruccion
}

/* Funcion para la configuracion del modulo Timer1 como temporizador */
void conf_timer1 (void) {

    // Configuración del timer 1. Con Osc de 4MHz la frecuencia de entrada del TMR
    // es 1MHz, con el prescaler en 1 tenemos una cuenta cada 1uSeg. Al ser
    // de 16 bits tenemos interrupcion cada 65,535 mSeg.
    // El timer 1 se usa como base de tiempos de CCP2
    TMR1 = 0;
    T1CONbits.T1CKPS = 0x00;    //Prescaler en 2 -> XX00
    T1CONbits.TMR1ON = 0;       //Enable Timer1
}


/* Funcion para la configuracion del modulo Timer1 como temporizador */
void conf_timer2 (void) {

    // Configuración del timer 1. Con Osc de 4MHz la frecuencia de entrada del TMR
    // es 1MHz, con el prescaler en 1 tenemos una cuenta cada 1uSeg. Al ser
    // de 16 bits tenemos interrupcion cada 65,535 mSeg.
    // El timer 1 se usa como base de tiempos de CCP2
    TMR1 = 0;
    T1CONbits.T1CKPS = 0x00;    //Prescaler en 2 -> XX00
    T1CONbits.TMR1ON = 0;       //Enable Timer1
}

void conf_pwm(void){
    // CONFIGURANDO PWM  - Pagina 133 datasheet
    TRISCbits.TRISC2=1;     //Configuro como entrada los pines del PWM
    TRISB |= 0b00010110;
    PR2 = 0x65;             // Frecuencia
    CCP1CONbits.CCP1M = 0b1100;     // Activamos el modo PWM.
    CCP1CONbits.P1M = 0b01;         // Full Bridge Forward
    CCP1CONbits.DC1B = 0b00;        // LSB del DC=0
    CCPR1=0x00;                     // MSB del DC=0

    PIR1bits.TMR2IF=0;              // Borro posible bandera de Int del TMR2
    T2CONbits.T2CKPS = 0b01;        // Prescaler del timer 2 en 1:4
    T2CONbits.TMR2ON = 1;           // Arranca el PWM
    while(PIR1bits.TMR2IF==0);      // Espero a primera interrupcion del TMR2
    TRISCbits.TRISC2=0;             // Configuro como Salida los pines del PWM
    TRISB &= ~(0b00010110);         // para que comience a funcionar
}

El archivo configuracion_de_hardware.c no lo incluyo porque en este caso no hay nada, solo la definicion del LED_tst que esta en RB5.

Este es el configuracion_de_fuses.c

Código: [Seleccionar]
// PIC16F883 Configuration Bit Settings

// CONFIG1
#pragma config FOSC = INTRC_NOCLKOUT// Oscillator Selection bits (INTOSCIO oscillator: I/O function on RA6/OSC2/CLKOUT pin, I/O function on RA7/OSC1/CLKIN)
#pragma config WDTE = OFF       // Watchdog Timer Enable bit (WDT disabled and can be enabled by SWDTEN bit of the WDTCON register)
#pragma config PWRTE = OFF      // Power-up Timer Enable bit (PWRT disabled)
#pragma config MCLRE = OFF      // RE3/MCLR pin function select bit (RE3/MCLR pin function is digital input, MCLR internally tied to VDD)
#pragma config CP = OFF         // Code Protection bit (Program memory code protection is disabled)
#pragma config CPD = OFF        // Data Code Protection bit (Data memory code protection is disabled)
#pragma config BOREN = OFF      // Brown Out Reset Selection bits (BOR disabled)
#pragma config IESO = OFF       // Internal External Switchover bit (Internal/External Switchover mode is disabled)
#pragma config FCMEN = OFF      // Fail-Safe Clock Monitor Enabled bit (Fail-Safe Clock Monitor is disabled)
#pragma config LVP = OFF        // Low Voltage Programming Enable bit (RB3 pin has digital I/O, HV on MCLR must be used for programming)

// CONFIG2
#pragma config BOR4V = BOR40V   // Brown-out Reset Selection bit (Brown-out Reset set to 4.0V)
#pragma config WRT = OFF        // Flash Program Memory Self Write Enable bits (Write protection off)

Si a halguien le interesa subo un videito del efecto que se consigue sobre unos LED. Todavia no tengo el puente H armado para verlo en el motor.

Saludos!
-
Leonardo Garberoglio

Desconectado Rseliman

  • PIC16
  • ***
  • Mensajes: 239
Re: Mini curso "Programación en XC8"
« Respuesta #152 en: 01 de Octubre de 2013, 16:00:44 »
Amigos ...les paso escrito en xc8 una subrutina modificada por mi para escribir un lcd 5110 de nokia ..con un pic18f2550 ....lo unico que no puedo llegar a entender todavia ..es la posicion de x ...me he cansado de leer el pdf del lcd y a mi entender estoy haciendo las cosas bien , pero no logro que escriba en la posicion x que quiero ...con y no tengo problemas ..esa va bien ...pero en x la verdad no lo entiendo si alguien me puede dar una mano ...bienvenido !!!!

5110lcd.h


Código: [Seleccionar]
/*
 * File:   5110lcd.h
 * Author: Ramiro
 *
 * Created on 22 de septiembre de 2013, 20:03
 */
  void gotoxy(int x , int y );
void LCD5110_init(void);
void LCD5110_send(unsigned char data, unsigned char dc);
void LCD5110_cls(unsigned char b_w);
void LCD5110_sendchar(unsigned char character);
void LCD5110_sendstring(const char *str);




5110lcd.c


Código: [Seleccionar]
/*
 * File:   5110lcd.c
 * Author: Ramiro Seliman 2013
 *
 * Created on 22 de septiembre de 2013, 20:32
 */


#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include <delays.h>
#include <spi.h>
#include "5110lcd.h"

// define the pins

   #define SCE_5110  LATBbits.LATB3
   #define RESET_5110 LATBbits.LATB2
   #define DC_5110 LATBbits.LATB4



 const char font[] = {0x00, 0x00, 0x00, 0x00, 0x00, // 20 space
    0x00, 0x00, 0x5f, 0x00, 0x00, // 21 !
    0x00, 0x07, 0x00, 0x07, 0x00, // 22 "
    0x14, 0x7f, 0x14, 0x7f, 0x14, // 23 #
    0x24, 0x2a, 0x7f, 0x2a, 0x12, // 24 $
    0x23, 0x13, 0x08, 0x64, 0x62, // 25 %
    0x36, 0x49, 0x55, 0x22, 0x50, // 26 &
    0x00, 0x05, 0x03, 0x00, 0x00, // 27 '
    0x00, 0x1c, 0x22, 0x41, 0x00, // 28 (
    0x00, 0x41, 0x22, 0x1c, 0x00, // 29 )
    0x14, 0x08, 0x3e, 0x08, 0x14, // 2a *
    0x08, 0x08, 0x3e, 0x08, 0x08, // 2b +
    0x00, 0x50, 0x30, 0x00, 0x00, // 2c ,
    0x08, 0x08, 0x08, 0x08, 0x08, // 2d -
    0x00, 0x60, 0x60, 0x00, 0x00, // 2e .
    0x20, 0x10, 0x08, 0x04, 0x02, // 2f /
    0x3e, 0x51, 0x49, 0x45, 0x3e, // 30 0
    0x00, 0x42, 0x7f, 0x40, 0x00, // 31 1
    0x42, 0x61, 0x51, 0x49, 0x46, // 32 2
    0x21, 0x41, 0x45, 0x4b, 0x31, // 33 3
    0x18, 0x14, 0x12, 0x7f, 0x10, // 34 4
    0x27, 0x45, 0x45, 0x45, 0x39, // 35 5
    0x3c, 0x4a, 0x49, 0x49, 0x30, // 36 6
    0x01, 0x71, 0x09, 0x05, 0x03, // 37 7
    0x36, 0x49, 0x49, 0x49, 0x36, // 38 8
    0x06, 0x49, 0x49, 0x29, 0x1e, // 39 9
    0x00, 0x36, 0x36, 0x00, 0x00, // 3a :
    0x00, 0x56, 0x36, 0x00, 0x00, // 3b ;
    0x08, 0x14, 0x22, 0x41, 0x00, // 3c <
    0x14, 0x14, 0x14, 0x14, 0x14, // 3d =
    0x00, 0x41, 0x22, 0x14, 0x08, // 3e >
    0x02, 0x01, 0x51, 0x09, 0x06, // 3f ?
    0x32, 0x49, 0x79, 0x41, 0x3e, // 40 @
    0x7e, 0x11, 0x11, 0x11, 0x7e, // 41 A
    0x7f, 0x49, 0x49, 0x49, 0x36, // 42 B
    0x3e, 0x41, 0x41, 0x41, 0x22, // 43 C
    0x7f, 0x41, 0x41, 0x22, 0x1c, // 44 D
    0x7f, 0x49, 0x49, 0x49, 0x41, // 45 E
    0x7f, 0x09, 0x09, 0x09, 0x01, // 46 F
    0x3e, 0x41, 0x49, 0x49, 0x7a, // 47 G
    0x7f, 0x08, 0x08, 0x08, 0x7f, // 48 H
    0x00, 0x41, 0x7f, 0x41, 0x00, // 49 I
    0x20, 0x40, 0x41, 0x3f, 0x01, // 4a J
    0x7f, 0x08, 0x14, 0x22, 0x41, // 4b K
    0x7f, 0x40, 0x40, 0x40, 0x40, // 4c L
    0x7f, 0x02, 0x0c, 0x02, 0x7f, // 4d M
    0x7f, 0x04, 0x08, 0x10, 0x7f, // 4e N
    0x3e, 0x41, 0x41, 0x41, 0x3e, // 4f O
    0x7f, 0x09, 0x09, 0x09, 0x06, // 50 P
    0x3e, 0x41, 0x51, 0x21, 0x5e, // 51 Q
    0x7f, 0x09, 0x19, 0x29, 0x46, // 52 R
    0x46, 0x49, 0x49, 0x49, 0x31, // 53 S
    0x01, 0x01, 0x7f, 0x01, 0x01, // 54 T
    0x3f, 0x40, 0x40, 0x40, 0x3f, // 55 U
    0x1f, 0x20, 0x40, 0x20, 0x1f, // 56 V
    0x3f, 0x40, 0x38, 0x40, 0x3f, // 57 W
    0x63, 0x14, 0x08, 0x14, 0x63, // 58 X
    0x07, 0x08, 0x70, 0x08, 0x07, // 59 Y
    0x61, 0x51, 0x49, 0x45, 0x43, // 5a Z
    0x00, 0x7f, 0x41, 0x41, 0x00, // 5b [
    0x02, 0x04, 0x08, 0x10, 0x20, // 5c 55
    0x00, 0x41, 0x41, 0x7f, 0x00, // 5d ]
    0x04, 0x02, 0x01, 0x02, 0x04, // 5e ^
    0x40, 0x40, 0x40, 0x40, 0x40, // 5f _
    0x00, 0x01, 0x02, 0x04, 0x00, // 60 `
    0x20, 0x54, 0x54, 0x54, 0x78, // 61 a
    0x7f, 0x48, 0x44, 0x44, 0x38, // 62 b
    0x38, 0x44, 0x44, 0x44, 0x20, // 63 c
    0x38, 0x44, 0x44, 0x48, 0x7f, // 64 d
    0x38, 0x54, 0x54, 0x54, 0x18, // 65 e
    0x08, 0x7e, 0x09, 0x01, 0x02, // 66 f
    0x0c, 0x52, 0x52, 0x52, 0x3e, // 67 g
    0x7f, 0x08, 0x04, 0x04, 0x78, // 68 h
    0x00, 0x44, 0x7d, 0x40, 0x00, // 69 i
    0x20, 0x40, 0x44, 0x3d, 0x00, // 6a j
    0x7f, 0x10, 0x28, 0x44, 0x00, // 6b k
    0x00, 0x41, 0x7f, 0x40, 0x00, // 6c l
    0x7c, 0x04, 0x18, 0x04, 0x78, // 6d m
    0x7c, 0x08, 0x04, 0x04, 0x78, // 6e n
    0x38, 0x44, 0x44, 0x44, 0x38, // 6f o
    0x7c, 0x14, 0x14, 0x14, 0x08, // 70 p
    0x08, 0x14, 0x14, 0x18, 0x7c, // 71 q
    0x7c, 0x08, 0x04, 0x04, 0x08, // 72 r
    0x48, 0x54, 0x54, 0x54, 0x20, // 73 s
    0x04, 0x3f, 0x44, 0x40, 0x20, // 74 t
    0x3c, 0x40, 0x40, 0x20, 0x7c, // 75 u
    0x1c, 0x20, 0x40, 0x20, 0x1c, // 76 v
    0x3c, 0x40, 0x30, 0x40, 0x3c, // 77 w
    0x44, 0x28, 0x10, 0x28, 0x44, // 78 x
    0x0c, 0x50, 0x50, 0x50, 0x3c, // 79 y
    0x44, 0x64, 0x54, 0x4c, 0x44, // 7a z
    0x00, 0x08, 0x36, 0x41, 0x00, // 7b {
    0x00, 0x00, 0x7f, 0x00, 0x00, // 7c |
    0x00, 0x41, 0x36, 0x08, 0x00, // 7d }
    0x10, 0x08, 0x08, 0x10, 0x08, // 7e ~
    0x78, 0x46, 0x41, 0x46, 0x78};


  void LCD5110_init(void)
{
   
     OpenSPI(SPI_FOSC_64, MODE_00, SMPEND );


    Delay10KTCYx(20);
    SCE_5110 = 0; // Enable the 5110 device (Active Low)
    RESET_5110 = 0; // Reset the device. Again, active low
    Delay10KTCYx(20); // Delay 20ms to make sure its ok!
    RESET_5110 = 1;


    LCD5110_send(0x21, 0); // Extended instructions enabled
    LCD5110_send(0xC0, 0); // Set VOLTAJE 5V
    LCD5110_send(0x07, 0); // Temperature control
    LCD5110_send(0x13, 0); // Set bias system
    LCD5110_send(0x20, 0); // Display control set to BASIC mode
    LCD5110_send(0x0C, 0); // Display modo NORMAL
 

  }

  void gotoxy(int x , int y )
  {
   LCD5110_send((0x80 | x) , 0); //X address
   LCD5110_send((0x40 | y) , 0); //Y address

  }

void LCD5110_send(unsigned char data, unsigned char dc)
{
    DC_5110 = dc; // Set the appropriate status for command=0 or data=1
    putcSPI (data);
}


void LCD5110_cls(unsigned char b_w)
{
    unsigned int i;
    unsigned char bg;

    if (b_w == 0) // set the background color
    {
        bg = 0x00;
    }
    else if (b_w == 1)
    {
        bg = 0xFF;
    }

    LCD5110_send(0x40, 0); // set Y address
    LCD5110_send(0x80, 0); // set X address
    for (i = 0; i < 504; i++)
    {
        LCD5110_send(bg, 1); // Clear everything
    }
}

void LCD5110_sendchar(unsigned char character)
{
   
    unsigned char column = 0;
    character = character - 0x20; // 0x20 is the first element of the array

    for (column = 0; column < 5; column++) // Pass through each column
    {
        LCD5110_send(font[(int) character * 5 + column], 1);
    }

    LCD5110_send(0x00, 1); // Send a small space
}

void LCD5110_sendstring(const char *str)
{

//   LCD5110_send((0x40 | y) , 0); //Y address
//   LCD5110_send((0x80 | x) , 0); //X address

    while (*str) // pass through each character
    {
        LCD5110_sendchar(*str); // and send it
        str++;
    }

     }



main .c


Código: [Seleccionar]
/*
 * File:   main.c
 * Author: Ramiro Seliman 2013
 *
 * Created on 5 de septiembre de 2013, 14:24
 */
#include <xc.h>
#include <delays.h>
#include <stdio.h>
#include <stdlib.h>
#include "system.h"
#include <PIC18F2550.h>
#include <spi.h>
#include "5110lcd.h"


#define _XTAL_FREQ 8000000

   void main(void) {
   
     ConfigureOscillator();

     _delay(500);

  //  BMP085_Calibration();
    LATB = 0x00 ;
    PORTB = 0x00 ;
    TRISB = 0x00;
    TRISA = 0x00 ;
    LATC = 0x00 ;
    PORTC = 0x00 ;
    TRISC = 0x00 ;
    LCD5110_init();
    LCD5110_cls(0);



        gotoxy(1,0); // coordenada x , coordenada y
        LCD5110_sendstring("Hola Mundo!"); //envio string
while (1)
    {
    };
    return;
}


Bitsconfiguracion.c

Código: [Seleccionar]

// PIC18F2550 Configuration Bit Settings

// CONFIG1L

#pragma config PLLDIV = 1       // PLL Prescaler Selection bits (No prescale (4 MHz oscillator input drives PLL directly))
#pragma config CPUDIV = OSC1_PLL2// System Clock Postscaler Selection bits ([Primary Oscillator Src: /1][96 MHz PLL Src: /2])
#pragma config USBDIV = 1       // USB Clock Selection bit (used in Full-Speed USB mode only; UCFG:FSEN = 1) (USB clock source comes directly from the primary oscillator block with no postscale)

// CONFIG1H
#pragma config FOSC = INTOSC_HS // Oscillator Selection bits (Internal oscillator, HS oscillator used by USB (INTHS))
#pragma config FCMEN = OFF      // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor disabled)
#pragma config IESO = OFF       // Internal/External Oscillator Switchover bit (Oscillator Switchover mode disabled)

// CONFIG2L
#pragma config PWRT = ON       // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOR = OFF         // Brown-out Reset Enable bits (Brown-out Reset enabled in hardware only (SBOREN is disabled))
#pragma config BORV = 3         // Brown-out Reset Voltage bits (Minimum setting)
#pragma config VREGEN = OFF     // USB Voltage Regulator Enable bit (USB voltage regulator disabled)

// CONFIG2H
#pragma config WDT = OFF        // Watchdog Timer Enable bit (WDT disabled (control is placed on the SWDTEN bit))
#pragma config WDTPS = 32768    // Watchdog Timer Postscale Select bits (1:32768)

// CONFIG3H
#pragma config CCP2MX = OFF      // CCP2 MUX bit (CCP2 input/output is multiplexed with RC1)
#pragma config PBADEN = OFF      // PORTB A/D Enable bit (PORTB<4:0> pins are configured as analog input channels on Reset)
#pragma config LPT1OSC = OFF    // Low-Power Timer 1 Oscillator Enable bit (Timer1 configured for higher power operation)
#pragma config MCLRE = ON       // MCLR Pin Enable bit (MCLR pin enabled; RE3 input pin disabled)

// CONFIG4L
#pragma config STVREN = OFF      // Stack Full/Underflow Reset Enable bit (Stack full/underflow will cause Reset)
#pragma config LVP = OFF        // Single-Supply ICSP Enable bit (Single-Supply ICSP disabled)
#pragma config XINST = OFF      // Extended Instruction Set Enable bit (Instruction set extension and Indexed Addressing mode disabled (Legacy mode))

// CONFIG5L
#pragma config CP0 = OFF        // Code Protection bit (Block 0 (000800-001FFFh) is not code-protected)
#pragma config CP1 = OFF        // Code Protection bit (Block 1 (002000-003FFFh) is not code-protected)
#pragma config CP2 = OFF        // Code Protection bit (Block 2 (004000-005FFFh) is not code-protected)
#pragma config CP3 = OFF        // Code Protection bit (Block 3 (006000-007FFFh) is not code-protected)

// CONFIG5H
#pragma config CPB = OFF        // Boot Block Code Protection bit (Boot block (000000-0007FFh) is not code-protected)
#pragma config CPD = OFF        // Data EEPROM Code Protection bit (Data EEPROM is not code-protected)

// CONFIG6L
#pragma config WRT0 = OFF       // Write Protection bit (Block 0 (000800-001FFFh) is not write-protected)
#pragma config WRT1 = OFF       // Write Protection bit (Block 1 (002000-003FFFh) is not write-protected)
#pragma config WRT2 = OFF       // Write Protection bit (Block 2 (004000-005FFFh) is not write-protected)
#pragma config WRT3 = OFF       // Write Protection bit (Block 3 (006000-007FFFh) is not write-protected)

// CONFIG6H
#pragma config WRTC = OFF       // Configuration Register Write Protection bit (Configuration registers (300000-3000FFh) are not write-protected)
#pragma config WRTB = OFF       // Boot Block Write Protection bit (Boot block (000000-0007FFh) is not write-protected)
#pragma config WRTD = OFF       // Data EEPROM Write Protection bit (Data EEPROM is not write-protected)

// CONFIG7L
#pragma config EBTR0 = OFF      // Table Read Protection bit (Block 0 (000800-001FFFh) is not protected from table reads executed in other blocks)
#pragma config EBTR1 = OFF      // Table Read Protection bit (Block 1 (002000-003FFFh) is not protected from table reads executed in other blocks)
#pragma config EBTR2 = OFF      // Table Read Protection bit (Block 2 (004000-005FFFh) is not protected from table reads executed in other blocks)
#pragma config EBTR3 = OFF      // Table Read Protection bit (Block 3 (006000-007FFFh) is not protected from table reads executed in other blocks)

// CONFIG7H
#pragma config EBTRB = OFF      // Boot Block Table Read Protection bit (Boot block (000000-0007FFh) is not protected from table reads executed in other blocks)





system.h


Código: [Seleccionar]
/*
 * File:   system.h
 * Author: Ramiro
 *
 * Created on 23 de septiembre de 2013, 15:03
 */

#ifndef SYSTEM_H
#define SYSTEM_H

#ifdef __cplusplus
extern "C" {
#endif




#ifdef __cplusplus
}
#endif

#endif /* SYSTEM_H */

 #define _XTAL_FREQ 8000000

void ConfigureOscillator(void);



system.c


Código: [Seleccionar]
/*
 * File:   system.c
 * Author: Ramiro
 *
 * Created on 23 de septiembre de 2013, 15:08
 */

#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include "system.h"

void ConfigureOscillator(void)
{
 
    ADCON1 = 0x0f ; //todos los bits como digitales

     CMCONbits.CM0 = 1;
     CMCONbits.CM1 = 1; // deshabilito los comparadores
     CMCONbits.CM2 = 1;

     OSCCONbits.IRCF2 = 1; //
     OSCCONbits.IRCF1 = 1; // defino oscilador interno en 8 mhz
     OSCCONbits.IRCF0 = 1; //
}
Las Grandes Obras las sueñan los grandes locos , mientras los inutiles las critican !!

Desconectado Rseliman

  • PIC16
  • ***
  • Mensajes: 239
Re: Mini curso "Programación en XC8"
« Respuesta #153 en: 02 de Octubre de 2013, 13:30:41 »
Amigos ...ya encontre el problema de las coordenadas del lcd ...como siempre pasaba por alto parte del pdf ...los datos estan bien al comienzo del pdf del 5110 ...

Aplique una pequeña formula para que sea menos confuso ...entonces se puede tomar coordenadas reales ...la formula es la siguiente

elimine el gotoxy y agregue a la funcion sendstring las coordenadas ...quedando de esta manera

Código: [Seleccionar]
void LCD5110_sendstring(int x, int y, const char *str)
    {

    if (y == 1 ) y == 0 ;
    {
    x = (6*x)+y ;
    }
   LCD5110_send((0x80 | x) , 0); //X address
   LCD5110_send((0x40 | y) , 0); //Y address


    while (*str) // pass through each character
    {
        LCD5110_sendchar(*str); // and send it
        str++;
    }

y en el main llamo a la funcion de esta manera


Código: [Seleccionar]
   LCD5110_sendstring(4, 0, "Ramiro");
   LCD5110_sendstring(3,0, "Seliman");


Saludos ...espero a alguien le sirva ....


« Última modificación: 02 de Octubre de 2013, 16:26:48 por Rseliman »
Las Grandes Obras las sueñan los grandes locos , mientras los inutiles las critican !!

Desconectado jukinch

  • Colaborador
  • PIC24F
  • *****
  • Mensajes: 608
Re: Mini curso "Programación en XC8"
« Respuesta #154 en: 08 de Octubre de 2013, 09:38:02 »
Rodrigo: Como siempre gracias por compartir. :)

Leo:
    subí el video!  :)
En cuanto a lo de los includes estos:
#include "configuracion_de_fuses.c"
#include "configuracion_hard.c"

deberían incluirse y llamarse así.
 #include "configuracion_de_fuses.h"
 #include "configuracion_hard.h"

 Y renombrar los respectivos archivos que incluimos a su correspondiente *.h
 Si los dejás con *.c funcionan igual. Pero conceptualmente lo que debemos incluir son *.h para hacer de interfaz y los archivos *.c debemos compilarlos y luego linkearlos junto a los demás.
Estoy medio perdido en el foro por el laburo pero en cuanto pueda retomar volcaré lo que estudié y ampliaré el concepto ese en la guia que está unos post atrás.
Abrazo
         Jukinch


 
"Divide las dificultades que examinas en tantas partes como sea posible para su mejor solución." -René Descartes

Desconectado elgarbe

  • Moderadores
  • PIC24H
  • *****
  • Mensajes: 2178
Re: Mini curso "Programación en XC8"
« Respuesta #155 en: 08 de Octubre de 2013, 22:31:59 »
Hola, leo!!!

si, sabia lo de los .h, pero no tengo presente como compilar los .c aparte y linkearlos en el proyecto actual... recuerdo que en la facu hacíamos eso, incluso teniamos parte del codigo en asm y parte en c y compartian variables y todo, pero ya olvide como se hacía todo eso.

Tamien me pasó querer crear un archivo funciones.c y tratar de vincularlo al proyecto, pero no podía compilar. cuando lo saque del arbol de archivos fuentes en el proyecto se soluciono todo... eso es raro...

Saludos!
-
Leonardo Garberoglio

Desconectado Rseliman

  • PIC16
  • ***
  • Mensajes: 239
Re: Mini curso "Programación en XC8"
« Respuesta #156 en: 11 de Octubre de 2013, 14:38:27 »
Hola Muchachos !!! les hago una pregunta ....se podra usar en un 18f2550 ..el I2C y el SPI ..los dos a la ves ?? se podran conmutar o tendre que usar una subr por soft de i2c ??

Gracias
Las Grandes Obras las sueñan los grandes locos , mientras los inutiles las critican !!

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: Mini curso "Programación en XC8"
« Respuesta #157 en: 11 de Octubre de 2013, 14:53:49 »
  Se podría intentar apagar uno de los módulos cuando se vaya a utilizar el otro... Cuando hagas una comunicación I2C, el dispositivo SPI es casi seguro que no interpretará nada si es que usas una línea de habilitación. En el caso de hacer una comunicación SPI, habría que ver si las variaciones sobre las líneas SDA y SCL no son mal interpretadas por los dispositivos I2C que tengas en el bus.

  Puedes hacer algo sencillo con ambos tipos de dispositivos y simularlo en ISIS.
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: Mini curso "Programación en XC8"
« Respuesta #158 en: 15 de Noviembre de 2013, 11:02:13 »
  Dejo aquí este link (está aparte porque no sabía a qué resultado iba a llegar y no quería llenar de mensajes sin sentido éste hilo)   http://www.todopic.com.ar/foros/index.php?topic=41671.0 para quienes estén interesados en hacer pruebas con USB en XC8 y con el stack de microchip. Es simplemente unas pruebas que fui haciendo y funcionaron simulando en ISIS.
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado Miquel_S

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 1251
Re: Mini curso "Programación en XC8"
« Respuesta #159 en: 15 de Noviembre de 2013, 20:55:03 »
Hola, estoy intentando adaptar un codigo de RedPic a un Pic18F4550, pero no consigo entrar en la interrupcion y por mas que lo miro no consigo dar con el problema.
Alguien seria tan amable de ayudarme.
Código: C
  1. /*
  2.  * Ejemplo de movimiento de un servo
  3.  * LICENCIA GPL
  4.  *
  5.  * File:   main.c
  6.  * Author: Miquel Servera
  7.  * Microcontrolador: PIC18F4550
  8.  * Compiler:   XC8 v1.21
  9.  * Ide:    MPLABX v1.95
  10.  *
  11.  * Date:    10-11-2013
  12.  */
  13.  
  14. // Ejemplo con un servo FUTABA S3003
  15. // Alimentación y pulsos a 5V
  16. // Cuadro de Tiempos :
  17. // Periodo 20 ms (Frecuencia 50 Hz)
  18. // Ancho Pulso minimo 0.5 ms
  19. // Ancho pulso medio 1.5 ms
  20. // Ancho pulso maximo 2.5 ms
  21. // TMR0 a 1:256 -> 1 RTCC cada 3.99 ms
  22. // -> 1 Tick cada 3.99 / 256 = 0.015 ms
  23. // -> 20 ms = (5 x RTCC completas)
  24. // Ancho Pulso minimo 0.5 ms -> 31 ticks de TMR0
  25. // Ancho pulso medio 1.5 ms -> 93 ticks de TMR0
  26. // Ancho pulso maximo 2.5 ms -> 155 ticks de TMR0
  27.  
  28. #define _XTAL_FREQ 48000000
  29. #include <xc.h>
  30. #include <plib/timers.h>
  31.  
  32. #pragma config FOSC=HSPLL_HS, PLLDIV=3, CPUDIV=OSC1_PLL2
  33. #pragma config IESO=OFF, FCMEN=OFF
  34. #pragma config PWRT=OFF, BOR=OFF, BORV=3, VREGEN=ON, WDT=OFF
  35. #pragma config MCLRE=ON, XINST=OFF, LVP=OFF, PBADEN=OFF
  36.  
  37. /* Definir el bit del pulsador de pruebas*/
  38. #define PULSADOR       LATA0
  39.  
  40. /* Definir el bit del PWM para el servo*/
  41. #define PIN_SERVO1     LATB0
  42.  
  43. /* Constantes para determinar si pulsador esta apretado o no */
  44. #define ESTADO_ON             1
  45. #define ESTADO_OFF            0
  46.  
  47. /*******************************************************/
  48. /* Declaracion de Variables.*/
  49. /*******************************************************/
  50. unsigned char contadorRTCC = 0;
  51. unsigned char flagRTCC = 0;
  52. unsigned char flagSERVO1 = 0;
  53.  
  54. /**********************************************************************************/
  55. /* Declaración del prototipo de las funciones implementadas en el archivo fuente. */
  56. /**********************************************************************************/
  57. void interrupt low_priority interrupcionDeBaja(void);
  58. void main(void);
  59. //void WriteTimer0(unsigned int timer0);
  60. //unsigned int ReadTimer0(void);
  61.  
  62. /*******************************************************/
  63. /* RUTINA DE ATENCION A LAS INTERRUPCIONES             */
  64. /*******************************************************/
  65. void interrupt low_priority interrupcionDeBaja(void)
  66. {
  67. //-- INT_TMR0 = 4*1/FOSC*(256-VALORTIMER)*PRESCALER
  68. //-- INT_TMR0 = 4*1/48000000*(256-68)*256
  69. //-- INT_TMR0 = 0.000000083*188*256
  70. //-- INT_TMR0 = 0.00399 => 3.99ms
  71.     if(INTCONbits.TMR0IF){
  72.         ++contadorRTCC;
  73.             if(contadorRTCC == 5){
  74.                 flagRTCC = 1;
  75.                 contadorRTCC = 0x00;
  76.                 INTCONbits.TMR0IF = 0;
  77.             }
  78.     }
  79. }
  80.  
  81. void main(void)
  82. {
  83.     unsigned char ValorTIMER0;
  84.  
  85.     //-- Configurar el pulsador y servo
  86.     ADCON1 = 0X06;  //-- Configurar RA0-RB0 como digital
  87.     TRISA0 = 1;     //-- RA0 como entrada
  88.     TRISB0 = 0;     //-- RB0 como salida
  89.  
  90. //-- Configuración del timer & interrupcion
  91.     TMR0 = 68;
  92.     INTCONbits.TMR0IE = 1;  //-- Habilitamos interrupcion por desbordamiento del TMR0
  93.     RCONbits.IPEN = 1;      //-- Activa modo alta y baja prioridad
  94.     INTCONbits.GIEL = 1;    //-- Permitimos interrupciones de baja prioridad
  95.     INTCONbits.GIEH = 1;    //-- Permitimos interrupciones de alta prioridad
  96.     T0CONbits.T0PS0 = 1;    //-- Prescale value
  97.     T0CONbits.T0PS1 = 1;    //-- Prescale value
  98.     T0CONbits.T0PS2 = 1;    //-- Prescale value
  99.     T0CONbits.PSA = 0;      //-- Timer0 prescaler is assigned
  100.     T0CONbits.T08BIT = 1;   //-- Timer0 is configured as an 8-bit timer/counter
  101.     T0CONbits.TMR0ON = 1;   //-- Timer0 On/Off Control bit
  102.  
  103.     /* Bucle principal */
  104.     while(1){
  105.     //-- Disparo del Pulso
  106.         if(flagRTCC == 1){
  107.             flagRTCC = 0x00;
  108.             PIN_SERVO1 = 0x01;
  109.             flagSERVO1 = 1;
  110.         }
  111.  
  112.     //-- Control del ancho del Pulso
  113.         if(flagSERVO1 == 1){
  114.             ValorTIMER0 = ReadTimer0();
  115.             if(ValorTIMER0>93){
  116.                 flagSERVO1 = 0;
  117.                 PIN_SERVO1 = 0x00;
  118.             }
  119.         }
  120.     }
  121. }

Gracias!
Todos somos muy ignorantes. Lo que ocurre es que no todos ignoramos las mismas cosas.

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: Mini curso "Programación en XC8"
« Respuesta #160 en: 15 de Noviembre de 2013, 21:53:29 »
  Por defecto (luego de un PowerOnReset) el timer0 queda configurado en interrupción de alta prioridad y en tu programa lo quieres utilizar en el vector de baja prioridad. Te falta cambiar el bit TMR0IP del registro INTCON2.
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado Miquel_S

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 1251
Re: Mini curso "Programación en XC8"
« Respuesta #161 en: 16 de Noviembre de 2013, 07:08:20 »
Gracias por el dato AngelGris, se me paso por alto dicho bit pero sigue sin entrar en la interrupcion, me volvere a leer el datasheet y os cuento.
De todas formas voy a hacer un programa que sea una simple interrupcion, parpadeo de un led, nada mas para probar.

Saludos y Gracias de nuevo.
Todos somos muy ignorantes. Lo que ocurre es que no todos ignoramos las mismas cosas.

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: Mini curso "Programación en XC8"
« Respuesta #162 en: 16 de Noviembre de 2013, 10:36:41 »
Gracias por el dato AngelGris, se me paso por alto dicho bit pero sigue sin entrar en la interrupcion, me volvere a leer el datasheet y os cuento.
De todas formas voy a hacer un programa que sea una simple interrupcion, parpadeo de un led, nada mas para probar.

Saludos y Gracias de nuevo.

  Te falto seleccionar la fuente de clock para el timer, por defecto queda configurada la entrada por el pin T0CKI. Tienes que hacer 0 el bit TOCS del registro T0CON para que tome como fuente el clock de instrucción, es decir a la frecuencia que trabaja el núcleo.
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado Miquel_S

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 1251
Re: Mini curso "Programación en XC8"
« Respuesta #163 en: 16 de Noviembre de 2013, 14:02:46 »
Gracias AngelGris, ahora si, justo antes de leerte me había percatado de que faltaba dicho bit de configuración. Una pregunta que siempre me ronda, ¿Influye el orden con que configuras los bit de una interrupción?
Por ejemplo yo lo tengo así:
Código: C
  1. //-- Configuración del timer & interrupcion
  2.     TMR0 = 68;
  3.     INTCONbits.TMR0IE = 1;  //-- Habilitamos interrupcion por desbordamiento del TMR0
  4.     RCONbits.IPEN = 1;      //-- Activa modo alta y baja prioridad
  5.     INTCONbits.GIEL = 1;    //-- Permitimos interrupciones de baja prioridad
  6.     INTCONbits.GIEH = 1;    //-- Permitimos interrupciones de alta prioridad
  7.     INTCON2bits.TMR0IP = 0; //-- TMR0 Overflow Interrupt Priority bit
  8.     T0CONbits.T0PS0 = 1;    //-- Prescale value
  9.     T0CONbits.T0PS1 = 1;    //-- Prescale value
  10.     T0CONbits.T0PS2 = 1;    //-- Prescale value
  11.     T0CONbits.PSA = 0;      //-- Timer0 prescaler is assigned
  12.     T0CONbits.T08BIT = 1;   //-- Timer0 is configured as an 8-bit timer/counter
  13.     T0CONbits.T0CS = 0;     //-- Timer0 Clock Source Select bit
  14.     T0CONbits.TMR0ON = 1;   //-- Timer0 On/Off Control bit
Da lo mismo cual vaya primero.

Saludos!
Todos somos muy ignorantes. Lo que ocurre es que no todos ignoramos las mismas cosas.

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: Mini curso "Programación en XC8"
« Respuesta #164 en: 16 de Noviembre de 2013, 15:30:15 »
  Yo siempre tengo en cuenta que los últimos bits en habilitar sean GIEL y GIEH, y antes de ello borrar todos los flag para asegurarme que no se dispare ninguna en el momento de la habilitación general.
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas


 

anything