Autor Tema: Mis experiencias con el BUS CAN  (Leído 894604 veces)

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

Desconectado MGLSOFT

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 7907
Re: Mis experiencias con el BUS CAN - La Norma de Bosch
« Respuesta #60 en: 10 de Noviembre de 2007, 13:48:18 »
Aqui encontrarán la Norma de Robert Bosch, creador del BUS CAN.

CAN2SPEC

Gracias por las flores PICMOUSE, viniendo de ti es un halago!! :mrgreen:
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado MGLSOFT

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 7907
Re: Mis experiencias con el BUS CAN
« Respuesta #61 en: 11 de Noviembre de 2007, 01:17:38 »
Bueno, anduve enloquecido hasta ahora porque no me andaba el LCD, y como siempre aparecio mi Musa inspiradora, el amigo PIKMAN y encontre el problema...
Gracias PIKMAN (ariel) por tu inspiracion!!! :-/ :-/
Y tu ayuda tambien, que te perdiste un rato y se que estabas haciendo tus cosas, y generosamente me dedicaste un rato a mi... :idea: :idea:

El problema es que solde tiras de zocalo, a falta de poder insertar bien el zocalo de 28 pines dentro del de 40 (para tener ambas posibilidades) y me quedo haciendo falso contacto...

Alli radicaba el problema de mi display y a veces de interrupciones del CAN (que no podia explicarme de donde venian)...

Mañana le dedico tiempo a desarrollar el tema software, ahora que no tengo (creo) mas problemas de hardware... :mrgreen: :mrgreen:
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado MGLSOFT

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 7907
Mis experiencias con el BUS CAN- Configurando la velocidad
« Respuesta #62 en: 11 de Noviembre de 2007, 22:49:50 »
Bueno, antes mostré como utilizando un programa libre se obtenían los valores a ingresar en el bus para funcionar a la velocidad deseada.

Ahora mostraré el tramo de la libreria de CCS que configura la velocidad, para luego mostrar cual es la forma mas directa utilizada por mí para setear los valores de configuración.

La librería CCS declara cada uno de los valores de configuración en forma separada, utilizandolos luego como parte de una estructura, que es enviada al PIC o al MCP2515.
Aqui vemos la declaración de estos valores:
Código: C
  1. #IFNDEF CAN_BRG_PRESCALAR
  2.   #define CAN_BRG_PRESCALAR  4  //baud rate generator prescalar (def: 4) ( Tq = (2 x (PRE + 1))/Fosc )
  3. #ENDIF
  4.  
  5. #ifndef CAN_BRG_SEG_2_PHASE_TS
  6.  #define CAN_BRG_SEG_2_PHASE_TS   TRUE //phase segment 2 time select bit (def: freely programmable)
  7. #endif
  8.  
  9. #ifndef CAN_BRG_SAM
  10.  #define CAN_BRG_SAM 0 //sample of the can bus line (def: bus line is sampled 1 times prior to sample point)
  11. #endif
  12.  
  13. #ifndef CAN_BRG_PHASE_SEGMENT_1
  14.  #define CAN_BRG_PHASE_SEGMENT_1  5 //phase segment 1 (def: 6 x Tq)
  15. #endif
  16.  
  17. #ifndef CAN_BRG_PROPAGATION_TIME
  18.  #define CAN_BRG_PROPAGATION_TIME 2 //propagation time select (def: 3 x Tq)
  19. #endif
  20.  
  21. #ifndef CAN_BRG_WAKE_FILTER
  22.  #define CAN_BRG_WAKE_FILTER FALSE   //selects can bus line filter for wake up bit
  23. #endif
  24.  
  25. #ifndef CAN_BRG_PHASE_SEGMENT_2
  26.  #define CAN_BRG_PHASE_SEGMENT_2 5 //phase segment 2 time select (def: 6 x Tq)
  27. #endif
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado MGLSOFT

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 7907
Mis experiencias con el BUS CAN- Estructuras de configuración
« Respuesta #63 en: 11 de Noviembre de 2007, 22:53:16 »
Esos valores luego son utilizados en estas estructuras, declaradas en el archivo .h de su librería:

Código: C
  1. ////////////////////////////////////////////////////////////////////////////////
  2. /////////////////////// Baud Control Registers /////////////////////////////////
  3. ////////////////////////////////////////////////////////////////////////////////
  4.  
  5. //baud rate control register 1
  6. struct {
  7.         int brp:6;      //0:5   //baud rate prescalar
  8.         int sjw:2;      //6:7   //synchronized jump width
  9. } BRGCON1;
  10. #byte BRGCON1=0xF70
  11.  
  12. //baud rate control register 2
  13. struct {
  14.         int prseg:3; //0:2 //propagation time select
  15.         int seg1ph:3; //3:5 //phase segment 1
  16.         int1 sam; //6 //sample of the can bus line
  17.         int1 seg2phts; //7 //phase segment 2 time select
  18. } BRGCON2;
  19. #byte BRGCON2=0xF71
  20.  
  21. //baud rate control register 3
  22. struct {
  23.         int seg2ph:3;   //0:2   //phase segment 2 time select
  24.         int void543:3;  //3:5
  25.         int1 wakfil;    //6 //selects can bus line filter for wake-up
  26.         int1 void7;     //7
  27. } BRGCON3;
  28. #byte BRGCON3=0xF72
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado MGLSOFT

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 7907
Mis experiencias con el BUS CAN - Uso de estructuras al configurar
« Respuesta #64 en: 11 de Noviembre de 2007, 23:01:53 »
Una vez declaradas las estructuras la librería utiliza estas estructuras para configurar la velocidad.

Código: C
  1. ////////////////////////////////////////////////////////////////////////
  2. //
  3. // can_set_baud()
  4. //
  5. // Configures the baud rate control registers.  All the defines here
  6. // are defaulted in the can-18xxx8.h file.  These defaults can, and
  7. // probably should, be overwritten in the main code.
  8. //
  9. // Current defaults are set to work with Microchip's MCP250xxx CAN
  10. // Developers Kit if this PIC is running at 20Mhz.
  11. //
  12. //      BRGCON1 contains the prescaler bits and the Synchronization jump
  13. //                width time bits.
  14. //
  15. //                        the prescale values are
  16. //                                111111=(2*64)/clock=Tq
  17. //                                111110=(2*63)/clock=Tq
  18. //                                       continued
  19. //                                000001=(2*2)/clock=Tq
  20. //                                000000=(2*1)/clock=Tq
  21. //
  22. //                        in the case of can-18xxx8.h, the prescale bits are set to
  23. //                        000100=10/clock profided that the user does not define it
  24. //                        differently
  25. //
  26. //                   The Synchronized Jump Width Bits are
  27. //                                11=4*Tq
  28. //                                10=3*Tq
  29. //                                01=2*Tq
  30. //                00=1*Tq
  31. //
  32. //                        in the case of can-18xxx8.h, the SJW bits are set to 0 or 1*Tq
  33. //
  34. //      BRGCON2 contains the Phase Segment 2 Time Select bit, the SAMple bit
  35. //                the Phase Segment 1 bits, and the Propagation Time Select bits
  36. //
  37. //                        SEG2PHTS
  38. //                                1=Freely Programmable
  39. //                                0=Maximum of PHEG1 or IPT, which ever is greatest
  40. //
  41. //                        in the case of can-18xxx8.h, the SEG2PHTS bit is set to 1 for
  42. //                        freely programmable
  43. //
  44. //                        SAM
  45. //                                1=Three Samples
  46. //                                0=One Sample
  47. //
  48. //                        in the case of can-18xxx8.h, the SAM bit is set to 0 for
  49. //                        one sample
  50. //
  51. //                        SEG1PH2:SEG1PH0
  52. //                                Phase Segment 1 = (SEG1PH2:SEG1PH0+1)*Tq
  53. //
  54. //                        in the case of can-18xxx8.h, the SEG1PH2:SEG1PH0 bits are set to 5
  55. //         for 6*Tq Phase Segment 1 Time
  56. //
  57. //                        PRSEG2:PRSEG0
  58. //                           Propogation Time = (PRSEG2:PRSEG0+1)*TQ
  59. //
  60. //                        in the case of can-18xxx8.h, the PRSEG2:PRSEG0 bits are set to 2
  61. //                        for 3*Tq Propogation Time
  62. //
  63. // BRGCON3 contains the WAKFIL bit and the Phase Segment 2 Time Select bits
  64. //
  65. //                        WAKEFIL
  66. //            1=CAN bus line filter is used for wake-up
  67. //                                0=CAN bus line filter is not used for wake-up
  68. //
  69. //                        in the case of can-18xx8.h, the WAKEFIL bit is set to 0 for
  70. //                        CAN bus not used for wake-up
  71. //
  72. //                        SEG2PH2:SEG2PH0
  73. //                                Phase Segment 2 Time = (SEG2PH2:SEG2PH0+1)*Tq
  74. //
  75. //                        in the case of can-18xxx8.h, SEG2PH2:SEG3PH0 is set to 5 for
  76. //         6*Tq Phase Segment 2 Time
  77. //
  78. // More information can be found in the PIC18F4580 datasheet section 23.9
  79. ////////////////////////////////////////////////////////////////////////
  80. void can_set_baud(void) {
  81.  
  82.    BRGCON1.brp=CAN_BRG_PRESCALAR;
  83.    BRGCON1.sjw=CAN_BRG_SYNCH_JUMP_WIDTH;
  84.  
  85.    BRGCON2.prseg=CAN_BRG_PROPAGATION_TIME;
  86.    BRGCON2.seg1ph=CAN_BRG_PHASE_SEGMENT_1;
  87.    BRGCON2.sam=CAN_BRG_SAM;
  88.    BRGCON2.seg2phts=CAN_BRG_SEG_2_PHASE_TS;
  89.  
  90.    BRGCON3.seg2ph=CAN_BRG_PHASE_SEGMENT_2;
  91.    BRGCON3.wakfil=CAN_BRG_WAKE_FILTER;
  92. }

Es un método cuanto menos muy pulcro y refinado, para la gente que sabe y conoce mucho, ya que declarando los valores en el programa principal se evita la carga de los valores por default.

En mi caso soy muy inexperto en el tema CAN, por lo que resolví cargar los valores directos del programa de calculo de velocidad que explique anteriormente, para eso tuve que desarrollar una forma que me permitiera configurar todo cambiando solo una línea de codigo desde mi programa principal, lo que sigue es lo que quedó... :mrgreen:
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado MGLSOFT

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 7907
Re: Mis experiencias con el BUS CAN
« Respuesta #65 en: 11 de Noviembre de 2007, 23:12:34 »
Modifiqué solamente la función de carga de valores, dejando la posibilidad de cargar tres valores de velocidad en forma rápida.
Las velocidades elegidas fueron 125, 250 y 500 Kbps.

Una de estas ahora puede ser seleccionada desde el programa principal, según la necesidad.

Ahora vemos como quedó la función CAN_Set_Baud (), que es la encargada de configurar la velocidad.
Aqui está:

Código: C
  1. ////////////////////////////////////////////////////////////////////////
  2. //
  3. // can_set_baud()
  4. //
  5. // Configures the baud rate control registers.  All the defines here
  6. // are defaulted in the can-18xxx8.h file.  These defaults can, and
  7. // probably should, be overwritten in the main code.
  8. //
  9. // Current defaults are set to work with Microchip's MCP250xxx CAN
  10. // Developers Kit if this PIC is running at 20Mhz.
  11. //
  12. //      BRGCON1 contains the prescaler bits and the Synchronization jump
  13. //                width time bits.
  14. //
  15. //
  16. //      BRGCON2 contains the Phase Segment 2 Time Select bit, the SAMple bit
  17. //                the Phase Segment 1 bits, and the Propagation Time Select bits
  18. //
  19. //
  20. // BRGCON3 contains the WAKFIL bit and the Phase Segment 2 Time Select bits
  21. //
  22. //
  23. // More information can be found in the PIC18F4580 datasheet section 23.9
  24. ////////////////////////////////////////////////////////////////////////
  25. void can_set_baud(void) {
  26.    #ifdef Set_125K_Baud {
  27.       BRGCON1 = 0x01;
  28.       BRGCON2 = 0xBA;      //modificado 5/11/07 para usar CAN a 125 KBps
  29.       BRGCON3 = 0x07;      //con reloj a 10 MHz
  30.    }
  31.    #endif
  32.  
  33.    #ifdef Set_250K_Baud {
  34.       BRGCON1 = 0x00;
  35.       BRGCON2 = 0xBA;      //modificado 5/11/07 para usar CAN a 250 KBps
  36.       BRGCON3 = 0x07;      //con reloj a 10 MHz
  37.    }
  38.    #endif
  39.  
  40.    #ifdef Set_500K_Baud {
  41.       BRGCON1 = 0x00;
  42.       BRGCON2 = 0x92;      //modificado 5/11/07 para usar CAN a 500 KBps
  43.       BRGCON3 = 0x02;      //con reloj a 10 MHz
  44.    }
  45.    #endif
  46. }

Como se ve, la función ahora ingresa directamente los valores a los registros de configuración.
Para poder utilizar una configuración u otra, se la llama declarando la velocidad elegida desde el programa principal, antes de llamar a la librería de CAN.

Se hace de esta forma:

Código: C
  1. #define CAN_DO_DEBUG TRUE
  2.  
  3. #define Set_250K_Baud TRUE  /// <<<Aqui configuro que velocidad del BUS utilizo
  4.  
  5. #include "can-18F4580.c"

Quedó mas simple, no?? :mrgreen: :mrgreen:
Esa era la finalidad, ya entiendo como es la configuración, ahora a contarles las experiencias con los cambios de velocidad.... :D :D
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado Nocturno

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 18272
    • MicroPIC
Re: Mis experiencias con el BUS CAN
« Respuesta #66 en: 12 de Noviembre de 2007, 03:17:00 »
Sencillo y eficaz, maestro Marcos.

Desconectado MGLSOFT

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 7907
Re: Mis experiencias con el BUS CAN
« Respuesta #67 en: 12 de Noviembre de 2007, 11:00:38 »
Gracias, Manolo.

Luego seguire explicando las experiencias que hice en el cambio de velocidades, me parece importante recalcarlo antes de ir al guisado... :mrgreen: :mrgreen:
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado ESTECA55

  • PIC24H
  • ******
  • Mensajes: 1404
Re: Mis experiencias con el BUS CAN
« Respuesta #68 en: 12 de Noviembre de 2007, 17:37:51 »
Felicitaciones por todo lo desarrollado y publicado hasta ahora!!!

Recien termino de leer todos los mensajes, la verdad que esta muy bueno!


Aca hay otro lector que se prende en esto del CAN.

saludos

PD: muy linda la placa!!
Hay que esforzarse por ser el mejor, no creerse el mejor

Desconectado MGLSOFT

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 7907
Re: Mis experiencias con el BUS CAN
« Respuesta #69 en: 12 de Noviembre de 2007, 17:47:12 »
Gracias Esteban!!
Si leíste todo lo que va del hilo habras visto mi agradecimiento a vos por pasarme al dato para hacer la placa, es muy buen trabajo el que hizo el Sr. Sanchez.

Despues le pasaremos aqui el anuncio, je..je.. :mrgreen:
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado PalitroqueZ

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 5470
    • Electrónica Didacta
Re: Mis experiencias con el BUS CAN
« Respuesta #70 en: 13 de Noviembre de 2007, 12:26:21 »
uff lectura interesante que me he perdido estos dias

Saludos Marcos  :-) :-)
La propiedad privada es la mayor garantía de libertad.
Friedrich August von Hayek

Desconectado stk500

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 4917
Re: Mis experiencias con el BUS CAN
« Respuesta #71 en: 13 de Noviembre de 2007, 13:22:34 »
 :-/ perdona marco no habia pasado por aqui
esta muy eso, y ya ha tenido una experiencia mas en los dichoso Zocalo y mi tambien me paso lo mismo con un circuito, sacaba y metia el chip y no habia contacto en zocalo
en hora buena amigo :mrgreen:

Desconectado MGLSOFT

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 7907
Re: Mis experiencias con el BUS CAN
« Respuesta #72 en: 13 de Noviembre de 2007, 17:48:29 »
Gracias STK, igual esa es solo una de mis desventuras con esta placa, ya pondre las demas, je..je :mrgreen:
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado MGLSOFT

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 7907
Re: Mis experiencias con el BUS CAN
« Respuesta #73 en: 15 de Noviembre de 2007, 00:46:33 »
Bueno!!! :-/ :-/
Recién acabo de solucionar mi problema existencial con la placa de mis amores, je..je :mrgreen: :mrgreen:

Mañana prometo retomar las clases, tengo mucho rollo para cortar ahora que estoy mas tranquilo.

No me funcionaba el primer MCP25050 que programe, y son OTP, así que no se puede pifiar demasiado, especialmente cuando tienes solo dos y crees que programaste mal el primero!!! :mrgreen: :mrgreen:
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.

Desconectado MGLSOFT

  • Moderador Local
  • DsPIC33
  • *****
  • Mensajes: 7907
Mis experiencias con el BUS CAN - El primer programa
« Respuesta #74 en: 18 de Noviembre de 2007, 18:11:00 »
Bueno, retomamos el tema luego de unas cortas vacaciones.... :D :D
Despues de ir descubriendo y reparando todos los problemas de mi placa (muchos por desconocimiento al momento de desarrollarla y otros creados por mi luego de tenerla), creo que ya estoy a punto de ir escribiendo las experiencias...

El primer programa:
Como veran, no es cuestión de ponerse muy locos al primer movimiento para probar nuestros equipos, la experiencia me dice que cuanto mas probadas las cosas que uses mejor para tener menos dolores de cabeza, por lo tanto el primer ejemplo es directamente el de CCS, modificado para usarlo con mi placa, que tiene un PIC18F4580.

El codigo del ejemplo, adaptado para 250 KBPs (viene a 125 KBPs) es este:
Código: C
  1. /////////////////////////////////////////////////////////////////////////
  2. ////                         EX_CAN_CCS_A.C                          ////
  3. ////                                                                 ////
  4. //// Example of CCS's CAN library, using the PIC18Fxx8.  This        ////
  5. //// example was tested with and written for the CCS CAN Prototype   ////
  6. //// board.                                                          ////
  7. ////                                                                 ////
  8. //// The CCS CAN Prototype board has four CAN nodes that communicate ////
  9. //// to each other.  Node A is the 18F458 with it's internal CAN     ////
  10. //// peripheral, Node B is a PIC16F87x connected to an external      ////
  11. //// MCP2510 CAN peripheral, and Node C and Node D are both MCP250xx ////
  12. //// stand-alone CAN I/O expanders.  This example is the firmware    ////
  13. //// for Node A.                                                     ////
  14. ////                                                                 ////
  15. //// Every two seconds this firmware sends out a command to node B   ////
  16. //// to change it's leds (CAN ID 0x202)                              ////
  17. ////                                                                 ////
  18. //// Upon change of the A/D reading, a value of 0-9 is sent to       ////
  19. //// Node D which is displayed on the 8-seg LCD (CAN ID 0x400)       ////
  20. ////                                                                 ////
  21. //// Pressing the Node A button sends a request to Node B (CAN ID    ////
  22. //// 0x201) for Node B's A/D reading, which Node B will respond      ////
  23. //// with a CAN message with it's A/D reading (with CAN ID 0x201).   ////
  24. //// Also, pressing the Node A button will change the LEDs on Node   ////
  25. //// C (CAN ID 0x300)                                                ////
  26. ////                                                                 ////
  27. //// Pressing Node C's buttons will cause Node A's buttons to change ////
  28. //// (Node C transmits button changes with CAN ID 0x303)             ////
  29. ////                                                                 ////
  30. //// Using a serial port, you can examine all the CAN traffic as     ////
  31. //// seen by the 18xxx8.                                             ////
  32. ////                                                                 ////
  33. //// For more documentation on the CCS CAN library, see can-18xxx8.c ////
  34. ////                                                                 ////
  35. ////  Jumpers:                                                       ////
  36. ////     PCH    pin C7 to RS232 RX, pin C6 to RS232 TX               ////
  37. ////                                                                 ////
  38. ////  This example will work with the PCH compiler.                  ////
  39. /////////////////////////////////////////////////////////////////////////
  40. ////                                                                 ////
  41. //// Baud rate settings to use to connect to the CCS CAN Prototype   ////
  42. //// board at 20Mhz:                                                 ////
  43. ////                                                                 ////
  44. ////    Baud Rate Prescalar: 4                                       ////
  45. ////    Propagation Segment: 3xTq                                    ////
  46. ////    Phase Segment 1: 6xTq                                        ////
  47. ////    Phase Segment 2: 6xTq                                        ////
  48. ////    Synchronized Jump Width: 1xTq                                ////
  49. ////    Sample Rate: 1x                                              ////
  50. ////    Wakeup Filter:  Off                                          ////
  51. ////                                                                 ////
  52. /////////////////////////////////////////////////////////////////////////
  53. ////                                                                 ////
  54. //// Node C and D are seperate stand-alone MCP250xx CAN I/O          ////
  55. //// expanders.  The CCS CAN Prototype board has these chips already ////
  56. //// programmed correctly.  However, if you wish to program your own ////
  57. //// to work with this example, then use the provided .HEX files     ////
  58. //// a programmer capable of programming these chips.  Or, make a    ////
  59. //// a new HEX file with these properties:                           ////
  60. ////                                                                 ////
  61. //// NODE C: Set RX ID mask and buffers to receive ID 0x3**. (The ** ////
  62. //// means make the least signifcant 8bits no-care in the mask).     ////
  63. //// Set TX1 buffer to ID 0x301, TX2 buffer to ID 0x302, TX3 buffer  ////
  64. //// to ID 0x303. Set GP0 to analog (and enable the A/D).  Set GP1,  ////
  65. //// GP2 and GP3 to OUTPUT.  Set GP4, GP5 and GP6 as INPUT with edge ////
  66. //// trigger enable.  Leave OPTREG2 clear, disable PWM1 and PWM2,    ////
  67. //// and disable scheduled transmission.  Also, see the baud rate    ////
  68. //// settings above.                                                 ////
  69. ////                                                                 ////
  70. //// NODE D: Set RX ID mask and buffers to receive ID 0x4**. (The ** ////
  71. //// means make the least signifcant 8bits no-care in the mask).     ////
  72. //// Set TX1 buffer to ID 0x401, TX2 buffer to ID 0x402, TX3 buffer  ////
  73. //// to ID 0x403. Configure all ports as OUTPUT.  Leave OPTREG2      ////
  74. //// clear, disable PWM1 and PWM2, and disable scheduled             ////
  75. //// transmission.  Also, see the baud rate settings above.          ////
  76. ////                                                                 ////
  77. /////////////////////////////////////////////////////////////////////////
  78. ////        (C) Copyright 1996,2003 Custom Computer Services         ////
  79. //// This source code may only be used by licensed users of the CCS  ////
  80. //// C compiler.  This source code may only be distributed to other  ////
  81. //// licensed users of the CCS C compiler.  No other use,            ////
  82. //// reproduction or distribution is permitted without written       ////
  83. //// permission.  Derivative programs created using this software    ////
  84. //// in object code form are not restricted in any way.              ////
  85. /////////////////////////////////////////////////////////////////////////
  86.  
  87. #include <18F4580.h>
  88. #device ICD=TRUE
  89. #device adc=8
  90.  
  91. #FUSES NOWDT                    //No Watch Dog Timer
  92. #FUSES WDT128                   //Watch Dog Timer uses 1:128 Postscale
  93. #FUSES HS                       //High speed Osc (> 4mhz)
  94. #FUSES NOPROTECT                //Code not protected from reading
  95. #FUSES BROWNOUT                 //Reset when brownout detected
  96. #FUSES BORV21                   //Brownout reset at 2.1V
  97. #FUSES PUT                      //Power Up Timer
  98. #FUSES NOCPD                    //No EE protection
  99. #FUSES STVREN                   //Stack full/underflow will cause reset
  100. #FUSES NODEBUG                  //No Debug mode for ICD
  101. #FUSES NOLVP                    //No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
  102. #FUSES NOWRT                    //Program memory not write protected
  103. #FUSES NOWRTD                   //Data EEPROM not write protected
  104. #FUSES NOIESO                   //Internal External Switch Over mode enabled
  105. #FUSES FCMEN                    //Fail-safe clock monitor enabled
  106. #FUSES PBADEN                   //PORTB pins are configured as analog input channels on RESET
  107. #FUSES BBSIZ1K                  //1K words Boot Block size
  108. #FUSES NOWRTC                   //configuration not registers write protected
  109. #FUSES NOWRTB                   //Boot block not write protected
  110. #FUSES NOEBTR                   //Memory not protected from table reads
  111. #FUSES NOEBTRB                  //Boot block not protected from table reads
  112. #FUSES NOCPB                    //No Boot Block code protection
  113. #FUSES NOLPT1OSC              //Timer1 is not configured for low-power operation
  114. #FUSES MCLR                     //Master Clear pin enabled
  115. #FUSES NOXINST                  //Extended set extension and Indexed Addressing mode disabled (Legacy mode)
  116.  
  117. //#include <18F4580.h>
  118. //#fuses HS,NOPROTECT,NOLVP,NOWDT
  119. #use delay(clock=10000000)
  120. //#use delay(clock=20000000)
  121. #use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)
  122.  
  123. #define CAN_DO_DEBUG TRUE
  124.  
  125. //#include <can-18xxx8.c>
  126. #include "can-18F4580.c"
  127.  
  128. #define PIN_LED1  PIN_A5
  129. #define PIN_LED2  PIN_B5
  130. #define PIN_LED3  PIN_B4
  131.  
  132. #define LED1_LOW  output_low(PIN_LED1)
  133. #define LED1_HIGH output_high(PIN_LED1)
  134. #define LED2_LOW  output_low(PIN_LED2)
  135. #define LED2_HIGH output_high(PIN_LED2)
  136. #define LED3_LOW  output_low(PIN_LED3)
  137. #define LED3_HIGH output_high(PIN_LED3)
  138.  
  139. #define BUTTON    PIN_A4
  140.  
  141. #define BUTTON_PRESSED  !input(BUTTON)
  142.  
  143. int16 ms;
  144.  
  145. const char lcd_seg[10]={0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10};   //0 for on, 1 for off
  146.  
  147. #int_timer2
  148. void isr_timer2(void) {
  149.    ms++; //keep a running timer that increments every milli-second
  150. }
  151.  
  152. #define ASK_FOR_ID_AD_B      0x201  //ask for AD info from CAN port B
  153. #define SET_LED_ID_B         0x202  //set LEDs for CAN port B
  154. #define RESPOND_TO_LED_C_ID  0x303
  155. #define WRITE_REGISTER_C_ID  0x300
  156. #define WRITE_REGISTER_D_ID  0x400
  157.  
  158. void main() {
  159.    int b_leds=0;
  160.    int c_leds=1;
  161.    int a_leds=0;
  162.    struct rx_stat rxstat;
  163.    int32 rx_id;
  164.    int buffer[8];
  165.    int rx_len;
  166.  
  167.    int last_lcd_output=0xFF;
  168.    int i,curr_lcd_output;
  169.  
  170.    setup_port_a(RA0_ANALOG);
  171.    setup_adc(ADC_CLOCK_INTERNAL);
  172.    set_adc_channel(0);
  173.  
  174.    for(i=0;i<8;i++) {
  175.       buffer[i]=0;
  176.    }
  177.  
  178.    LED1_HIGH;
  179.    LED2_HIGH;
  180.    LED3_HIGH;
  181.    printf("\r\n\r\nCCS CAN EXAMPLE\r\n");
  182.    delay_ms(1000);
  183.    LED1_LOW;
  184.    LED2_LOW;
  185.    LED3_LOW;
  186.  
  187.    setup_timer_2(T2_DIV_BY_4,79,16);   //setup up timer2 to interrupt every 1ms if using 20Mhz clock
  188.  
  189.    can_init();
  190.  
  191.    enable_interrupts(INT_TIMER2);
  192.    enable_interrupts(GLOBAL);
  193.  
  194.    printf("\r\nRunning...");
  195.  
  196.    while(TRUE)
  197.    {
  198.       if ( can_kbhit() )
  199.       {
  200.          printf("\r\n");
  201.          if(can_getd(rx_id, &buffer[0], rx_len, rxstat)) {
  202.             if (rx_id == ASK_FOR_ID_AD_B) {
  203.                printf("Channel B AD: %X\r\n",buffer[0]);
  204.             }
  205.             else if (rx_id == RESPOND_TO_LED_C_ID) {  //node C is an mcp250x0 which sends out a message upon edge detection on IO
  206.                printf("Chaning LEDs\r\n");            //in_data[0]=iointfl, in_data[1]=gpio
  207.                a_leds=~(buffer[1]);
  208.                if (bit_test(a_leds,4)) {LED1_HIGH;} else {LED1_LOW;}
  209.                if (bit_test(a_leds,5)) {LED2_HIGH;} else {LED2_LOW;}
  210.                if (bit_test(a_leds,6)) {LED3_HIGH;} else {LED3_LOW;}
  211.             }
  212.          }
  213.       }
  214.  
  215.       if ( can_tbe() && (ms > 2000))       //every two seconds, send new data if transmit buffer is empty
  216.       {
  217.          ms=0;
  218.  
  219.          //change leds on port b
  220.          printf("\r\n\r\nSet LEDs on Port B to %U",b_leds);
  221.          can_putd(SET_LED_ID_B, &b_leds, 1, 1, 1, 0);
  222.          b_leds++;
  223.          if (b_leds > 7) {b_leds=0;}
  224.       }
  225.  
  226.       if (BUTTON_PRESSED) {
  227.          while (BUTTON_PRESSED) {}
  228.          delay_ms(200);
  229.  
  230.          //ask for AD on port B
  231.          printf("\r\n\r\nAsking for A/D reading on Port B...");
  232.          can_putd(ASK_FOR_ID_AD_B, 0, 1, 1, 1, 1);
  233.  
  234.          //change LEDs on port C
  235.          buffer[0]=0x1E;            //addr of gplat on 25050
  236.          buffer[1]=0x0E;            //mask
  237.          buffer[2]=~(c_leds << 1);  //new gplat values
  238.          printf("\r\nIncrementing LED on Port C");
  239.          can_putd(WRITE_REGISTER_C_ID, &buffer[0], 3, 1, 1, 0);
  240.          c_leds++;
  241.          if (c_leds > 7) {c_leds=0;}
  242.       }
  243.  
  244.          //change lcd segment on port d
  245.          i=read_adc();
  246.          curr_lcd_output=i/26;   //scale to 0-9
  247.          if (curr_lcd_output != last_lcd_output) {
  248.             last_lcd_output=curr_lcd_output;
  249.             printf("\r\nChanging 8-seg LCD on D to current A/D reading (%X, %X)",i,curr_lcd_output);
  250.             buffer[0]=0x1E;                    //addr of gplat
  251.             buffer[1]=0x7F;             //mask
  252.             buffer[2]=lcd_seg[curr_lcd_output];                //new gplat values
  253.             can_putd(WRITE_REGISTER_D_ID, &buffer[0], 3, 1, 1, 0);
  254.          }
  255.    }
  256. }
« Última modificación: 18 de Noviembre de 2007, 18:15:29 por MGLSOFT »
Todos los dias aprendo algo nuevo, el ultimo día de mi vida aprenderé a morir....
Mi Abuelo.


 

anything