Bootloader PIC18F2550 con CCS PIC C Compiler

Hace algunos dias me encuentro trabajando en el botloader para este pic , he buscado información el la red y he encontrado que el compilador CCS o mas conocido como pic C compiler ofrece un bootloader fabricado por ellos
acá hay una pagina de referencia

http://curiosidadesford.blogspot.com/2011/04/bootloader-hidcdc-para-pic18f2550.html

lo que hago es buscar e archivo fuente que según la pagina citada es Ex_usb_bootloader.c y lo compilo en un proyecto para 2550
la compilación es correcta si ningún error

B5C644AE4.png
luego de ello procedí a grabar este archivo con el pk2 como normalmente lo haría mediante e puerto ICSP, efectivamente el archivo se carga y cuando lo conecto al pc se reconoce como un nuevo dispocitivo USB y procedo a instalar los drivers del USB TO UART que asi se denomina el bootloader de ccs

el driver esta ubicado en directorio de instalación del compilador (C:\Archivos de programa\PICC\Drivers\NT,2000,XP,VISTA,7) efectivamente queda instalado de manera correcta .

hasta el momento el bootloader esta bn '
luego procedo a crear un programa sencillo con el cual busco hacer parpadear un led cada 1s
para ello inclui la librería (#INCLUDE "usb_bootloader.h")

y procedo a cargar el archivo con el CCSLOAD

474F33B74.jpg

selecciono el puerto rs232 y le doy COM 4 que fue donde quedo instalado el driver de
USB TO COM

pero no funciona sale este error ¡:confused:
C77E42B5A.jpg

espero que alguien tenga este bootloader y me diga que es lo que estoy haciendo mal ¡ porfavor :)
 
Al instalar el Ccs, a mi me crea una carpeta en archivos de programa llamada PICC, y además del compilador se instalan mas cosas. Pues dentro de esa carpeta hay un programa llamado Siow, serial input/output monitor. Cuando lo abres configuras la comunicación, el puerto que usas, la velocidad, etc... y después en la pestaña Download, eliges el .hex que quieres pasarle al PIC y te lo transfiere.
En el ejemplo "ex_usb_bootloader" es donde dice hacerlo así, y es como llevo tiempo haciendo:
Código:
This program must be loaded into a target chip using a device    ////
////  programmer.  Afterwards this program may be used to load new     ////
////  versions of the application program.  There is a specific        ////
////  protocol used by the bootloader, SIOW.EXE uses this protocol     ////
////  if you use the 'Download Software' option.

Un saludo y espero que tengas suerte.
 
Viejo gracias por su respuesta ya estoy un poco mas cerca de lograrlo ¡
la verdad creo que tengo problemas con el hadware

porque conecto el dispocitivo y instala el driver pero luego me sale una advertencia diciendo que no me reconoce el dispositivo
luego intento tocar la placa y lo reconoce en el com 2 , luego habro el siow en file y download sofware aparentemente ha cargado el archivo ..
el programa que cargo es este

Código:
#INCLUDE <18f2550.h>
#FUSES NOWDT, HS, NOPUT, NOPROTECT, NODEBUG, NOBROWNOUT, NOLVP, NOCPD, NOWRT
//#use delay(clock=4mhz)
#USE delay (clock=20mhz)
#INCLUDE "usb_bootloader.h"



VOID MAIN(VOID){
set_tris_b(0x00);
setup_adc_ports(NO_ANALOGS|VSS_VDD);
setup_adc(ADC_CLOCK_DIV_2);
WHILE(TRUE){
DELAY_MS(100);
OUTPUT_TOGGLE(PIN_b7);
}
}
no se si tenga algo mal en el código ps no hace nada ¡

Podría ayudarme diciéndome su hay alguna conexión en especial yo tengo un condensador de 10 uf a 50 v conectado al voltage usb y resistencias de 22hom a los pines de datos del pic
 
Un dato importante es que tienes que tener los mismos fuses en el bootloader que hayas cargado que en el programa que quieras cargar después

:aplauso::D

Mi viejo muchas gracias ¡ deverdad ya me funciono :apreton: espero pagarte el favor luego de alguna manera ¡
modifique el programa y coloque el pulsador en el pin A0
Código:
///////////////////////////////////////////////////////////////////////////
////                    EX_USB_BOOTLOADER.C                            ////
////                                                                   ////
////  This program is an example stand alone USB bootloader.  It uses  ////
////  the communication device class (CDC) that creates a virtual COM  ////
////  port on your PC.  The bootloader contains it's own set of USB    ////
////  and bootloader code in low memory, the high memory will contain  ////
////  the application (and if you are developing a USB application,    ////
////  this will hold it's own USB code).                               ////
////                                                                   ////
////  This program must be loaded into a target chip using a device    ////
////  programmer.  Afterwards this program may be used to load new     ////
////  versions of the application program.  There is a specific        ////
////  protocol used by the bootloader, SIOW.EXE uses this protocol     ////
////  if you use the 'Download Software' option.                       ////
////                                                                   ////
////  Compiling this program gives you a HEX file of just the loader.  ////
////  To load the application you have two choices: a.) use the loader ////
////  to load the application, or b.) merge the application HEX and    ////
////  loader HEX into one production HEX.  The #import() CCS command   ////
////  will help you perfrom the latter.  Be aware that if you do the   ////
////  former the PIC will get it's configuration bit settings (fuses)  ////
////  from the loader and not the application (this bootloader does    ////
////  not change the configuration bits)                               ////
////                                                                   ////
////  To create an application that is compatible with this loader     ////
////  simply #include usb_bootlaoder.h into your application.  This    ////
////  loader does support interrupts in your application.              ////
////                                                                   ////
////  This bootloader is designed to detect pin A4 low on reset (this  ////
////  is the push-button on the CCS USB Development kit).  If A4 is    ////
////  low it starts the USB CDC stack and checks for bootload          ////
////  information over USB.  Otherwise the application program is      ////
////  started.                                                         ////
////                                                                   ////
////  This is a port of ex_bootloader.c, which is a serial bootloader. ////
////  Since CDC makes it easy to port legacy applications, the         ////
////  previous example makes the bulk of this code.                    ////
////                                                                   ////
////  This example will work with the PCH compiler.  The               ////
////  following conditional compilation lines are used to include a    ////
////  valid device for each compiler.  Change the device, clock and    ////
////  RS232 pins for your hardware if needed.                          ////
////                                                                   ////
//// This file is part of CCS's PIC USB driver code.  See USB.H        ////
//// for more documentation and a list of examples.                    ////
////                                                                   ////
///////////////////////////////////////////////////////////////////////////
////                                                                   ////
//// VERSION HISTORY                                                   ////
////                                                                   ////
//// March 5th, 2009:                                                  ////
////   Cleanup for Wizard.                                             ////
////   PIC24 Initial release.                                          ////
////                                                                   ////
///////////////////////////////////////////////////////////////////////////
////        (C) Copyright 1996,2009 Custom Computer Services           ////
//// This source code may only be used by licensed users of the CCS    ////
//// C compiler.  This source code may only be distributed to other    ////
//// licensed users of the CCS C compiler.  No other use,              ////
//// reproduction or distribution is permitted without written         ////
//// permission.  Derivative programs created using this software      ////
//// in object code form are not restricted in any way.                ////
///////////////////////////////////////////////////////////////////////////

//set to 1 to use a PIC's internal USB Peripheral
//set to 0 to use a National USBN960x peripheral
#define __USB_PIC_PERIF__ 1

#if !defined(__PCH__)
 #error This bootloader written for PIC18
#endif

#if __USB_PIC_PERIF__

 #INCLUDE <18f2550.h>
#fuses HSPLL,NOMCLR,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL5,CPUDIV1,VREGEN,NOPBADEN
#USE delay (clock=20mhz)

  //configure a 20MHz crystal to operate at 48MHz, for 4550
/*  #include <18F4550.h>
  #fuses HSPLL,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL5,CPUDIV1,VREGEN

  //configure a 8MHz crystal to operate at 48MHz, for 67j50
  //#include <18F67J50.h>
  //#fuses H4_SW,NOXINST,NOWDT,NOSTVREN,NOFCMEN,NOIESO,NOPROTECT,NODEBUG,PLL2,NOCPUDIV
  
  #use delay(clock=48000000)*/
#else //use the National USBN960x peripheral
  #include <18F452.h>
  #fuses HS,NOWDT,NOPROTECT,NOLVP
  #use delay(clock=20000000)
#endif   //endif check to see which peripheral to use

/////////////////////////////////////////////////////////////////////////////
//
// If you are using a USB connection sense pin, define it here.  If you are
// not using connection sense, comment out this line.  Without connection
// sense you will not know if the device gets disconnected.
//       (connection sense should look like this:
//                             100k
//            VBUS-----+----/\/\/\/\/\----- (I/O PIN ON PIC)
//                     |
//                     +----/\/\/\/\/\-----GND
//                             100k
//        (where VBUS is pin1 of the USB connector)
//
/////////////////////////////////////////////////////////////////////////////
///only ccs's 18F4550 development kit has this pin
#if __USB_PIC_PERIF__ && defined(__PCH__)
 #define USB_CON_SENSE_PIN PIN_B2
#endif

#define LOADER_ISR 0x28
#build(interrupt=LOADER_ISR)

/*
 Configure, then load the bootloader definitions
*/
#define _bootloader
#include <usb_bootloader.h>

// Includes all USB code and interrupts, as well as the CDC API
#include <usb_cdc.h>


/*
 Goto the interrupt vector of the application.
*/
#org 0x08,0x17
void high_isr(void) 
{
   if (bit_test(g_InBootloader,0))
   {
    #ASM
     goto LOADER_ISR
    #ENDASM
   }
   else
   {
    #ASM
     goto APPLICATION_ISR
    #ENDASM
   }
}

#org 0x18,0x27
void low_isr(void) 
{
   if (bit_test(g_InBootloader,0))
   {
    #ASM
     goto LOADER_ISR+0x10
    #ENDASM
   }
   else
   {
    #ASM
     goto APPLICATION_ISR+0x10
    #ENDASM
   }
}

#define ROM_BLOCK_INVALID -1

int32 rom_block_start = ROM_BLOCK_INVALID;

#define EEPROM_ERASE_SIZE  getenv("FLASH_ERASE_SIZE")
int8 rom_block[EEPROM_ERASE_SIZE];

// see rom_w() documentation.  performs the flushing
void rom_w_flush(void)
{
   if (rom_block_start != ROM_BLOCK_INVALID)
   {
      erase_program_eeprom(rom_block_start);     //erase entire block
   
      write_program_memory(rom_block_start, rom_block, sizeof(rom_block));    //write modified block
      
      rom_block_start = ROM_BLOCK_INVALID;
   }
}

// see rom_w() documentation.  performs the writing
void rom_w_block(int32 location, char *src, int16 size)
{
   int32 block_start;
   int16 i,num;

   block_start = location & (~((int32)EEPROM_ERASE_SIZE-1));
      
   i = location - block_start;

   while (size) 
   {
      if (block_start != rom_block_start)
      {
         rom_w_flush();
         
         rom_block_start = block_start;
         
         read_program_memory(block_start, rom_block, sizeof(rom_block));  //read entire block to ram buffer
      }
      

      if (size>(EEPROM_ERASE_SIZE-i)) {num=EEPROM_ERASE_SIZE-i;} else {num=size;}

      memcpy(&rom_block[i], src, num);    //modify ram buffer

      src += num;
      block_start += EEPROM_ERASE_SIZE;
      i = 0;
      size -= num;
   }
}

// Write to Flash ROM.
//
// location - flash program memory address
// src - pointer to data to write
// size - number of bytes to write to flash
//
// Here is the sequence of events:
//   1.) Goes to the beginning of the first erase block for this address
//   2.) Reads n records to ram, where n is the PIC's flash erase size
//   3.) Erases block in flash
//   4.) Modifies block in RAM
//   5.) Writes changed block back to FLASH.  Writes in chunks defined by PIC's flash write size
//   6.) Goes back to step1 if there is still more data to be written
void rom_w(int32 location, char *src, int16 size)
{
   rom_w_block(location, src, size);
   rom_w_flush();
}

#define BUFFER_LEN_LOD 64

#define ACKLOD 0x06
#define XON    0x11
#define XOFF   0x13

// Convert two hex characters to a int8
unsigned int8 atoi_b16(char *s) 
{  
   char c;
   unsigned int8 result = 0;
   int i;

   for (i=0; i<2; i++,s++)  
   {
      c = *s;
      if (c >= 'A')
         result = 16*result + c - 'A' + 10;
      else
         result = 16*result + c - '0';         
   }

   return(result);
}

void load_program(void)
{
   int1  do_ACKLOD, done=FALSE;
   int8  checksum, line_type;
   int16 l_addr,h_addr=0;
   int8 to;
   int32 addr;
   int8  dataidx, i, count;
   int8  data[32];
   int  buffidx;
   char buffer[BUFFER_LEN_LOD];
   
   while (!done)  // Loop until the entire program is downloaded
   {
      usb_task();
      
      if (!usb_cdc_kbhit())
         continue;
         
      buffidx = 0;  // Read into the buffer until 0x0D ('\r') is received or the buffer is full
      to = 250;   //250 milliseconds
      do 
      {
         if (!usb_cdc_kbhit())
         {
            delay_ms(1);
            to--;
            if (!to)
               break;
         }
         else
            to = 250;
         i = usb_cdc_getc();
         buffer[buffidx++] = i;
      } while ( (i != 0x0D) && (i != 0x0A) && (buffidx <= BUFFER_LEN_LOD) );
            
      if (!to)
         continue;

      usb_cdc_putc(XOFF);  // Suspend sender

      do_ACKLOD = TRUE;

      // Only process data blocks that start with ':'
      if (buffer[0] == ':') 
      {
         count = atoi_b16 (&buffer[1]);  // Get the number of bytes from the buffer

         // Get the lower 16 bits of address
         l_addr = make16(atoi_b16(&buffer[3]),atoi_b16(&buffer[5]));

         line_type = atoi_b16 (&buffer[7]);

         addr = make32(h_addr,l_addr);

         checksum = 0;  // Sum the bytes to find the check sum value
         for (i=1; i<(buffidx-3); i+=2)
            checksum += atoi_b16 (&buffer[i]);
         checksum = 0xFF - checksum + 1;

         if (checksum != atoi_b16 (&buffer[buffidx-3]))
            do_ACKLOD = FALSE;
         else
         {
            // If the line type is 1, then data is done being sent
            if (line_type == 1) 
               done = TRUE;
            else if (line_type == 4)
               h_addr = make16(atoi_b16(&buffer[9]), atoi_b16(&buffer[11]));
            else if ((line_type == 0) && (addr >= (int32)APPLICATION_START) && (addr < ((int32)APPLICATION_END)))
            {
                  // Loops through all of the data and stores it in data
                  // The last 2 bytes are the check sum, hence buffidx-3
                  for (i = 9,dataidx=0; i < buffidx-3; i += 2)
                     data[dataidx++]=atoi_b16(&buffer[i]);
                       
                  rom_w_block(addr, data, count);
            }
         }
      }

      if (do_ACKLOD)
         usb_cdc_putc (ACKLOD);

      usb_cdc_putc(XON);
   }

   rom_w_flush();

   usb_cdc_putc (ACKLOD);
   usb_cdc_putc(XON);
   delay_ms(2000);   //give time for packet to flush
   reset_cpu();
}

void main(void) 
{
  #if (defined(__USB_87J50__) && (getenv("FUSE_SET:H4_SW")))
   #byte OSCTUNE = 0xF9B
   #bit PLLEN=OSCTUNE.6
   PLLEN = TRUE;
   delay_ms(250);
  #endif

   //we use PIN_A4 as an event to determine if we should start the USB CDC
   //bootloader.  if it is not low (button is not pressed) then goto the 
   //application, else if is low (button is pressed) then do the bootloader.
   if(!input(PIN_a0))
   {
      g_InBootloader = TRUE;
      usb_cdc_init();
      usb_init();
      while(!usb_enumerated());
      load_program();
   }

   g_InBootloader = FALSE;
   
  #ASM
   goto APPLICATION_START
  #ENDASM
}
 
hola,
estoy utilizando el usb bootloader de ccs y quiero usar rc4,rc5,rc6,rc7 que son los pines del rs-232 y usb, como io, hize un programa para parpadear todos los puertos pero estos cuatro pines no parpadean, alguien sabe porque?
 
darez ..hola que tal estoy empezando a involucrarme al bootloader y vi tus aportaciones que me parecieron importantes para mi iniciación, con este código pudiste hacer la comunicación', no se como buscar este código yo puse #include usb_bootloader.h y la lineas de codigo son diferente me pudieras ayudar a entender que pasa? en el CCS
 
darez ..hola que tal estoy empezando a involucrarme al bootloader y vi tus aportaciones que me parecieron importantes para mi iniciación, con este código pudiste hacer la comunicación', no se como buscar este código yo puse #include usb_bootloader.h y la lineas de codigo son diferente me pudieras ayudar a entender que pasa? en el CCS

hola mjug02

Colega este es un tema viejo , el bootloader que esta planteado tiene algunos bugs y errores :(
pero de igual manera investigando en Internet y con un poco de experiencia obtenida en ccs he logrado implementar un botloadre 100% funcional :aplauso:

mire el siguiente código esta diseñado para un pic 2550 con un cristal de 20 mhz

Código:
#include <18F4550.h>
#fuses HSPLL,NOWDT,NOPROTECT,NOLVP,NODEBUG,NOBROWNOUT,USBDIV,PLL2,CPUDIV1,VREGEN,PUT,NOMCLR
#use delay(clock=48000000)

#define  ON    output_high
#define  OFF   output_low

//#define  LedV  PIN_B0
//#define  LedR  PIN_B1

#define  BTLDR PIN_E3

#define LOADER_ISR 0x28
#build(interrupt=LOADER_ISR)

#define _bootloader
#include "usb/usb_bootloader.h"
#include "usb/usb_cdc.h"

#org 0x08,0x17
void high_isr(void) 
{
   if (bit_test(g_InBootloader,0))
   {
    #ASM
     goto LOADER_ISR
    #ENDASM
   }
   else
   {
    #ASM
     goto APPLICATION_ISR
    #ENDASM
   }
}

#org 0x18,0x27
void low_isr(void) 
{
   if (bit_test(g_InBootloader,0))
   {
    #ASM
     goto LOADER_ISR+0x10
    #ENDASM
   }
   else
   {
    #ASM
     goto APPLICATION_ISR+0x10
    #ENDASM
   }
}

#define ROM_BLOCK_INVALID -1

int32 rom_block_start = ROM_BLOCK_INVALID;

#define EEPROM_ERASE_SIZE  getenv("FLASH_ERASE_SIZE")
int8 rom_block[EEPROM_ERASE_SIZE];

void rom_w_flush(void)
{
   if (rom_block_start != ROM_BLOCK_INVALID)
   {
      erase_program_eeprom(rom_block_start);
   
      write_program_memory(rom_block_start, rom_block, sizeof(rom_block));
      
      rom_block_start = ROM_BLOCK_INVALID;
   }
}

void rom_w_block(int32 location, char *src, int16 size)
{
   int32 block_start;
   int16 i,num;

   block_start = location & (~((int32)EEPROM_ERASE_SIZE-1));
      
   i = location - block_start;

   while (size) 
   {
      if (block_start != rom_block_start)
      {
         rom_w_flush();
         
         rom_block_start = block_start;
         
         read_program_memory(block_start, rom_block, sizeof(rom_block));
      }   

      if (size>(EEPROM_ERASE_SIZE-i)) num=EEPROM_ERASE_SIZE-i;
      else num=size;

      memcpy(&rom_block[i], src, num);

      src += num;
      block_start += EEPROM_ERASE_SIZE;
      i = 0;
      size -= num;
   }
}

void rom_w(int32 location, char *src, int16 size)
{
   rom_w_block(location, src, size);
   rom_w_flush();
}

#define BUFFER_LEN_LOD 64

#define ACKLOD 0x06
#define XON    0x11
#define XOFF   0x13

unsigned int8 atoi_b16(char *s) 
{  
   char c;
   unsigned int8 result = 0;
   int i;

   for (i=0; i<2; i++,s++)  
   {
      c = *s;
      if (c >= 'A')
         result = 16*result + c - 'A' + 10;
      else
         result = 16*result + c - '0';         
   }

   return(result);
}

void load_program(void)
{
   int1  do_ACKLOD, done=FALSE;
   int8  checksum, line_type;
   int16 l_addr,h_addr=0;
   int8 to;
   int32 addr;
   int8  dataidx, i, count;
   int8  data[32];
   int  buffidx;
   char buffer[BUFFER_LEN_LOD];
   
   while (!done)
   {
      usb_task();
      
      if (!usb_cdc_kbhit())
         continue;
         
      buffidx = 0;
      to = 250;
      do 
      {
         if (!usb_cdc_kbhit())
         {
            delay_ms(1);
            to--;
            if (!to)
               break;
         }
         else
            to = 250;
         i = usb_cdc_getc();
         buffer[buffidx++] = i;
      } while ( (i != 0x0D) && (i != 0x0A) && (buffidx <= BUFFER_LEN_LOD) );
            
      if (!to)
         continue;

      usb_cdc_putc(XOFF);

      do_ACKLOD = TRUE;

      if (buffer[0] == ':') 
      {
         count = atoi_b16 (&buffer[1]);

         l_addr = make16(atoi_b16(&buffer[3]),atoi_b16(&buffer[5]));

         line_type = atoi_b16 (&buffer[7]);

         addr = make32(h_addr,l_addr);

         checksum = 0;
         for (i=1; i<(buffidx-3); i+=2)
            checksum += atoi_b16 (&buffer[i]);
         
         checksum = 0xFF - checksum + 1;

         if (checksum != atoi_b16 (&buffer[buffidx-3]))
            do_ACKLOD = FALSE;
         else
         {
            if (line_type == 1) 
               done = TRUE;
            else if (line_type == 4)
               h_addr = make16(atoi_b16(&buffer[9]), atoi_b16(&buffer[11]));
            else if ((line_type == 0) && (addr >= (int32)APPLICATION_START) && (addr < ((int32)APPLICATION_END)))
            {
               for (i = 9,dataidx=0; i < buffidx-3; i += 2)
                  data[dataidx++]=atoi_b16(&buffer[i]);
                       
               rom_w_block(addr, data, count);
            }
         }
      }

      if (do_ACKLOD) usb_cdc_putc (ACKLOD);

      usb_cdc_putc(XON);
   }

   rom_w_flush();

   usb_cdc_putc (ACKLOD);
   usb_cdc_putc(XON);
   delay_ms(100);
   #zero_ram
   reset_cpu();
}

void main(void) 
{
   if(!input(BTLDR))
   {
      //ON(LEDR);ON(LEDV);
      g_InBootloader = TRUE;
      usb_cdc_init();
      usb_init();
      while(!usb_enumerated());
      load_program();
   }
   g_InBootloader = FALSE;
   
   #ASM
      goto APPLICATION_START
   #ENDASM
}

con este código creas el proyecto en ccs generas el .hex el cual podrá grabar con el pk2
si te fijas en la linea 6 del condigo encontraras la siguiente instrucción "#define BTLDR PIN_E3" en la cuaal pordra modificar el pulsador para acceder al modo Bootloader
el pulsador debe estar con una resistencia normalmente a 5volt y cuando presiones debe enviar un cero
puedes intentarlo hasta aca mas mas luego escribo mas info de esto y te paso links de información con respecto a este tema :D
 
Última edición por un moderador:
Hola Darez, te hago una consulta, vi que subiste el codigo de un bootloader pero hace referencia a archivos que no estan, y ademas decis que es para 18f2550 pero se incluye el .h del 18f4550. Te pido si podes subir el proyecto completo de tu bootloader que funciona, el hardware y con que programa se cargan las aplicaciones de usuario.
En realidad tengo una aplicación ya armada con 18F4550 y me gustaría que se pudiera actualizar por usb, pero solo me queda el pin E0 desocupado lo otro lo uso todo. Por eso sería importante conocer el codigo del bootloader para modificarle el mdo de entrada al bootloader y sacarle todo tipo de led de indicación de modo y eso.
Espero que me des una mano, y desde ya gracias por los aportes...(y)
 
Hola Darez, te hago una consulta, vi que subiste el codigo de un bootloader pero hace referencia a archivos que no estan, y ademas decis que es para 18f2550 pero se incluye el .h del 18f4550. Te pido si podes subir el proyecto completo de tu bootloader que funciona, el hardware y con que programa se cargan las aplicaciones de usuario.
En realidad tengo una aplicación ya armada con 18F4550 y me gustaría que se pudiera actualizar por usb, pero solo me queda el pin E0 desocupado lo otro lo uso todo. Por eso sería importante conocer el codigo del bootloader para modificarle el mdo de entrada al bootloader y sacarle todo tipo de led de indicación de modo y eso.
Espero que me des una mano, y desde ya gracias por los aportes...(y)

Teoricamente los bits de configuracion son los mismos :D esete codigo funciona tanto para 2550 y 4550 ¡ solo es cambiar el #include<"Pic">
claro esta para pics gama 18 con usb ¡
Mañana o mas adelante con buen tiempo subiré los archivos o el proyecto completo :cool:
 
Teoricamente los bits de configuracion son los mismos :D esete codigo funciona tanto para 2550 y 4550 ¡ solo es cambiar el #include<"Pic">
claro esta para pics gama 18 con usb ¡
Mañana o mas adelante con buen tiempo subiré los archivos o el proyecto completo :cool:

Hola Darez, ya se que para cambiar el pic solo cambio el define, mi problema para poder probar tu codigo es los archivos:
"usb/usb_bootloader.h"
"usb/usb_cdc.h"
Son los del CCS?
Saludos
 
Hola a todos, desde hace varios dias he intentado usar un bootloader en mi pic18f2550 para cargar firmware sin necesidad de un programador...pero no he tenido exito, si compila bien el bootloader en CCS y lo cargo por ICSP al pic y hasta ahi todo bien, pero al conectar el cable usb a la PC, no lo reconoce... oprimo el boton de boot antes de conectarlo a la PC y si entra en modo boot porque prende el LED, pero la PC no hace nada..

les dejo el código del bootloader que me encontre aki en el foro, del amigo DAREZ de un tema muy viejo referente a lo mismo... este es el bootloader que estoy utilizando

Código:
#include "18F2550.h"
#fuses HSPLL,NOWDT,NOPROTECT,NOLVP,NODEBUG,NOBROWNOUT,USBDIV,PLL5,CPUDIV2,VREGEN,PUT,MCLR
#use delay(clock=48000000)

#define  ON    output_high
#define  OFF   output_low
#define  LEDR  PIN_C1
#define  BTLDR PIN_C2

#define LOADER_ISR 0x28
#build(interrupt=LOADER_ISR)

#define _bootloader
#include "usb_bootloader.h"
#include "usb_cdc.h"

#org 0x08,0x17
void high_isr(void) 
{
   if (bit_test(g_InBootloader,0))
   {
    #ASM
     goto LOADER_ISR
    #ENDASM
   }
   else
   {
    #ASM
     goto APPLICATION_ISR
    #ENDASM
   }
}

#org 0x18,0x27
void low_isr(void) 
{
   if (bit_test(g_InBootloader,0))
   {
    #ASM
     goto LOADER_ISR+0x10
    #ENDASM
   }
   else
   {
    #ASM
     goto APPLICATION_ISR+0x10
    #ENDASM
   }
}

#define ROM_BLOCK_INVALID -1

int32 rom_block_start = ROM_BLOCK_INVALID;

#define EEPROM_ERASE_SIZE  getenv("FLASH_ERASE_SIZE")
int8 rom_block[EEPROM_ERASE_SIZE];

void rom_w_flush(void)
{
   if (rom_block_start != ROM_BLOCK_INVALID)
   {
      erase_program_eeprom(rom_block_start);
   
      write_program_memory(rom_block_start, rom_block, sizeof(rom_block));
      
      rom_block_start = ROM_BLOCK_INVALID;
   }
}

void rom_w_block(int32 location, char *src, int16 size)
{
   int32 block_start;
   int16 i,num;

   block_start = location & (~((int32)EEPROM_ERASE_SIZE-1));
      
   i = location - block_start;

   while (size) 
   {
      if (block_start != rom_block_start)
      {
         rom_w_flush();
         
         rom_block_start = block_start;
         
         read_program_memory(block_start, rom_block, sizeof(rom_block));
      }   

      if (size>(EEPROM_ERASE_SIZE-i)) num=EEPROM_ERASE_SIZE-i;
      else num=size;

      memcpy(&rom_block[i], src, num);

      src += num;
      block_start += EEPROM_ERASE_SIZE;
      i = 0;
      size -= num;
   }
}

void rom_w(int32 location, char *src, int16 size)
{
   rom_w_block(location, src, size);
   rom_w_flush();
}

#define BUFFER_LEN_LOD 64

#define ACKLOD 0x06
#define XON    0x11
#define XOFF   0x13

unsigned int8 atoi_b16(char *s) 
{  
   char c;
   unsigned int8 result = 0;
   int i;

   for (i=0; i<2; i++,s++)  
   {
      c = *s;
      if (c >= 'A')
         result = 16*result + c - 'A' + 10;
      else
         result = 16*result + c - '0';         
   }

   return(result);
}

void load_program(void)
{
   int1  do_ACKLOD, done=FALSE;
   int8  checksum, line_type;
   int16 l_addr,h_addr=0;
   int8 to;
   int32 addr;
   int8  dataidx, i, count;
   int8  data[32];
   int  buffidx;
   char buffer[BUFFER_LEN_LOD];
   
   while (!done)
   {
      usb_task();
      
      if (!usb_cdc_kbhit())
         continue;
         
      buffidx = 0;
      to = 250;
      do 
      {
         if (!usb_cdc_kbhit())
         {
            delay_ms(1);
            to--;
            if (!to)
               break;
         }
         else
            to = 250;
         i = usb_cdc_getc();
         buffer[buffidx++] = i;
      } while ( (i != 0x0D) && (i != 0x0A) && (buffidx <= BUFFER_LEN_LOD) );
            
      if (!to)
         continue;

      usb_cdc_putc(XOFF);

      do_ACKLOD = TRUE;

      if (buffer[0] == ':') 
      {
         count = atoi_b16 (&buffer[1]);

         l_addr = make16(atoi_b16(&buffer[3]),atoi_b16(&buffer[5]));

         line_type = atoi_b16 (&buffer[7]);

         addr = make32(h_addr,l_addr);

         checksum = 0;
         for (i=1; i<(buffidx-3); i+=2)
            checksum += atoi_b16 (&buffer[i]);
         
         checksum = 0xFF - checksum + 1;

         if (checksum != atoi_b16 (&buffer[buffidx-3]))
            do_ACKLOD = FALSE;
         else
         {
            if (line_type == 1) 
               done = TRUE;
            else if (line_type == 4)
               h_addr = make16(atoi_b16(&buffer[9]), atoi_b16(&buffer[11]));
            else if ((line_type == 0) && (addr >= (int32)APPLICATION_START) && (addr < ((int32)APPLICATION_END)))
            {
               for (i = 9,dataidx=0; i < buffidx-3; i += 2)
                  data[dataidx++]=atoi_b16(&buffer[i]);
                       
               rom_w_block(addr, data, count);
            }
         }
      }

      if (do_ACKLOD) usb_cdc_putc (ACKLOD);

      usb_cdc_putc(XON);
   }

   rom_w_flush();

   usb_cdc_putc (ACKLOD);
   usb_cdc_putc(XON);
   delay_ms(100);
   #zero_ram
   reset_cpu();
}

void main(void) 
{
   if(!input(BTLDR))
   {
      ON(LEDR);
      g_InBootloader = TRUE;
      usb_cdc_init();
      usb_init();
      while(!usb_enumerated());
      load_program();
   }
   g_InBootloader = FALSE;
   OFF(LEDR);
   #ASM
      goto APPLICATION_START
   #ENDASM
}

y el siguiente codigo es el USB_BOOTLOADER.H al que hace referencia, aunque tengo dudas en las direcciones de memoria... checando el datasheet del pic18f2550 empieza en la 0x0000 y termina en la 0x7FFF.. y en el bootloader tiene 0x1FFFF, hay alguna diferencia?

Código:
///////////////////////////////////////////////////////////////////////////
////                                                                   ////
////                     USB_BOOTLOADER.H                              ////
////                                                                   ////
////  This include file must be included by any application loaded     ////
////  by the example USB bootloader (ex_usb_bootloader                 ////
////                                                                   ////
////  The directives in this file relocate the reset and interrupt     ////
////  vectors as well as reserving space for the bootloader.           ////
////                                                                   ////
////  For more documentation see ex_usb_bootloader.c                   ////
////                                                                   ////
///////////////////////////////////////////////////////////////////////////
////                                                                   ////
//// VERSION HISTORY                                                   ////
////                                                                   ////
//// March 5th, 2009:                                                  ////
////   Cleanup for Wizard.                                             ////
////   PIC24 Initial release.                                          ////
////                                                                   ////
///////////////////////////////////////////////////////////////////////////
////        (C) Copyright 1996,2009 Custom Computer Services           ////
//// This source code may only be used by licensed users of the CCS    ////
//// C compiler.  This source code may only be distributed to other    ////
//// licensed users of the CCS C compiler.  No other use,              ////
//// reproduction or distribution is permitted without written         ////
//// permission.  Derivative programs created using this software      ////
//// in object code form are not restricted in any way.                ////
///////////////////////////////////////////////////////////////////////////

//how big is the bootloader?
//the bootloader will reside from address 0x0000 to this location.  the
//application will then sit at this location+1 to the end of program memory.
//#if defined(__DEBUG)
#define LOADER_SIZE        (0x1FFF)
//#else
//#define LOADER_SIZE        (0x17FF)
//#endif

//the loader and application need a common flag that determines if we are in
//the bootloader or application, that way the ISR knows where to go.  this
//is the location in ram that is reserved for this flag.
#define LOC_IN_LOADER_FLAG  0x25

//// --- end configuration --- ////////////////////////////////////////////

#reserve LOC_IN_LOADER_FLAG

int8 g_InBootloader;
#locate g_InBootloader=LOC_IN_LOADER_FLAG

#define LOADER_START       (0)
#define LOADER_END         (LOADER_SIZE)
#define APPLICATION_START  (LOADER_SIZE+1)
#if defined(__USB_87J50__)
 #define APPLICATION_END    (getenv("PROGRAM_MEMORY")-9) //configuration bits
#else
 #define APPLICATION_END    (getenv("PROGRAM_MEMORY")-1)
#endif 
#define APPLICATION_ISR    (APPLICATION_START+8)

#ifdef _bootloader
 /*
  Provide an empty application, so if you load this .HEX file into the pic
  without an application this will prevent the pic from executing unknown code.
 */
 #org APPLICATION_START,APPLICATION_START+0xF
 void BlankApplication(void) 
 {
   while(TRUE);
 }

 //we need to prevent the loader from using application space
 #if (APPLICATION_END > 0x10000)
   #org APPLICATION_START+0x10, 0xFFFF {}
   #if (APPLICATION_END > 0x20000)
      #org 0x10000, 0x1FFFF {}
      #org 0x20000, APPLICATION_END {}
   #else
      #org 0x10000, APPLICATION_END {}
   #endif
 #else
   #org APPLICATION_START+0x10, APPLICATION_END {}
 #endif

   #define  USB_CONFIG_PID       0x0034

   #define USB_STRINGS_OVERWRITTEN
   char USB_STRING_DESC_OFFSET[]={0,4,12};

   // Here is where the "CCS" Manufacturer string and "SERIAL DEMO" are stored.
   // Strings are saved as unicode.
   // These strings are mostly only displayed during the add hardware wizard.
   // Once the operating system drivers have been installed it will usually display
   // the name from the drivers .INF.
   char const USB_STRING_DESC[]={
      //string 0
            4, //length of string index
            0x03, //USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
            0x09,0x04,   //Microsoft Defined for US-English
      //string 1  - manufacturer
            8, //length of string index
            0x03, //USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
            'C',0,
            'C',0,
            'S',0,
      //string 2 - product
            30, //length of string index
            0x03, //USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
            'C',0,
            'D',0,
            'C',0,
            ' ',0,
            'B',0,
            'o',0,
            'o',0,
            't',0,
            'l',0,
            'o',0,
            'a',0,
            'd',0,
            'e',0,
            'r',0
   };
#endif   //_bootloader

#ifndef _bootloader
 //in the application, this moves the reset and isr vector out of the bootload
 //space.  it then reserves the loader space from being used by the application.
 #build(reset=APPLICATION_START, interrupt=APPLICATION_ISR)
 #org 0, LOADER_END {}
#endif

tambien les comento que mi diagrama únicamente tiene un cristal de 20Mhz, el pic, R1 del MCLR, Boton de reset, boton de Boot, y un led indicador, cable USB (rojo=5vcd,verde=D+,blanco=D-,negro=GND), un capacitor de 100nf del pin VBUS del pic a GND...

QUE PODRE ESTAR HACIENDO MAL? :cry:
hay que modificar las direcciones de memoria?
porque la pc no lo detecta?
ya habia instalado anteriormente un driver y quedo en el COM13, pero solo funcionó una vez y desde entonces ya no aparece ni el puerto ni el dispositivo... :confused::confused::confused:
pero se supone que es HID entonces no necesito drivers?:rolleyes:
aun asi, probe conectandolo a otra PC que no sabe de mi existencia y de igual manera, no pasa nada, no lo detecta aunque entre en modo bootloader desde el pic.

por favor, de antemano gracias por la atención y espero alguien pueda ayudarme. saludos:apreton:
 
les comento que mi diagrama únicamente tiene un cristal de 20Mhz, el pic, R1 del MCLR, botón de reset, botón de Boot, y un led indicador, cable USB (rojo=5vcd,verde=D+,blanco=D-,negro=GND), un capacitor de 100nf del pin VBUS del pic a GND.
Si estás usando un cristal de 20MHz. para llevar el CPU a 48MHz, entonces tienes mal la palabra de configuración.

Usa esta:
#fuses hspll, cpudiv1, pll5, nobrownout, nopbaden, nolvp
#use delay(clock = 48MHz)


Suerte.
 
Si estás usando un cristal de 20MHz. para llevar el CPU a 48MHz, entonces tienes mal la palabra de configuración.

Usa esta:
#fuses hspll, cpudiv1, pll5, nobrownout, nopbaden, nolvp
#use delay(clock = 48MHz)


Suerte.

gracias por tu pronta respuesta Darkbytes pero sigue sin funcionar.. si entra el modo bootloader pero la PC no detecta el dispositivo... otra pregunta: tiene que llevar USBDIV, no? debido a que el periferico es de 48MHz, de todos modos lo probe sin USBDIV y con USBDIV y sigue igual... no lo detecta ninguna PC... que podrá ser?:confused::confused::confused:
 
Atrás
Arriba