Autor Tema: Ahorrando memoria ram o gastando memoria ram?  (Leído 1868 veces)

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

Desconectado donvalles

  • PIC10
  • *
  • Mensajes: 35
Ahorrando memoria ram o gastando memoria ram?
« en: 06 de Septiembre de 2014, 20:30:21 »
Senõres, me di cuenta que necesito entender más y estuve mirando ejemplos  en ccs , pero no consigo entender cúal es el concepto que debo adoptar al programar en c para el pic. o sea para que crean variables globales si despues crean copias de las mismas.

ejemplo:
Código: C++
  1. //variables globales
  2. int vector[10]={1,2,3,4,5,6,7,8,9,10};    //delcaro vector com sus elemetos
  3. int u16_size=10;                          //declaro e inicializo
  4.  
  5. //prototipo y cuerpo de funcion
  6. void puntero(int *Array, int Tamanio)
  7. {
  8.         int i;
  9.         for(i=0; i<Tamanio ;i++)
  10.          Array[i]*=10;
  11. }
  12.  
  13.  
  14. //main
  15. int main()
  16. {
  17.         int i;
  18.         puntero(vector,u16_size); //ACA NO ENTIENDO, POR QUE PASAN VARIABLES SI EXISTEN GLOBALMENTE?

Este ejemplo es pequeño con una sola función llamada puntero , esta función tiene dos parametros uno pasado por referencia y el otro por valor, estos parametros SON GLOBALES, por que lo usan así? usando dos byte a más.
si ven en el ejemplo de ccs EX_CRC.c  van a encontrar que hace ahí también llamando a la función send_packet(packet_buffer, 5); donde sus parámetros son globales creando dos char (2 byte), uno es el puntero y el otro una varieble char, en resumen,ocupan dos byte de más sin necesidad,  no entiendo por que programan así? ocupando memoria RAM, la idea no es programar ocupando la menor memoria posible?. Lo único que se me ocurre es que cuando un programa con un gran código para no confundirse escriben los parámetros en la función para tener una mejor interpretación del software, entonces se sabe que dentro de la función vas a usar esas variables que están pasadas por referencia o por valor más las variables creadas dentro de la función y todas sus variables son conocidas, y dentro de la función no va a aparecer una varieble global de la nada y no sabemos que hace. No se, no se, me está dejando loco, les pido un poco de paciencia ya tengo muchos años así que cuesta un poco. Gracias por explicarme.

Desconectado PalitroqueZ

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 5474
    • Electrónica Didacta
Re: Ahorrando memoria ram o gastando memoria ram?
« Respuesta #1 en: 06 de Septiembre de 2014, 22:07:11 »
según entendí del código, es innecesario declarar Array como puntero si vas a usar una variable global (vector) para procesar dichos datos
La propiedad privada es la mayor garantía de libertad.
Friedrich August von Hayek

Desconectado donvalles

  • PIC10
  • *
  • Mensajes: 35
Re: Ahorrando memoria ram o gastando memoria ram?
« Respuesta #2 en: 07 de Septiembre de 2014, 00:50:20 »
fijense en el ejemplo de ccs, en la función send_packet(packet_buffer, 5); utiliza parametro que están declarados como GLOBAL como ser packet_buffer, entonces, por que que lo usa como parametro de una funcion si es global existe en todo el programa? si la función la puede usar sin necesidad de ser pasada por referencia ya que es global .... osea por que programan así utlizando memoria sin nececidad ?

Código: C++
  1. /////////////////////////////////////////////////////////////////////////
  2. ////                            EX_CRC.C                             ////
  3. ////                                                                 ////
  4. ////  This example program shows how to send messages between two    ////
  5. ////  PICs using CRC error checking.  Pushing a button on the        ////
  6. ////  prototype card sends a message from that PIC to any other PICs ////
  7. ////  that are connected.  The receiving PIC then sends back an ACK  ////
  8. ////  after it correctly receives the message.                       ////
  9. ////                                                                 ////
  10. ////  Two seperate PICs are needed for this example.  Compile the    ////
  11. ////  code as is and program the first PIC.  Then switch the         ////
  12. ////  MACHINE_ADDRESS and SEND_ADDRESS and program the second PIC.   ////
  13. ////                                                                 ////
  14. ////                                                                 ////
  15. ////  Packet Protocol:                                               ////
  16. ////  +------------+--------------+---------+--------+------+-----+  ////
  17. ////  | Address TO | Address FROM | Control | Length | Data | CRC |  ////
  18. ////  +------------+--------------+---------+--------+------+-----+  ////
  19. ////                                                                 ////
  20. ////  Address TO:    1 byte         Address of sending PIC           ////
  21. ////  Address FROM:  1 byte         Address of receiving PIC         ////
  22. ////  Control:       1 byte         Used for ACK and NACK            ////
  23. ////  Length:        2 bytes        Number of bytes in Data field    ////
  24. ////  Data:          0 to N bytes   Data being sent                  ////
  25. ////  CRC:           2 bytes        16 Bit CRC                       ////
  26. ////                                                                 ////
  27. ////  Configure the CCS prototype card as follows:                   ////
  28. ////     Jumper from PIC 1 pin B0 to PIC 2 pin B1                    ////
  29. ////     Jumper from PIC 1 pin B1 to PIC 2 pin B0                    ////
  30. ////     Jumper from PIC 1 GND to PIC 2 GND                          ////
  31. ////     Jumper from PIC 1 Switch to PIC 1 pin B2                    ////
  32. ////     Jumper from PIC 2 Switch to PIC 2 pin B2                    ////
  33. ////     See additional connections below.                           ////
  34. ////                                                                 ////
  35. ////  This example will work with the PCM and PCH compilers.  The    ////
  36. ////  following conditional compilation lines are used to include a  ////
  37. ////  valid device for each compiler.  Change the device, clock and  ////
  38. ////  RS232 pins for your hardware if needed.                        ////
  39. ////                                                                 ////
  40. /////////////////////////////////////////////////////////////////////////
  41. ////        (C) Copyright 1996,2003 Custom Computer Services         ////
  42. //// This source code may only be used by licensed users of the CCS  ////
  43. //// C compiler.  This source code may only be distributed to other  ////
  44. //// licensed users of the CCS C compiler.  No other use,            ////
  45. //// reproduction or distribution is permitted without written       ////
  46. //// permission.  Derivative programs created using this software    ////
  47. //// in object code form are not restricted in any way.              ////
  48. /////////////////////////////////////////////////////////////////////////
  49.  
  50.  
  51. #if defined(__PCM__)
  52. #include <16F877.H>
  53. #device *=16
  54. #fuses HS,NOWDT,NOPROTECT,NOLVP
  55. #use delay(clock=20000000)
  56. #use rs232(baud=9600, xmit=PIN_B1, rcv=PIN_B0)
  57.  
  58. #elif defined(__PCH__)
  59. #include <18F452.H>
  60. #fuses HS,NOWDT,NOPROTECT,NOLVP
  61. #use delay(clock=20000000)
  62. #use rs232(baud=9600, xmit=PIN_B1, rcv=PIN_B0)
  63. #endif
  64.  
  65. #include <crc.c>
  66.  
  67. // CONSTANTS
  68. #define MACHINE_ADDRESS 0x01
  69. #define SEND_ADDRESS    0x02
  70. #define ACK             0x01
  71. #define NACK            0xFF
  72. #define BUFFER_SIZE     64
  73.  
  74. // GLOBAL VARIABLES
  75. int packet_buffer[BUFFER_SIZE];
  76. int ext_buffer[BUFFER_SIZE];
  77. int ext_buffer_next_in;
  78. int ext_buffer_next_out;
  79.  
  80. #define MESSAGE_SEND    (!input(PIN_B2))
  81. #define DATA_IN         (ext_buffer_next_in != ext_buffer_next_out)
  82.  
  83.  
  84. // EXTERNAL INTERRUPT
  85. // function for reading in bytes from other PIC
  86. #INT_EXT
  87. void ext_isr()
  88. {
  89.    ext_buffer[ext_buffer_next_in] = getc();     // get a byte, put it in buffer
  90.  
  91.    if(++ext_buffer_next_in == BUFFER_SIZE)      // increment counter
  92.       ext_buffer_next_in = 0;
  93. }
  94.  
  95. // GET_BUFF_INT
  96. // function to extract bytes from the buffer
  97. int get_buff_int()
  98. {
  99.    int retval;
  100.  
  101.    while(!DATA_IN);                             // wait until data available
  102.  
  103.    retval = ext_buffer[ext_buffer_next_out];    // get the byte
  104.    if(++ext_buffer_next_out == BUFFER_SIZE)     // increment counter
  105.       ext_buffer_next_out = 0;
  106.  
  107.    return retval;
  108. }
  109.  
  110. // SEND_PACKET
  111. // function to send a packet of data to another PIC
  112. void send_packet(int* packet_ptr, int16 packet_length)
  113. {
  114.    int *ptr;
  115.    int16 CRC,i;
  116.  
  117.    ptr = packet_ptr;                            // set pointer
  118.  
  119.    CRC = generate_16bit_crc(ptr, packet_length, CRC_CCITT);
  120.                                                 // make CRC
  121.    for(i=0; i<packet_length; i++)               // send packet
  122.       putc(packet_ptr[i]);
  123.  
  124.    putc((int)(CRC>>8));                         // send CRC
  125.    putc((int)(CRC));
  126. }
  127.  
  128. // GET_PACKET
  129. // function to get a packet from the buffer and read the data
  130. short get_packet(int* packet_ptr)
  131. {
  132.    short retval;
  133.    int16 length;
  134.    int16 CRC;
  135.    int16 i;
  136.  
  137.    retval = TRUE;
  138.  
  139.    packet_ptr[0] = get_buff_int();              // get the address of send to
  140.    packet_ptr[1] = get_buff_int();              // get the address of send from
  141.  
  142.    if(packet_ptr[0] != MACHINE_ADDRESS)
  143.       retval = FALSE;
  144.  
  145.    packet_ptr[2] = get_buff_int();              // get the control byte
  146.    if(packet_ptr[2] == NACK)
  147.       retval = FALSE;
  148.  
  149.    packet_ptr[3] = get_buff_int();              // get the length of the data
  150.    packet_ptr[4] = get_buff_int();
  151.  
  152.    length = (int16)(packet_ptr[3])<<8;
  153.    length += packet_ptr[4];
  154.  
  155.    for(i=5; i<(length+5); i++)                  // get the data
  156.       packet_ptr[i] = get_buff_int();
  157.  
  158.    packet_ptr[length+5] = get_buff_int();       // get the CRC
  159.    packet_ptr[length+6] = get_buff_int();
  160.  
  161.    CRC = (int16)(packet_ptr[length+5])<<8;
  162.    CRC += packet_ptr[length+6];
  163.  
  164.    if(CRC != generate_16bit_crc(packet_ptr, length+5, CRC_CCITT))
  165.       retval = FALSE;
  166.  
  167.    return retval;
  168. }
  169.  
  170. // Change RS-232 IO pins
  171. #use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)  // Jumpers: 8 to 11, 6 to 14
  172.  
  173. void main()   {
  174.  
  175.    ext_buffer_next_in = 0;                      // init variables
  176.    ext_buffer_next_out = 0;
  177.  
  178.    ext_int_edge(H_TO_L);                        // init interrupts
  179.    enable_interrupts(INT_EXT);
  180.    enable_interrupts(GLOBAL);
  181.  
  182.    while(TRUE)                                  // loop always
  183.    {
  184.       if(MESSAGE_SEND)                          // if button pushed
  185.       {
  186.          packet_buffer[0] = SEND_ADDRESS;
  187.          packet_buffer[1] = MACHINE_ADDRESS;
  188.          packet_buffer[2] = 0;
  189.          packet_buffer[3] = 0;
  190.          packet_buffer[4] = 9;
  191.          packet_buffer[5] = 'H';
  192.          packet_buffer[6] = 'i';
  193.          packet_buffer[7] = ' ';
  194.          packet_buffer[8] = 't';
  195.          packet_buffer[9] = 'h';
  196.          packet_buffer[10] = 'e';
  197.          packet_buffer[11] = 'r';
  198.          packet_buffer[12] = 'e';
  199.          packet_buffer[13] = '!';
  200.          send_packet(packet_buffer, 14);        // send message
  201.       }
  202.  
  203.       delay_ms(100);
  204.  
  205.       if(!DATA_IN)                              // if no data in
  206.          continue;                              // loop back
  207.  
  208.       if(get_packet(packet_buffer))             // if valid packet
  209.       {
  210.          int16 length,i;
  211.          // int16 CRC;
  212.  
  213.          printf("Message from unit# %U\r\n",packet_buffer[1]);
  214.  
  215.          length = ((int16)(packet_buffer[3]<<8)) + packet_buffer[4];
  216.  
  217.          if(packet_buffer[2] == ACK)
  218.             printf("Previous message sent was received by unit.\r\n");
  219.  
  220.          if(length)                             // display message
  221.          {
  222.             printf("Message is:\r\n\n");
  223.             for(i=0; i<length; ++i)
  224.                putc(packet_buffer[i+5]);
  225.          }
  226.          printf("\r\n\n... Message End ...\r\n\n\n");
  227.  
  228.          if(length)
  229.          {
  230.             packet_buffer[0] = packet_buffer[1];//send an ACK
  231.             packet_buffer[1] = MACHINE_ADDRESS;
  232.             packet_buffer[2] = ACK;
  233.             packet_buffer[3] = 0;
  234.             packet_buffer[4] = 0;
  235.             send_packet(packet_buffer, 5);
  236.          }
  237.       }
  238.       else                                      // if not valid packet
  239.       {
  240.          if(packet_buffer[0] != MACHINE_ADDRESS)
  241.             break;                              // message is not for this PIC
  242.          else if(packet_buffer[2] == NACK)      // tried to send and failed error
  243.             printf("Previous message sent was not received by unit.\r\n");
  244.          else
  245.          {                                      // tried to receive and failed error
  246.             printf("Message received was corrupted.\r\n");
  247.  
  248.             packet_buffer[0] = packet_buffer[1];//send a NACK
  249.             packet_buffer[1] = MACHINE_ADDRESS;
  250.             packet_buffer[2] = NACK;
  251.             packet_buffer[3] = 0;
  252.             packet_buffer[4] = 0;
  253.             send_packet(packet_buffer, 5);
  254.          }
  255.       }
  256.    }
  257. }

Desconectado PalitroqueZ

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 5474
    • Electrónica Didacta
Re: Ahorrando memoria ram o gastando memoria ram?
« Respuesta #3 en: 07 de Septiembre de 2014, 12:38:23 »
ahora si entiendo tu punto, lo que pasa es que en el ejemplo ex_crc.c están usando una variable del tipo array y para no sobrecargar la función (porque están haciendo uso de parametros en la función send_packet) necesariamente deben usar punteros, se usa punteros en este caso para poder recorrer el array e ir leyendo/modificando datos en indices específicos.

supongo que deben existir otros modos de programar una trama con su propio protocolo en la transmisión de datos entre pic, pero así se lo ha inventado el que escribió el ejemplo ex_crc.c

La propiedad privada es la mayor garantía de libertad.
Friedrich August von Hayek

Desconectado RedPic

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 5544
    • Picmania by Redraven
Re: Ahorrando memoria ram o gastando memoria ram?
« Respuesta #4 en: 07 de Septiembre de 2014, 14:13:29 »
En la época en que estuve haciendo un firmware para el 18F4550 me vi en la necesidad de reducir al máximo el consumo de ROM y esta es una de las cosas que más usé: tenía RAM libre así que decidí declarar variables globales y no pasarlas como parámetros, ni siquiera como punteros (sólo 2 bytes), llamaba a las funciones sin parámetros y éstas procesaban las variables globales. La reducción de ocupación de ROM (y en cierto sentido de RAM) fueron espectaculares. Ya me cabían muchas más funciones que antes me hacían saltar el error de ROM insuficiente.  :mrgreen:
Contra la estupidez los propios dioses luchan en vano. Schiller
Mi Güeb : Picmania

Desconectado jhozate

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 1698
Re: Ahorrando memoria ram o gastando memoria ram?
« Respuesta #5 en: 07 de Septiembre de 2014, 14:23:19 »
yo la verdad (en mi poca experiencia) no he visto un ahorro significativo en el ahorro de memoria en el ccs, en cuanto a declaración de variables locales
Ser Colombiano es un Premio, Saludos desde CALI-COLOMBIA

Desconectado PalitroqueZ

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 5474
    • Electrónica Didacta
Re: Ahorrando memoria ram o gastando memoria ram?
« Respuesta #6 en: 07 de Septiembre de 2014, 15:46:29 »
yo alterno entre globales y locales, aunque ya me acostumbré a usar variables globales y dejo en void las entradas de la mayoría de las funciones. Total con micros de 8bits y un compilador que no es estandarizado poco importa las reglas modernas de la programación.  :shock:

La propiedad privada es la mayor garantía de libertad.
Friedrich August von Hayek

Desconectado jhozate

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 1698
Re: Ahorrando memoria ram o gastando memoria ram?
« Respuesta #7 en: 07 de Septiembre de 2014, 16:03:55 »
si  pedro, me paso usando el Atmel Studio, donde usando variables locales se ahorra memoria , en ccs parece que siempre se reserva el espacio.
Ser Colombiano es un Premio, Saludos desde CALI-COLOMBIA

Desconectado donvalles

  • PIC10
  • *
  • Mensajes: 35
Re: Ahorrando memoria ram o gastando memoria ram?
« Respuesta #8 en: 08 de Septiembre de 2014, 00:17:10 »
Ahora entendí , muchas gracias.


 

anything