TODOPIC

Microcontroladores PIC => Lenguaje C para microcontroladores PIC => Mensaje iniciado por: ppyote en 23 de Diciembre de 2012, 22:35:15

Título: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: ppyote en 23 de Diciembre de 2012, 22:35:15
Hola gente....

pues vereis, estoy buscando informacion sobre las interrupciones producidas por el ADC del 18f4550 para poder sacar el ucontrolador del sleep mediante una pulsacion del touch capacitivo... el problema es que no encuentro casi nada, solo ejemplos un poco nublados ya que no sale ningun esquema ni explicacion de como se debe de actuar para checar un pulsacion...

como son los pasos que se deben de seguir para que actue la interrupcion? dentro de ella.... como se debe hacer para leer el valor? se podrian leer las 4 entradas ADC desde que actua la interrupcion? no se la verdad... estoy liado y no paro de modificar mi proyecto pero no doy con la solucion....
Aqui en el foro lei en este POST (http://www.todopic.com.ar/foros/index.php?topic=35513.0) que primero se debe de cargar el condensador de retencion y descargar el de sensado.... no lo pillo... la verdad

por favor decidme los pasos a seguir a grandes rasgos, no busco soluciones, si no la secuencia a seguir explicada por que mi cabeza ya va a petar....
gracias y un saludo a la peña
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: Nocturno en 24 de Diciembre de 2012, 03:19:29
La interrupción del ADC no se ejecuta cuando hay un cambio en la entrada analógica. Funciona de la siguiente forma:
- solicitas una conversión adc
- activas la interrupción int_ad
- suspendes al micro con sleep
- el micro despertará cuando haya terminado la conversión adc y tengas el dato disponible

Puedes ver el proceso en la página 263 de la data:
http://ww1.microchip.com/downloads/en/devicedoc/39632c.pdf

Para hacer lo que quieres, yo usaría la interrupción del timer. Así, tienes al micro dormido durante, por ejemplo, 10ms. Cada periodo se despierta, chequea las entradas ADC y si no detecta pulsación se vuelve a dormir.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: ppyote en 24 de Diciembre de 2012, 06:05:44
gracias por contestar Nocturno, la verdad es que si me conviene utilizar el timer0 para comprobar las entradas de los pulsadores.... lo habia pensado como segunda opcion si no hacia funcionar la interrupcion int_ad o esta, no se ajustaba a mis necesidades.... cosa que no se ajusta
la otra gran duda que tengo es la de los touchs capacitivos, en el post que puse se puede ver como pone a 1 el estado de la salida del A1 y seguidamente comprueba hace lo mismo con el A0.....
Código: [Seleccionar]
while(TRUE){
     set_tris_a(0b11111100); //Drive secondary channel to VDD as digital output.
     output_high(PIN_A1);
     set_adc_channel(1); //Point ADC to the secondary VDD pin (charges CHOLD to VDD)
     
     output_low(PIN_A0); //Ground sensor line.
     set_tris_a(0b11111101); //Turn sensor line as input (TRISx = 1).
     set_adc_channel(0);//Point ADC to sensor channel (voltage divider from sensor to CHOLD).
     
     value=read_adc();//Begin ADC conversion.
     printf("%lu\n",value);
     delay_ms(50);
  } 


que explicacion hay que para comprobar un valor cambie el estado del A1 si lo que se desea es comprovar el del A0?
primero se debe de cargar el condensador de retencion(imagino que es el condensador conectado exteriormente al pin) y descargar el de sensado(es el que lleva interiormente el pic) no es asi?
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: Nocturno en 24 de Diciembre de 2012, 07:35:41
Sí, esa técnica se llama CVD. Puedes verla explicada aquí:
http://ww1.microchip.com/downloads/en/AppNotes/01298A.pdf
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: ppyote en 24 de Diciembre de 2012, 09:39:56
Sí, esa técnica se llama CVD. Puedes verla explicada aquí:
http://ww1.microchip.com/downloads/en/AppNotes/01298A.pdf


el ingles no es lo mio Nocturno.... uso el traducctor de google pero no me queda aun claro el por que utiliza el canal1 si lo que se quiere en el ejemplo es obtener la medicion del canal0
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: ppyote en 24 de Diciembre de 2012, 09:58:46
http://www.youtube.com/watch?v=0GmIkyEzHnk&feature=endscreen&NR=1 (http://www.youtube.com/watch?v=0GmIkyEzHnk&feature=endscreen&NR=1)

aqui se explica graficamente.... pero no aparece nada de otro canal del ADC....
como llenar o como vaciar el Condensador de censado? cambiando el estado del pin a alto se llena? seleccionado el canal se vacia?
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: Nocturno en 24 de Diciembre de 2012, 13:32:49
1. Drive secondary channel to VDD as digital
output.
2. Point ADC to the secondary VDD pin (charges
CHOLD to VDD).
3. Ground sensor line.
4. Turn sensor line as input (TRISx = 1).
5. Point ADC to sensor channel (voltage divider
from sensor to CHOLD).
6. Begin ADC conversion.
7. Reading is in ADRESH:ADRESL

1.- Establece el canal secundario como salida digital a nivel alto
2.- Selecciona en el ADC al canal secundario (cargará el condensador)
3.- Tira a tierra la línea que vas a sensar (salida a nivel bajo)
4.- Pon la línea a sensar como entrada
5.- Selecciona en el ADC la línea a sensar
6.- Comienza la conversión ADC
7.- Lee el resultado
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: ppyote en 24 de Diciembre de 2012, 16:59:06
Nocturno, gracias de nuevo por la ayuda
Sí quisiera sensar los canales 2 3 y 4 debería de hacerlo correlativamente siguiendo los pasos que tú me has descrito no?
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: Nocturno en 25 de Diciembre de 2012, 03:00:23
Sí, tienes que ejecutar ese proceso con cada pin a sensar.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: ppyote en 25 de Diciembre de 2012, 15:13:52
hace un rato que he llegado a casa para probar lo aprendido gracias a nocturno.... bueno, pruebo el primer boton touch conectado en el conversor del canal 0 y va perfecto.... el primer boton esta operativo ya...
el problema viene con el segundo boton que esta conectado al canal1...


set_tris_a(0x11111100);               //este va perfecto
   output_high(PIN_A1);
   set_adc_channel(1);
   output_low(PIN_A0);
   set_tris_a(0x11111101);
   set_adc_channel(0);
   valor_ADC[1]=read_adc();
   
   
   set_tris_a(0x11111001);           //este no va
   output_high(PIN_A2);
   set_adc_channel(2);
   output_low(PIN_A1);
   set_tris_a(0x11111011);
   set_adc_channel(1);
   valor_ADC[2]=read_adc();

hay que utilizar un canal "vacio" para cargar el condensados de sensado?
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: Nocturno en 25 de Diciembre de 2012, 16:49:21
Prueba así:

Código: [Seleccionar]
   output_high(PIN_A2);
   set_adc_channel(2);
   output_low(PIN_A0);
   output_float(PIN_A0);
   set_adc_channel(0);
   valor_ADC[1]=read_adc();
   
   output_high(PIN_A2);
   set_adc_channel(2);
   output_low(PIN_A1);
   output_float(PIN_A1);
   set_adc_channel(1);
   valor_ADC[2]=read_adc();

No es necesario establecer los tris, porque con los comandos output_x el compilador CCS establece la dirección automáticamente.
Y he usado el canal 2 como canal comodín para cargar el condensador, sensando primero el 0 y luego el 1.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: ppyote en 25 de Diciembre de 2012, 17:37:21
Prueba así:

Código: [Seleccionar]
   output_high(PIN_A2);
   set_adc_channel(2);
   output_low(PIN_A0);
   output_float(PIN_A0);
   set_adc_channel(0);
   valor_ADC[1]=read_adc();
   
   output_high(PIN_A2);
   set_adc_channel(2);
   output_low(PIN_A1);
   output_float(PIN_A1);
   set_adc_channel(1);
   valor_ADC[2]=read_adc();

No es necesario establecer los tris, porque con los comandos output_x el compilador CCS establece la dirección automáticamente.
Y he usado el canal 2 como canal comodín para cargar el condensador, sensando primero el 0 y luego el 1.

perfecto, gracias nocturno.... yo los iva haciendo correlativamente por eso no me funcionaba... usana el canal 0 y 1, despues el 1 y 2, 2 y 3.... ahora si que si....
ahora mirare de poner a dormir el micro y comprobar con el timer1 cuando se desborde que se ha pulsado algun mtouch y de no ser asi a dormir otra vez....
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: ppyote en 29 de Diciembre de 2012, 17:06:03
Una pregunta me tiene algo intrigado, que hace diferentes a los pics que implementan los touch en su arquitectura a los que no la llevan?
Los que tienen este tipo de hardware la lectura es de idéntica forma que el resto?
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 29 de Diciembre de 2012, 19:36:42
En esos Pics el hardware ya resuelve mucho de esto que has logrado con programación...
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: ppyote en 29 de Diciembre de 2012, 21:14:25
En esos Pics el hardware ya resuelve mucho de esto que has logrado con programación...

ya estube dandole un vistazo a la web del ccs.... asi se miran.... con estas funciones.... gracias MGLSOFT... siempre estais los mejores para solventar las dudas....

#USE TOUCHPAD ( )
touchpad_state( )
touchpad_getc( )
touchpad_hit( )
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 29 de Diciembre de 2012, 22:37:24
Aprovecho a colocar aqui una duda planteada a la gente de CCS, acerca de como usar esas funciones con PICs que en vez del modulo Mtouch tienen modulo CTMU.


Aqui va la respuesta, original en ingles:

Citar
When using the #use touchpad() library on CTMU devices the options are the same except the CTMU devices have and added option called SOURCETIME which sets how long in us each pin is charged for.  The default is 10 us if not specified.  Otherwise the examples for a CSM device and a CTMU device are exactly the same.

A couple things to be careful of for CTMU devices is that #use touchpad uses the ADC peripheral to read the touch pins.  The #use touchpad() directive automatically sets the necessary pins to analog inputs.  So if you need to make a pin an analog input for the ADC or analog comparator with the setup_adc_ports() function, make sure that you also make the pins specified in #use touchpad() analog also.  Finally, if you are using the ADC peripheral the #use touchpad() directive will be changing the adc channel to read the touch pins, so it will probably mess up any adc_read() calls you do in your code.  I recommend that when you need to read an adc pin that you disable the global interrupt, read the pin and then re-enable the global interrupt.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: sanpic en 05 de Febrero de 2013, 23:32:30
Aprovecho a colocar aqui una duda planteada a la gente de CCS, acerca de como usar esas funciones con PICs que en vez del modulo Mtouch tienen modulo CTMU.


Aqui va la respuesta, original en ingles:

Citar
When using the #use touchpad() library on CTMU devices the options are the same except the CTMU devices have and added option called SOURCETIME which sets how long in us each pin is charged for.  The default is 10 us if not specified.  Otherwise the examples for a CSM device and a CTMU device are exactly the same.

A couple things to be careful of for CTMU devices is that #use touchpad uses the ADC peripheral to read the touch pins.  The #use touchpad() directive automatically sets the necessary pins to analog inputs.  So if you need to make a pin an analog input for the ADC or analog comparator with the setup_adc_ports() function, make sure that you also make the pins specified in #use touchpad() analog also.  Finally, if you are using the ADC peripheral the #use touchpad() directive will be changing the adc channel to read the touch pins, so it will probably mess up any adc_read() calls you do in your code.  I recommend that when you need to read an adc pin that you disable the global interrupt, read the pin and then re-enable the global interrupt.


A propósito , ¿ alguien ha logrado hacer funcionar el touchpad en dispositivos con ctmu bajo ccs ?  Me está volviendo loco y  o logro hacerlo funcionar.  :5]
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 06 de Febrero de 2013, 00:00:09
Yo tampoco... :shock:
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: sanpic en 06 de Febrero de 2013, 19:38:11
Pues si Marcos , es raro que la gente de CCS haya anunciado plena compatibilidad con los dispositivos CTMU , no hayan puesto ejemplos al respecto , no se discuta nada en el foro de CCS , compiles sin errores y nada de  nada. Frustrante. Pero bue , a seguir esperando.
Un abrazo.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 06 de Febrero de 2013, 20:36:14
Como haces los botones touch ??
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: sanpic en 08 de Febrero de 2013, 15:38:24
Marcos , estoy probando en protoboard , así que solamente es un cablecito con un espiral descubierto en el extremo , y solamente conectado al pin del pic.
Usando por ej, la gama 16f727, 16f1939 etc funciona perfecto pero con los ctmu nada de nada.
Abrazo grande.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 08 de Febrero de 2013, 15:48:59
Yo probé así también en el protoboard, pero en un video que anda por internet, hay uno que muestra una placa doble faz, con un lado conectado al pin del pic y el otro a gnd.
En el video muestra que la ganancia es tan alta de esa forma que detectaba la cercanía del dedo a 1 mm aun sin tocarlo, y según el tipo usaba el modulo CTMU.
Eso no lo probé por falta de tiempo.

Por otro lado , con el modulo CTMU, entiendo que hace falta recalibrarlo sin tener toque, para optimizar el funcionamiento.
Si lo tienes armado todavía, intenta probarlo, a ver si va...
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 03 de Julio de 2013, 14:08:23
Voy a probar algo que lei en el foro de CCS y si tengo resultados lo pongo.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: sanpic en 03 de Julio de 2013, 19:44:40
Lo espero con ansias Marcos.  :D
Un abrazo grande.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 03 de Julio de 2013, 23:59:26
Ya envie la pregunta a CCS, pero al menos ya leo el pulsador apretado e el mometo del arranque de la placa, luego no se que pasa...
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: sanpic en 04 de Julio de 2013, 12:05:56
Excelente avance.  ;-)
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 05 de Julio de 2013, 16:01:10
Segun la consulta hecha a la gente de CCS, me dijeron que use la ultima version del compilador que anda bien.

A decir verdad mejoro mucho, salvo algunas dudas que tiene el PIC a veces  :D :D :D detecta los touch hechos de tres teclas y los diferencia mejor de la que tenia.
Ahora queda saber como hacer bien un teclado para usarlo en Mtouch, porque lo que yo hice es tomar un pedazo de PCB virgen y calarle entre los botones con una amoladora.
Parece un teclado para Pedro Picapiedras, je..je.. :mrgreen: :mrgreen:
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: sanpic en 05 de Julio de 2013, 16:40:58
Jajaja.
Excelente trabajo Marcos  ((:-))
Podrías poner parte del código que usaste ?
Yo tengo pensado usar un 24FV , debería funcionar en todas las familias verdad ?

Un abrazo grande.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: planeta9999 en 05 de Julio de 2013, 17:17:52
Ahora queda saber como hacer bien un teclado para usarlo en Mtouch, porque lo que yo hice es tomar un pedazo de PCB virgen y calarle entre los botones con una amoladora.
Parece un teclado para Pedro Picapiedras, je..je.. :mrgreen: :mrgreen:


En Microchip, tienes unas cuantas notas aplicativas con consejos para diseñar botones mtouch (AN1102, AN1334, etc...).
Según quieras mejorar sensibilidad o inmunidad al ruido, debes de diseñar el botón, yo opto por una solución intermedia, sin planos de tierra bajo el botón o con plano de tierra de rejilla y con el cobre a masa entre botones, para evitar falsos disparos, todos los planos de tierra que pongo son de rejilla.


En este dibujo, se resume la relación sensibilidad - inmunidad al ruido, según como diseñes los planos de tierra bajo el botón (solidos, de rejilla o sin plano de tierra):

(http://imageshack.us/a/img844/192/7htw.jpg)



Estos son dos de los botones que tengo hechos en mis diseños, cada botón tiene dos hilos más una pista de masa que lo rodea, y los conecto en matriz para poder tener bastantes botones con unos pocos puertos (hasta 64 botones con una matriz de 8x8):

(http://imageshack.us/a/img811/7572/hd68.jpg)


(http://imageshack.us/a/img441/9614/2vrt.jpg)

 
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 05 de Julio de 2013, 18:46:46
Gracias, excelente aporte...

Y en caso de estos botones, como es la conexión ?, ya que veo que es una rejilla...
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: planeta9999 en 05 de Julio de 2013, 19:33:09
Gracias, excelente aporte...

Y en caso de estos botones, como es la conexión ?, ya que veo que es una rejilla...



Los conecto en matriz, pero esta configuración solo es necesaria si tienes muchos botones, en mi caso tengo un diseño con 22 botones. Para diseños con pocos botones, los diseñas sólidos y cada botón a una patilla.


(http://imageshack.us/a/img809/4339/nozc.jpg)


(http://imageshack.us/a/img203/2940/jnue.jpg)
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 05 de Julio de 2013, 19:47:54
Si uso botones comunes (si multiplexar), los hago sólidos y con rodeo de masa alrededor??
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 05 de Julio de 2013, 20:09:42
Aquí pongo el código que tengo a medio funcionar, ya que según comente creo que mis botones no son los mejores, je..je..

El archivo .h

Código: C
  1. /#include <18F26K80.h>
  2. //#device adc=10
  3.  
  4. #FUSES NOWDT                    //No Watch Dog Timer
  5. //#FUSES WDT128                   //Watch Dog Timer uses 1:128 Postscale
  6. //#FUSES SOSC_DIG                 //Digital mode, I/O port functionality of RC0 and RC1
  7. #FUSES NOXINST                  //Extended set extension and Indexed Addressing mode disabled (Legacy mode)
  8. #FUSES INTRC_IO                 //Internal RC Osc, no CLKOUT
  9. //#FUSES PLLEN                    //PLL habilitado
  10. #FUSES PUT                      //Power Up Timer
  11. #FUSES NOBROWNOUT               //No brownout reset
  12. //#FUSES WDT_NOSLEEP              //Watch Dog Timer, disabled during SLEEP
  13.  
  14. #use delay(int=8000000)//, RESTART_WDT)
  15.  
  16. #use rs232(baud=9600,parity=N,xmit=PIN_C6,rcv=PIN_C7,bits=8,stream=PORT1)//,RESTART_WDT)
  17.  
  18. //#USE TOUCHPAD(RANGE=H, THRESHOLD=6, SCANTIME=32, SOURCETIME=10, PIN_A0='A', PIN_A1='B', PIN_A2='C')
  19. #USE TOUCHPAD(RANGE=M, THRESHOLD=4, SCANTIME=40, SOURCETIME=10, PIN_A0='A', PIN_A1='B', PIN_A2='C')
  20. // aqui entrar a Tools > Device Editor > elegir el Pic > (Cuadro central)Other Features > Cap Sens Mode y elegir cual es el formato utilizado si no esta.

Y el archivo .c

Código: C
  1. #include <Uso CTMU Touch.h>
  2. //#use fast_io(A)
  3. #ZERO_RAM
  4. #Define Led_Amar Pin_C4
  5.  
  6. void main()
  7. {
  8.    char c = 'D';
  9.    int16 Conteo;
  10.   // set_tris_a(0b00000111);//RA2 input
  11.    delay_ms(5000); //pausa para levantar el port USB
  12.    
  13.  //  setup_adc_ports(ALL_ANALOG);
  14.  //sets all the adc pins to analog
  15.  
  16.    enable_interrupts(GLOBAL);
  17.  
  18.    TOUCHPAD_STATE(1);     //calibrates, then enters normal state
  19.  
  20.       printf(" MTOUCH con CTMU...\n\r");
  21.      
  22.    while(TRUE)
  23.    {
  24.       //TODO: User Code
  25.      if ( TOUCHPAD_HIT() )
  26.       {
  27.          c = TOUCHPAD_GETC();   //will wait until a pin is detected
  28.          Conteo = 0;
  29.       }
  30.      
  31.       switch (c)
  32.       {
  33.  
  34.           case 'A':
  35.           case 'B':
  36.           case 'C':     output_high(Led_Amar);
  37.                         delay_ms(50);
  38.                         output_low(Led_Amar);
  39.                   break;
  40.      
  41.           default:      c = 'D';
  42.      
  43.                   break;
  44.        }
  45.      
  46.       printf("Tecla pulsada: %c ...\r",c);
  47.            
  48.    }
  49.  
  50. }

como veran, en el codigo estan los rastros de mis diversas pruebas, je..je..

Y una foto de mi "teclado", cuidado que tiene derechos de Copyrigth !!!   :D :D :D :D

De frente:

(http://imageshack.us/a/img191/8092/1ai4.jpg)

Y por detrás, el secreto!!! :D :D

(http://imageshack.us/a/img837/668/t0v0.jpg)
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: planeta9999 en 06 de Julio de 2013, 08:39:10

Si uso botones comunes (si multiplexar), los hago sólidos y con rodeo de masa alrededor??


Si, así están hechos en las placas demo de Microchip, como estas, no tienen plano de tierra bajo el botón, pero si entre botones.


(http://imageshack.us/a/img812/7035/instrumental016.jpg)

(http://imageshack.us/a/img690/8716/instrumental015.jpg)

Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 06 de Julio de 2013, 09:09:18
O sea que en mi "diseño" solo me falto el plano de masa entre los botones !!! :D :D :D
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 28 de Julio de 2013, 18:21:23
hey there

just to show what I'm working so far, is the second version of my CANBus Board, but with a enhance CAN with the PIC18F26K80, and Touch Sensors added.

Still working on the Touch Library


"Hola

sólo para mostrar lo que estoy trabajando hasta el momento, es la segunda versión de mi Junta CANBus, pero con una mejorar CAN con el PIC18F26K80, añadió y Sensores táctiles.

Sigo trabajando en la Biblioteca Touch"






Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 28 de Julio de 2013, 23:08:57
Con que compilador programas rotting79 ??

Para los moderadores: No se que pasa pero veo un segundo las imagenes y videos y luego ya no se ven mas...
alguna idea de porque ocurre esto ??
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 29 de Julio de 2013, 00:18:37
With that compiler rotting79 programs?

To the moderators: No passing but I see one seconds pictures and videos and then are no longer more ...
any idea why this happens?

I use XC8 as my main compiler

...I don't know what you mean with "are no longer more" maybe a bug, but please visit the youtube page to see what's going on the video

Yo uso XC8 como mi compilador principal

... no sé lo que quieres decir con "no son más" tal vez un error, pero por favor, visite la página de youtube para ver lo que está pasando en el video
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: Nocturno en 29 de Julio de 2013, 01:03:36
Yo he visto bien el vídeo, Marcos, ¿lo ves bien ya o será algo de tu pc?
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: stk500 en 29 de Julio de 2013, 03:44:58
yo veo el video perfecto!

I see it very well.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 10 de Agosto de 2013, 17:41:09
there again!!

This is the second video about the CAN Bus board V2,  with PIC18F26K80, on this, I'm testing the Touch Sensor Library that I made.

In the first channel there are two simple Touch Sensors Buttons, debugged at 0:41, (*.csv file), and in the channel two there is a Slide Touch Sensor, debugged at 0:49, to see the value from the Slid, which is a unsigned int (16 bit) I moved to the ECCP, to the PWM register, and you can see the dimmer action over the LED, adn the oscilloscope at 1:08.

At the very end, you can see the two sensors'value and the result of it at 1:31



Este es el segundo video sobre el CAN Bus tablero V2, con PIC18F26K80, en esto, estoy probando la Biblioteca del sensor táctil que hice.

En el primer canal hay dos sensores táctiles simples botones, depuradas en doce y cuarenta y uno, (*. Csv) y en el canal dos hay un Sensor Touch Slide, depurado a doce y cuarenta y nueve minutos, para ver el valor de la Slid , que es un entero sin signo (16 bits), me trasladé a la PECC, en el registro PWM, y se puede ver la acción más tenue sobre el LED, adn el osciloscopio a las 1:08.

Al final, se puede ver los dos sensors'value y el resultado de la misma a las 1:31


A quick question: how can I share my library?, I've seen those "windows"  where u share your code and can scroll it
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 10 de Agosto de 2013, 18:58:23
(http://imageshack.us/a/img547/7927/p1xv.png)

(http://imageshack.us/a/img23/1768/o5hj.png)
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 10 de Agosto de 2013, 20:54:28
here is the library:

aquí está la biblioteca with XC8 Compiler:

CTMU.C


Código: C
  1. /************ CTMU.c *********/
  2.  
  3. #include "CTMU.h"
  4. #include "stdio.h"
  5.  
  6.  
  7.  
  8. /** struct where the values for every touch sensor saves its own values **/
  9. typedef struct _TOUCH_SENSOR
  10. {
  11.         unsigned int            Threshold;              // Un-pressed Sensor value.
  12.         unsigned char   Trip;                   // Difference between pressed and un-pressed switch.
  13.         unsigned char   Hysteresis;             // Amount to change.
  14.         unsigned char   SensorState;    // Actual Sensor State.
  15.         unsigned int            SensorRead;             // ADC value.
  16.         } TOUCH_SENSOR;
  17.  
  18. volatile TOUCH_SENSOR sensors [ NUMBER_OF_TOUCH_SENSORS ];
  19.  
  20. /*******************************************************************/
  21. /*      -SetUpCTMU ( Edges Configurtion, Current Source,
  22.                                 Edge 2 Polarity, Edge 1 Polarity,
  23.                                 Current Source Range )
  24. /*              -Edges Configurtion
  25. /*              -Current Source
  26. /*              -Edge 2 Polarity
  27. /*              -Edge 1 Polarity
  28. /*              -Current Source Range
  29. /*              *configures the CTMU Port.
  30. /*
  31. /*      -SetUpTouchSensor ( TouchSensorNumber, Threshold
  32. /*                                              Trip, Hysteresis,
  33. /*                                              ChargeDelay, DischargeDelay )
  34. /*              -TouchSensorNumber
  35. /*              -Threshold
  36. /*              -Trip
  37. /*              -Hysteresis
  38. /*              -ChargeDelay
  39. /*              -DischargeDelay
  40. /*              *sets the Touch Sensor Channel to be read.
  41. /*
  42. /*      -DecodeTouchSensor ( TouchSensorNumber )
  43. /*              -TouchSensorNumber
  44. /*              *Returns the value stored in ptrSensor -> SensorState
  45. /*               if pressed = 1; else = 0.
  46. /*
  47. /*      -DebbugTouchSensor ( TouchSensorNumber, TouchSensorNumber )
  48. /*              -TouchSensorNumber
  49. /*              -TouchSensorNumber
  50. /*              *Prints out the value of any two touch sensors
  51. /*
  52. /*      -SliderTouchSensor ( TouchSensorNumber0,  TouchSensorNumber1)
  53. /*              -TouchSensorNumber0
  54. /*              -TouchSensorNumber1
  55. /*              *Returns the unsigned int value ( 16bit) of the Slider Sensor.
  56. /*              *Require two sensors.
  57. /******************************************************************/
  58.  
  59. /********* Configures the CTMU Module Register ********************/
  60. void SetUpCTMU ( unsigned char CTMUConfig0, unsigned char CTMUConfig1,
  61.                                 unsigned char CTMUConfig2, unsigned char CTMUConfig3,
  62.                                 unsigned char CTMUConfig4 )
  63. {
  64.         CTMUCONH = 0x00;                                                        // Set to POR/BOR values.
  65.         CTMUCONL = 0x00;
  66.         CTMUICON = 0x00;       
  67.  
  68.         CTMUCONHbits . EDGEN = CTMUConfig0;     // Edges are blocked.  
  69.         CTMUCONHbits . IDISSEN = CTMUConfig1;   // Analog current source output is not grounded.
  70.                
  71.         CTMUCONLbits . EDG2POL = CTMUConfig2;   // Edge 2 is programmed for a positive edge response.
  72.         CTMUCONLbits . EDG1POL = CTMUConfig3;   // Edge 1 is programmed for a positive edge response.
  73.  
  74.         CTMUICONbits . IRNG = CTMUConfig4;              // Current Source Range Select.
  75.  
  76.         CTMUCONHbits . CTMUEN = ENABLE;         //Enable the CTMU.
  77.         }      
  78.  
  79. /********* Configure the Touch Sensor to use ********************/
  80. void SetUpTouchSensor ( unsigned char TouchSensorNumber, unsigned int Threshold,
  81.                                                 unsigned char Trip, unsigned char Hysteresis,
  82.                                                 unsigned char ChargeDelay, unsigned char DischargeDelay )
  83. {
  84.         TOUCH_SENSOR* ptrSensor;
  85.         ptrSensor = ( TOUCH_SENSOR* ) sensors + TouchSensorNumber;      // Pointing to the Touch Sensor
  86.                                                                                                                                         // to be Set it.
  87.         ptrSensor -> Threshold = Threshold;                                                             // Pasing the values to
  88.         ptrSensor -> Trip = Trip;                                                                                       // the Sensors
  89.         ptrSensor -> Hysteresis = Hysteresis;
  90.         }      
  91.  
  92. /********* Decode the Touch Sensor Selsected; verified if it is Pressed or not ********************/
  93. int DecodeTouchSensor ( unsigned char TouchSensorNumber )
  94. {
  95.         TOUCH_SENSOR* ptrSensor;
  96.         ptrSensor = ( TOUCH_SENSOR* ) sensors + TouchSensorNumber;      // Pointing to the Touch Sensor
  97.                                                                                                                                         // to be Decode it.
  98.         CTMUCONL = CTMUCONL & 0xFC;                                                             // 0xFC = 0b11111100.
  99.  
  100.         ADCON0 &= 0b10000011;                                                                                   // Cleaning up the previous channel.
  101.         ADCON0 |= TouchSensorNumber << 0x02;                                                    // Setting the AD channel to read
  102.                                                                                                                                         // without changing the ADCON0 value.
  103.  
  104.         CTMUCONHbits . IDISSEN = START;                                                 // Drain charge on the circuit.
  105.         __delay_us ( DEFAULT_DISCHARGE_TIME );
  106.         CTMUCONHbits . IDISSEN = STOP;                                                          // End drain of circuit.
  107.         CTMUCONLbits . EDG1STAT = START;                                                        // Begin charging the circuit
  108.                                                                                                                                         // using CTMU current source.
  109.         __delay_us ( DEFAULT_CHARGE_TIME );
  110.         CTMUCONLbits . EDG1STAT = STOP;                                                         // Stop charging circuit.
  111.  
  112.         ADCON0bits . GO = 0x01;                                                                         // Starts the reading of the capacitive sensor.                        
  113.         while ( ADCON0bits . GO );                                                                              // Wait until convertion is done.
  114.  
  115.         ptrSensor -> SensorRead = ( ( ( unsigned int ) ADRESH ) << 8 ) |        
  116.                         ( ADRESL );                                                                                             // Return the value from two Bytes.
  117.  
  118.         CTMUCONHbits . IDISSEN = START;                                                 // Drain charge on the circuit.
  119.        
  120.         if ( ptrSensor -> SensorRead < DEFAULT_THRESHOLD - DEFAULT_TRIP )
  121.         {
  122.                 ptrSensor -> SensorState = PRESSED;
  123.                 }      
  124.  
  125.         else if ( ptrSensor -> SensorRead > DEFAULT_THRESHOLD - DEFAULT_TRIP + \
  126.                         DEFAULT_HYST )
  127.         {
  128.                 ptrSensor -> SensorState = UNPRESSED;
  129.                 }      
  130.  
  131.         return ptrSensor -> SensorState;
  132.         }
  133.  
  134. /********* Debug the touch Sensor; debug propouse ********************/
  135. void DebbugTouchSensor ( unsigned char TouchSensorNumber0, unsigned char TouchSensorNumber1 )
  136. {
  137.         TOUCH_SENSOR* ptrSensor0;
  138.         ptrSensor0 = ( TOUCH_SENSOR* ) sensors + TouchSensorNumber0;            // Pointing to the Touch Sensor
  139.                                                                                                                                                         // to be Decode it.
  140.         TOUCH_SENSOR* ptrSensor1;
  141.         ptrSensor1 = ( TOUCH_SENSOR* ) sensors + TouchSensorNumber1;                    // Pointing to the Touch Sensor
  142.                                                                                                                                                         // to be Decode it.
  143.  
  144.         printf ( " \n%d,%d", ptrSensor0 -> SensorRead   , ptrSensor1 -> SensorRead );   // Printing out the actual value
  145.                                                                                                                                                         // on the sensor selected.
  146.         }
  147.        
  148. /********* Return the Slider Value Selected ********************/
  149. unsigned int CurrentSliderVal;
  150.  
  151. int SliderTouchSensor ( unsigned char SlideSensorNumber0, unsigned char SlideSensorNumber1 )
  152. {
  153.         unsigned int SliderTouchSensorValue, SliderTempVal;
  154.         unsigned char Sensor0, Sensor1;
  155.        
  156.         Sensor0 = DecodeTouchSensor ( SlideSensorNumber0 );
  157.         Sensor1 = DecodeTouchSensor ( SlideSensorNumber1 );
  158.  
  159.         TOUCH_SENSOR* ptrSlideSensor0;
  160.         ptrSlideSensor0 = ( TOUCH_SENSOR* ) sensors + SlideSensorNumber0;       // Pointing to the Touch Sensor
  161.                                                                                                                                                         // to be Read.
  162.         TOUCH_SENSOR* ptrSlideSensor1;
  163.         ptrSlideSensor1 = ( TOUCH_SENSOR* ) sensors + SlideSensorNumber1;               // Pointing to the Touch Sensor
  164.                                                                                                                                                         // to be Read.
  165.         SliderTouchSensorValue = CurrentSliderVal;
  166.  
  167.         if ( ( Sensor0 ) || ( Sensor1 ) )
  168.         {
  169.                 SliderTempVal = ( ptrSlideSensor0 -> SensorRead * 3 ) - ( ptrSlideSensor1 -> SensorRead );
  170.        
  171.                 SliderTouchSensorValue = SliderTempVal / FACTOR_10BIT_RESOLUTION
  172.                                                                 - DIFFERENTIAL;
  173.                 CurrentSliderVal = SliderTempVal / FACTOR_10BIT_RESOLUTION
  174.                                                         - DIFFERENTIAL;
  175.                 }      
  176.  
  177.         return ( SliderTouchSensorValue );
  178.         }


here is the CTMU.h

Código: C
  1. /************ CTMU.h *********/
  2.  
  3. /********* A/D Port Configuration Control bits ********/
  4. #define TOUCH_SENSOR_ZERO               0x00    // The same as ADC channels.
  5. #define TOUCH_SENSOR_ONE                        0x01
  6. #define TOUCH_SENSOR_TWO                        0x02
  7. #define TOUCH_SENSOR_THREE              0x03
  8. #define TOUCH_SENSOR_FOUR                       0x04
  9.  
  10. /********* Edge Enable bit ********/
  11. #define EDGE_NOT_BLOCKED                        0x01
  12. #define EDGE_BLOCKED                            0x00
  13.  
  14. /********* Edge Sequence Enable ********/
  15. #define CURRENT_GROUNDED                        0x01
  16. #define CURRENT_NOT_GROUNDED    0x00
  17.  
  18. /********* Edge 2 Polarity Select bit ********/
  19. #define EDGE_2_POSITIVE                         0x01
  20. #define EDGE_2_NEGATIVE                 0x00
  21.  
  22. /********* Edge 1 Polarity Select bit ********/
  23. #define EDGE_1_POSITIVE                         0x01
  24. #define EDGE_1_NEGATIVE                         0x00
  25.  
  26. /********* Current Source Range Select bits ********/
  27. #define BASE_CURRENT_100                        0x03
  28. #define BASE_CURRENT_10                         0x02
  29. #define BASE_CURRENT_550nA                      0x01
  30. #define CURRENT_DISABLED                        0x00
  31.  
  32.  
  33. /********* Values to Set The Touch Sensors ********/
  34. #define DEFAULT_THRESHOLD                       2500    // Un-pressed switch value.
  35. #define DEFAULT_TRIP                                    100             // Difference between pressed and un-pressed switch.
  36.                                                                                                
  37. #define DEFAULT_HYST                            65              // Amount to change from pressed to un-pressed.
  38.                                                                                                  
  39. #define DEFAULT_CHARGE_TIME             2               // Time to charge and discharge.
  40. #define DEFAULT_DISCHARGE_TIME  35              // Time to discharge and discharge.
  41.  
  42.  
  43. /********* General Registers ********/
  44. #define ENABLE                                          0x01
  45. #define DISABLE                                         0x00
  46.        
  47. #define START                                                   0x01
  48. #define STOP                                                    0x00
  49.  
  50. #define PRESSED                                                 0x01    // Decoding the Touch Semsors.
  51. #define UNPRESSED                                       0x00
  52.  
  53.  
  54. /********* General Registers for Slider Tocuh Sensor ********/
  55. #define FACTOR_10BIT_RESOLUTION 0x05    // Factors for the Slider
  56. #define DIFFERENTIAL                                    0x12C  
  57.  
  58.  
  59. /********* Number of Sensors to be read in the uC ********/
  60. #define NUMBER_OF_TOUCH_SENSORS 0x05    // Number of Sensors to be read in the uC.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 10 de Agosto de 2013, 20:58:01
here is one example how get the sensor as a button with PIC18F26K80


aquí es un ejemplo de cómo sacar el sensor como un botón con PIC18F26K80

Main.c file
Código: C
  1. #include        <xc.h>
  2.  
  3. #define _XTAL_FREQ      FREQ_16MHz
  4.  
  5. #include "SetUp.c"
  6.  
  7. bit Button0, Button1;
  8.  
  9. void main ( void )       //@0x100
  10. {
  11.         SetUp ( );
  12.  
  13.         SetUpCTMU ( EDGE_BLOCKED, CURRENT_NOT_GROUNDED,
  14.                                 EDGE_2_POSITIVE, EDGE_1_POSITIVE,
  15.                                 BASE_CURRENT_100 );
  16.        
  17.         SetUpTouchSensor ( TOUCH_SENSOR_ONE, DEFAULT_THRESHOLD,
  18.                                                 DEFAULT_TRIP, DEFAULT_HYST, DEFAULT_CHARGE_TIME,
  19.                                                 DEFAULT_DISCHARGE_TIME );
  20.  
  21.         SetUpTouchSensor ( TOUCH_SENSOR_TWO, DEFAULT_THRESHOLD,
  22.                                                 DEFAULT_TRIP, DEFAULT_HYST, DEFAULT_CHARGE_TIME,
  23.                                                 DEFAULT_DISCHARGE_TIME );
  24.  
  25.         printf ( " \n\f Sensor1, Sensor2... " );
  26.        
  27.         while ( TRUE )
  28.         {
  29.                 Button0 = DecodeTouchSensor ( TOUCH_SENSOR_ONE );
  30.                 Button1 = DecodeTouchSensor ( TOUCH_SENSOR_TWO );
  31.                
  32.                 if ( !PORTBbits . RB7 )                                 // For debbuging propouses.
  33.                         DebbugTouchSensor (     TOUCH_SENSOR_ONE, TOUCH_SENSOR_TWO      );
  34.  
  35.                 LED1_OFF;
  36.                 LED2_OFF;
  37.  
  38.                 if ( Button0 )
  39.                 {
  40.                         LED1_ON;
  41.                         }      
  42.                 if ( Button1 )
  43.                 {
  44.                         LED2_ON;
  45.                         }
  46.                 }              
  47.         }


and here is the SetUp.c file

Código: C
  1. /* CONFIG1L ************************/
  2. #pragma config  XINST = OFF                     // Extended Instruction Set.
  3. #pragma config  SOSCSEL = DIG                   // SOSC Power Selection and Mode Configuration.
  4. #pragma config  INTOSCSEL = HIGH        // LF-INTOSC Low-power.
  5. #pragma config  RETEN = OFF                     // VREG Sleep.
  6.  
  7. /* CONFIG1H ************************/
  8. #pragma config  IESO = OFF                              // Internal/External Oscillator Switchover.
  9. #pragma config  FCMEN = OFF                     // Fail-Safe Clock Monitor.
  10. #pragma config  PLLCFG = OFF                    // 4X PLL.
  11. #pragma config  FOSC = INTIO2                   // Oscillator.
  12.  
  13. /* CONFIG2L ************************/
  14. #pragma config  BORPWR = ZPBORMV        // BORMV Power-Level.
  15. #pragma config  BORV = 0x03                     // Brown-out Reset Voltage.
  16. #pragma config  BOREN = SBORDIS         // Brown-out Reset Enable.
  17. #pragma config  PWRTEN = ON                     // Power-up Timer.
  18.  
  19. /* CONFIG2H ************************/
  20. #pragma config  WDTPS = 0x01                    // Watchdog Timer Postscale.
  21. #pragma config  WDTEN = OFF                     // Watchdog Timer Enable.
  22.  
  23. /* CONFIG3H ************************/
  24. #pragma config  MCLRE = ON                      // MCLR Pin Enable.
  25. #pragma config  MSSPMSK = MSK7          // MSSP V3 7-Bit Address Masking Mode.
  26. #pragma config  CANMX = PORTB           // ECAN MUX.
  27.  
  28. /* CONFIG4L ************************/
  29. #pragma config  BBSIZ = BB1K                    // Boot Block Size.
  30. #pragma config  STVREN = ON                     // Stack Full/Underflow Reset.
  31.  
  32. /* CONFIG5L ************************/
  33. #pragma config  CP3 = OFF                               // Code Protection.
  34. #pragma config  CP2 = OFF                               // Code Protection.
  35. #pragma config  CP1 = OFF                               // Code Protection.
  36. #pragma config  CP0 = OFF                               // Code Protection.
  37.  
  38. /* CONFIG5H ************************/
  39. #pragma config  CPD = OFF                               // Data EEPROM Code Protection.
  40. #pragma config  CPB = OFF                               // Boot Block Code Protection.
  41.  
  42. /* CONFIG6L ************************/
  43. #pragma config  WRT3 = OFF                              // Write Protection.
  44. #pragma config  WRT2 = OFF                              // Write Protection.
  45. #pragma config  WRT1 = OFF                                      // Write Protection.
  46. #pragma config  WRT0 = OFF                              // Write Protection.
  47.  
  48. /* CONFIG6H ************************/
  49. #pragma config  WRTD = OFF                              // Data EEPROM Write.
  50. #pragma config  WRTB = OFF                              // Boot Block Write Protection.
  51. #pragma config  WRTC = OFF                              // Configuration Register Write.
  52.  
  53. /* CONFIG7L ************************/
  54. #pragma config  EBTR3 = OFF                             // Table Read Protection.
  55. #pragma config  EBTR2 = OFF                             // Table Read Protection.
  56. #pragma config  EBTR1 = OFF                             // Table Read Protection.
  57. #pragma config  EBTR0 = OFF                             // Table Read Protection.
  58.  
  59. /* CONFIG7H ************************/
  60. #pragma config  EBTRB = OFF                             // Boot Block Table Read Protection.
  61.  
  62.  
  63. #if     defined ( _PIC18F26K80_H_ )
  64.         #define FREQ_64MHz      64000000
  65.         #define FREQ_16MHz      16000000
  66.         #define FREQ_8MHz       8000000
  67.         #define FREQ_4MHz       4000000
  68.         #define FREQ_1MHz               1000000
  69. #endif
  70.  
  71. #define TRUE            0x01
  72. #define FALSE           0x00
  73.  
  74. #include "Oscillator.c"
  75. #include "UART.c"
  76. #include "ADC.c"
  77. #include "CTMU.c"
  78. #include "PullUps.c"
  79. #include "stdio.h"
  80.  
  81.  
  82.  
  83. #define TRUE    0x01
  84. #define FALSE   0x00
  85.  
  86. #define LED1_ON         PORTCbits . RC2 = 0x01;
  87. #define LED2_ON         PORTCbits . RC3 = 0x01;
  88.  
  89. #define LED1_OFF                PORTCbits . RC2 = 0x00;
  90. #define LED2_OFF                PORTCbits . RC3 = 0x00;
  91.  
  92.  
  93. void SetUp ( void )
  94. {
  95.         SetUpOscillator ( OSC_16MHz );
  96.  
  97.         TRISC = 0x00;
  98.  
  99.         TRISB = 0x08;
  100.         EnablePullUps ( WPU7 );
  101.  
  102.         CANCON = 0;
  103.         CANSTAT = 0;
  104.         ECANCON = 0b10000000;
  105.  
  106.         SetUpUART ( BAUD_RATE_57600 );
  107.        
  108.         SetUpADC ( sAN1 | sAN2, RIGHT_JUSTIFIED, VDD_VSS, FOSC_32 );
  109.  
  110.         LED1_OFF;
  111.         LED2_OFF;
  112.         }
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: stk500 en 11 de Agosto de 2013, 05:04:24
Very nice, Fein work..
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 27 de Agosto de 2013, 23:44:47
hey there

for those who program with CCS, here is the same program as above, you will see about 300 words in this program, instead 1000 and something with XC8 (3 to 4 times bigger).

Hola

para aquellos que programa con CCS, aquí es el mismo programa que el anterior, verá a unos 300 palabras en este programa, en vez 1000 y algo con XC8 (3 a 4 veces más grande)


the rest of the files are pretty much as  i do my libraries, and i think can be done easily and intuitive to follow. (just read the datasheet)
el resto de los archivos son más o menos lo que yo hago mis bibliotecas, y creo que se puede hacer fácilmente e intuitivo a seguir.(simplemente leer la hoja de datos)
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 28 de Agosto de 2013, 00:11:56
Queda mas grande el programa en XC8 que el mismo en CCS ??
Que nivel de optimizacion usas ??

It is the largest program XC8 the same in CCS??
What level of optimization you use??
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 28 de Agosto de 2013, 01:09:52
Sadly I'm poor, so I can't afford the PRO version, so I use the FREE one which spend more instructions (as attached image shows), and runs a little bit more slow, because the extra instructions, but instead the CCS does not do that, but has some lacks, like linkers, Data Memory write, etc.

so it's up to you

Por desgracia yo soy pobre, así que no puedo permitirme la versión PRO, así que uso el libre que pasar más instrucciones (como se muestra en la imagen adjunta), y corre un poco más lento, porque las instrucciones adicionales, pero en lugar el CCS no lo hace, pero tiene algunas carencias, como conectores, escribir en la memoria de datos, etc

por lo que depende de ti

(http://imageshack.us/a/img542/9494/kfu9.jpg)
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 28 de Agosto de 2013, 08:36:27
No te preocupes, has entrado en el Foro correcto.
Aqui todos somos pobres !!  :D :D :D
Solamente que me llamo la atencion que el compilador de CCS optimizara mejor, ya que por defecto esta programado que usa el nivel medio de optimizacion.
Que version del compilador de CCS utilizas??

Por otro lado, en el programa que escribiste para CCS, configuras el reloj para 16 MHz, tu usas en esa aplicacion el reloj interno o un resonador o cristal externo?

Do not worry, you have entered the correct forum.
Here are all poor!  :D :D
Only to my attention that the CCS compiler optimizes better, because the default is programmed using the average level of optimization.
What version of the CCS compiler use??

On the other hand, in the program you wrote for CCS, you set the clock to 16 MHz, you use it in this application the internal clock or an external crystal or resonator?
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 28 de Agosto de 2013, 09:24:02
Si intento compilar tu aplicacion tal cual esta,  me da una gran cantidad de errores, hay muchas librerias que no estan y hay muchos errores provocados por GETENV.
Podras subir la aplicacion completa??
Gracias.


If I try to compile your application as it is, gives me a lot of errors, there are many libraries that are not and there are many errors caused by GETENV.
You can upload the completed application?
Thank you.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 28 de Agosto de 2013, 22:54:36
man, damn it!!!!!  i got to write it again, seems that waste much time...... shoot (didn't publish the first time)

OK here is again...

yes, i always use uC with internal Oscillators.
CCS v 4.12 (XC8 v1.2 if u want to know)


and for the rest, let me explain u some tricks over here, I use my own libraries for two reasons:
1) I really like to understand what I'm doing, so I spend some time reading datasheets (It's very important to REALLY understand whats going on on ur application, PCB and firmware) and there is no other way to spend some time to get it, I must confess I've invest more time trying to understand how the things work than making them work, but I like it, I really KNOW how they work. and of course, reading some others libraries (like Microchip's) and examples and over here, etc, believe me, I'm in the process of learning (still).
2)If u use someone else's libraries (like Microchip), most people don't bother read the whole thing, because it's already running the application, and because of that don't know how it works, Am I right¿ and sometimes, actually all the time, u can optimize the application because u do what u really need o want to do.


So after the Litany, here's a trick:

rather than use "getenv" u can use the registers' address. here is an example:

//#BYTE PORTA = getenv("SFR:PORTA")          //0xF92.
#BYTE PORTA = 0xF92

that's why I comment the address at the end, but not anymore, because if u use "getenv" u can get the address automatically.

for doing that u should look at the datasheet (again) and get the address manually, for the last example go to datasheet PIC18F26K80 page 111, and u will see all registers and get the actual address u need, the problem doing this way is that you need to change the address every time u change the pic, that's why I use getenv.... I still don't know why doesn't work with you!!!!


the other trick is doing your own "register map" or werever u want to call it, such as this one:



/* OSCCON: OSCILLATOR CONTROL REGISTER  pag 53*/
enum SystemClock            
{
   InternalOscillatorBlock   = 0x02,
   SecondaryOscillator      = 0x01,
   PrimaryClock            = 0x00
   };
enum InternalRCOscillatorFrequency            
{
   INTOSC16MHz   = 0x07,      // Values.
   INTOSC8MHz   = 0x06,   
   INTOSC4MHz   = 0x05,      
   INTOSC2MHz   = 0x04,      
   INTOSC1MHz   = 0x03,   
   INTOSC500kHz   = 0x02,
   INTOSC250kz   = 0x01,
   INTOSC31kHz   = 0x00
   };
      
struct
{
   SystemClock                     SCS : 2;      // 1:0 System Clock Select bit.
   int1   HFIOFS;                           // 2 HFINTOSC Frequency Stable bit.
   int1   OSTS;                              // 3 Oscillator Start-up Time-out Status bit.
   InternalRCOscillatorFrequency      IRCF : 3;   // 6:4 Internal RC Oscillator Frequency Select bits.
   int1   IDLEN;                              // 7 Idle Enable bit.
   } OSCCON;
//#BYTE OSCCON = getenv("SFR:OSCCON")    //0xFD3.
//or
#BYTE OSCCON = 0xFD3

IMPORTANT NOTE: Read the datasheet once again!!!!!!

then u can use them  as STRUCT in your own library!!!!!, just like this:

// Oscillator.h

#include "OscillatorRegisters.h"

   #define      OSC_64MHz   0x0A   // Any number.
   #define      OSC_16MHz      0x07   // 0bx111xxxxx.
   #define      OSC_8MHz      0x06   // 0bx110xxxxx.
   #define      OSC_4MHz      0x05   // 0bx101xxxx.
   #define      OSC_2MHz      0x04   // 0bx100xxxx.
   #define      OSC_1MHz      0x03   // 0bx011xxxx.
   #define      OSC_500kHz   0x02   // 0bx010xxxx.
   #define      OSC_250kHz   0x01   // 0bx001xxxx.
   #define      OSC_31kHz      0x00   // 0bx000xxxx.


#include   "Oscillator.h"

/*******************************************************************/
/*   -SetUpOscillator ( Frequency )
/*      -Frequency - at the uC will run.
/*   
/*   Note: This library just run for Internal Oscillator.
/******************************************************************/
void SetUpOscillator ( unsigned char Frequency )
{
   OSCCON = 0x00;            // Set to POR/BOR default values.

#if   defined ( _PIC18F26K80_H_ ) || defined ( _PIC18F45K22_H_ )
   if ( Frequency == OSC_64MHz )
   {
      OSCCON . IRCF = OSC_16MHz;
      OSCTUNE . PLLEN = 0x01;    // Frequency Multiplier PLL Enable.
      }   
   else
      OSCCON . IRCF = Frequency;   // Passing the Fequency value.

#elif   defined ( _PIC16F887_H_ ) || defined ( _PIC16F886_H_ ) || defined ( _PIC12F683_H_ )
   OSCCON . OSTS = 0x00;      // Internal oscillator.
   OSCCON . SCS = 0x01;      // Internal oscillator = system clock.
   OSCCON . HTS = 0x01;      // OSC stable.
         
   OSCCON |= Frequency;         // Passing the Fequency value.
#endif
   }

U got the main idea, I think it is better to show u how to do it (and WE can learn something from it) than give it, and once again, don't learn nothing..... Am I wrong¿¿¿

but it is OK, we are here to learn something, so if I can help u with anything, sure just ask please, because I'm pretty sure that if I'm stuck, u'd help, right¿¿


hombre , maldita sea ! ! ! tengo que escribirlo de nuevo, parece que he perder demasiado tiempo ...... disparar ( no publicó la primera vez)


Bien aquí es de nuevo ...

sí, yo siempre utilizo uC con osciladores internos.
CCS v 4.12 ( XC8 v1.2 si quieres saber)


y para el resto , permítanme explicar u algunos trucos de aquí , yo uso mis propias bibliotecas , por dos razones :
1 ) Me gusta entender lo que estoy haciendo , por lo que pasar algún tiempo leyendo las hojas de datos (es muy importante para entender realmente lo que pasa en la aplicación ur , PCB y firmware) y no hay otra manera de pasar algún tiempo para que , debo confesar que he invierto más tiempo tratando de entender cómo funcionan las cosas que hacer que funcionen, pero me gusta , lo que realmente saben cómo funcionan. y por supuesto , la lectura de algunas otras bibliotecas (como las de Microchip ) y ejemplos y por aquí, etc , créeme , estoy en el proceso de aprendizaje (aún) .
2 ) En caso de uso u otra persona bibliotecas (como Microchip ) , la mayoría de las personas no se molestan en leer toda la cosa, porque ya está ejecutando la aplicación , y debido a que no saben cómo funciona, ¿ Estoy en lo cierto y, a veces , En realidad todo el tiempo , u puede optimizar la aplicación, ya que u hacer lo que u realmente necesita o quiere hacer.


Así que después de la Letanía , aquí hay un truco :

en lugar de utilizar " getenv " u puede utilizar la dirección de los registros . Aquí está un ejemplo:

/ / # BYTE PORTA = getenv ( " SFR : PORTA ") / / 0xF92 .
# BYTE PORTA = 0xF92

es por eso que comento la dirección al final , pero ya no, porque si u utilizar " getenv " u puede obtener la dirección automáticamente.

para hacer que u debe mirar la hoja de datos ( de nuevo) y obtener la dirección manualmente , para el último ejemplo ir a la ficha técnica PIC18F26K80 página 111 , yu ver todos los registros y obtener la necesidad u dirección real , el problema haciendo de esta manera es que necesita cambiar la dirección cada vez u cambiar la imagen, es por eso que uso getenv .... Todavía no sé por qué no trabajar con usted! !


Por otro truco está haciendo su propia "hoja de registro " o werever u quiera llamarlo, como este :



/ * OSCCON : OSCILADOR DE REGISTRO DE CONTROL pag 53 * /
enumeración SystemClock
{
InternalOscillatorBlock = 0x02 ,
SecondaryOscillator = 0x01 ,
PrimaryClock = 0x00
} ;
enumeración InternalRCOscillatorFrequency
{
INTOSC16MHz = 0x07 , / / Valores .
INTOSC8MHz = 0x06 ,
INTOSC4MHz = 0x05 ,
INTOSC2MHz = 0x04 ,
INTOSC1MHz = 0x03 ,
INTOSC500kHz = 0x02 ,
INTOSC250kz = 0x01 ,
INTOSC31kHz = 0x00
} ;

struct
{
SystemClock SCS : 2 / / 01:00 reloj del sistema Seleccione bits .
INT1 HFIOFS ; / / 2 HFINTOSC Frecuencia de bits estable.
INT1 OSTS ; / / 3 Oscilador Start -up Time-out bits de estado.
InternalRCOscillatorFrequency IRCF : 3 / / 06:04 internos RC oscilador de frecuencia de bits de selección .
INT1 IDLEN / / 7 bit Enable Idle .
} OSCCON ;
/ / # BYTE OSCCON = getenv ( " SFR : OSCCON ") / / 0xFD3 .
/ / o
# BYTE OSCCON = 0xFD3

NOTA IMPORTANTE : [b ] Lea la hoja de datos , una vez más [/ b] ¡¡¡ ¡¡¡

entonces u puede utilizar como STRUCT en su propia biblioteca, al igual que este ! ! ! :

/ / Oscillator.h

# include " OscillatorRegisters.h "

# define OSC_64MHz 0x0A / / cualquier número.
# define OSC_16MHz 0x07 / / 0bx111xxxxx .
# define OSC_8MHz 0x06 / / 0bx110xxxxx .
# define OSC_4MHz 0x05 / / 0bx101xxxx .
# define OSC_2MHz 0x04 / / 0bx100xxxx .
# define OSC_1MHz 0x03 / / 0bx011xxxx .
# define OSC_500kHz 0x02 / / 0bx010xxxx .
# define OSC_250kHz 0x01 / / 0bx001xxxx .
# define OSC_31kHz 0x00 / / 0bx000xxxx .


# include " Oscillator.h "

/ ************************************************* ****************** /
/ * - SetUpOscillator (Frecuencia)
/ * -Frequency - a la UC se ejecutará.
/ *
/ * Nota : Esta biblioteca sólo funciona para el oscilador interno .
/ ************************************************* ***************** /
void SetUpOscillator ( Frecuencia unsigned char )
{
OSCCON = 0x00 ; / / Establecer los valores predeterminados POR / BOR .

# if defined ( _PIC18F26K80_H_ ) | | define ( _PIC18F45K22_H_ )
if ( Frecuencia == OSC_64MHz )
{
OSCCON . IRCF = OSC_16MHz ;
OSCTUNE . PLLEN = 0x01 ; / / Multiplicador de frecuencia PLL Enable .
}
más
OSCCON . IRCF = Frecuencia / / Pasar el valor fequency .

# elif definido ( _PIC16F887_H_ ) | | define ( _PIC16F886_H_ ) | | define ( _PIC12F683_H_ )
OSCCON . OSTS = 0x00 ; oscilador / / Interna .
OSCCON . SCS = 0x01 ; / / Interna oscilador = reloj del sistema.
OSCCON . HTS = 0x01 ; / / OSC estable.

OSCCON | = Frecuencia / / Pasar el valor fequency .
# endif
}

U consiguió la idea principal, creo que es mejor mostrar u cómo hacerlo ( y podemos aprender algo de ella ) que le dan , y una vez más , no aprenden nada ..... ¿Me equivoco ¿¿¿

pero está bien, estamos aquí para aprender algo, por lo que si te puedo ayudar u con cualquier cosa, que acaba de pedir por favor, porque estoy bastante seguro de que si estoy atascado, ayuda u'd, ¿no ¿¿


seem that when google translate it for me, in the library make some change, but the original still up there!!!!

hope u can enjoy it as I do ....
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: MGLSOFT en 28 de Agosto de 2013, 23:12:49
Usas CCS 4.012 o CCS 4.120 ??
Hay una gran diferencia entre esas versiones, por eso pregunto...

Respecto a GETENV, el compilador o protesta por el uso de la instruccion, sino por el nombre de la direccion de memoria que buscas con la instruccion Getenv.
Como dices bien, es facil de arreglar...

Yo tambien leo mucho de cada hoja de datos para sacar el mejor provecho de una aplicacion, pero aun asi, uso el CCS porque me ayuda mucho en el desarrollo.

Seguramente tu usas el CCS Compiler desde dentro del MPlab, y esa puede ser la razon por la cual si has compilado esa aplicacion, a ti te funcione y a mi aun no.

Puedes subir el archivo .hex ya compilado, para intentar probarlo en la practica ??

Desde ya te agradezco las molestias que has tomado para mostrarnos el uso de tu codigo.


You use CCS 4.012 or CCS 4.120??
There is a big difference between those versions, so I ask ...

Regarding GETENV, the compiler or protest the use of the instruction, but by the name of the memory address you want to getenv instruction.
As you say, it is easy to fix ...

I also read a lot of each sheet to make the most of an application, but still, use the CCS because it helps me a lot in the development.

Surely you are using the CCS Compiler from within MPLAB, and that may be the reason why if you compiled the application, you will work and I have not.

You can upload the file. Hex and compiled, to try to prove it in practice?

Of course I appreciate the trouble you have taken to show the use of your code.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 28 de Agosto de 2013, 23:43:34
hey hey hey my man

of course i share my hex file, but remember, because i did it when i pass it to PIC18F45K22, didn't work because the threshold need another constant (i was using a protoboard), so please try wtih the MPlab, I'd help you to make it run....

(I think the google translation is messing up what i meen, so don't get me wrong.. and i hope u can understand what i want to say)

hey hey hey my man

Por supuesto que comparto mi archivo hex, pero recuerda, ya lo hice cuando me pase a PIC18F45K22, no funcionó debido a que el umbral necesita otra constante (yo estaba usando un protoboard), así que por favor intente con el MPLAB, yo había ayudará a hacer que funcione ....

(Creo que la traducción de Google está arruinando lo que quiero decir, así que no me malinterpreten .. y espero u puede entender lo que quiero decir)
and i use CCS4.120  (sorry, my bad)

the last two files are in CCS, first one PIC18F45K22 and the other one is for the PIC18F26K80


Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 03 de Septiembre de 2013, 00:26:44
hey there

Just testing the CVD Library.

The library come from the AN1298 Application Note, from Microchip.

Even when I try to make some tendence from Proteus' UART, getting done frome the very first time, I didn't know I can do that, with a *.csv file at 0:56, even two touch sensors (no capacitive pads).

At 1:14 testing with a  PIC18F45K22, at 1:20 testing with PIC16F887, at 1:25 testing with a PIC16F886, at 1:31 testing with a PIC18F26K80, and finally at 1:37 testing with a PIC12F683.

So anyway, just as the Application Note said, get it from a ADC channel to get a (int) value as a touch sensor.

I'll upload the library shortly...

Hola

Sólo probar la Biblioteca ECV.

La biblioteca proviene de la aplicación AN1298 Note, de Microchip.

Incluso cuando trato de hacer un poco de Tendence de Proteus 'UART, conseguir que se hagan desde el primer momento, yo no sabía que yo puedo hacer eso con un archivo csv *. A doce y cincuenta y seis, incluso los dos sensores de contacto (sin pastillas capacitivos ).

En las pruebas de 1:14 con una PIC18F45K22, a las 1:20 de pruebas con PIC16F887, en las pruebas de 01:25 con un PIC16F886, en las pruebas de 01:31 con una PIC18F26K80, y, finalmente, en las pruebas de una y treinta y siete con un PIC12F683.

En fin, como dijo el Nota de aplicación, obtener de un canal ADC para obtener un valor (int) como un sensor de contacto.

Voy a subir a la biblioteca en breve ...
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 03 de Septiembre de 2013, 01:11:04
here is the XC8 Library...

CVD.c
Código: C
  1. /************ CVD.c *********/
  2.  
  3. #include "CVD.h"
  4. #include "stdio.h"
  5.  
  6. /** struct where the values for every cvd touch sensor saves its own values **/
  7. typedef struct _CVD_SENSOR
  8. {
  9.         unsigned int            Threshold;              // Un-pressed Sensor value.
  10.         unsigned char   Trip;                   // Difference between pressed and un-pressed switch.
  11.         unsigned char   Hysteresis;             // Amount to change.
  12.         unsigned char   PinRef;                 // Charging Pin to Reference.
  13.         unsigned char   Tris;                   // SFR Tris Register.
  14.         unsigned char   Port;                   // SFR Port Register.
  15.         unsigned char   SensorState;    // Actual Sensor State.
  16.         unsigned int            SensorRead;             // ADC value.
  17.         } CVD_TOUCH_SENSOR;
  18.  
  19. volatile CVD_TOUCH_SENSOR cvd_sensors [ NUMBER_OF_CVD_SENSORS ];
  20.  
  21.  
  22. /*******************************************************************/
  23. /*      -SetUpCVDTouch ( ReferencePin )
  24. /*              -ReferencePin
  25. /*              *configures the Pin which is a reference for touch sensors.
  26. /*              should be high (VDD) to charge and pass voltage to the sensors
  27. /*              internally.    
  28. /*
  29. /*      -SetUpCVDTouchSensor ( CVDSensorNumber, Threshold
  30. /*                                                      Trip, Hysteresis,
  31. /*                                                      ChargingPin, Tris, Port )
  32. /*              -TouchSensorNumber
  33. /*              -Threshold
  34. /*              -Trip
  35. /*              -Hysteresis
  36. /*              -ChargingPin    (reference pin)
  37. /*              -Tris
  38. /*              -Port
  39. /*              *sets the Touch Sensor Channel to be read.
  40. /*
  41. /*      -CVDTouchSensorNumber ( CVDTouchSensorNumber )
  42. /*              -CVDTouchSensorNumber
  43. /*              *Returns the value stored in ptrSensor -> SensorState
  44. /*               if pressed = 1; else = 0.
  45. /*
  46. /*      -DebbugCVDTouchSensor ( TouchSensorNumber, TouchSensorNumber )
  47. /*              -TouchSensorNumber
  48. /*              -TouchSensorNumber
  49. /*              *Prints out the value of any two touch sensors, int (16-bit).
  50. /*
  51. /******************************************************************/
  52.  
  53.  
  54. /********* Configure the CVD Touch Pin Reference ********************/
  55. void SetUpCVDTouch ( unsigned char ReferencePin )
  56. {
  57.         switch ( ReferencePin )
  58.         {
  59.                 case CVD_CH_0:
  60.                         REFERENCE_TRIS_PIN_0 = AS_OUTPUT;       // Chargin pin as output
  61.                         REFERENCE_PIN_0 = TO_VDD;                                       // and logic high.
  62.                         break;
  63.                 case CVD_CH_1:
  64.                         REFERENCE_TRIS_PIN_1 = AS_OUTPUT;       // Chargin pin as output
  65.                         REFERENCE_PIN_1 = TO_VDD;                                       // and logic high.
  66.                         break;
  67.                 case CVD_CH_2:
  68.                         REFERENCE_TRIS_PIN_2 = AS_OUTPUT;       // Chargin pin as output
  69.                         REFERENCE_PIN_2 = TO_VDD;                                       // and logic high.
  70.                         break;
  71.                 case CVD_CH_3:
  72.                         REFERENCE_TRIS_PIN_3 = AS_OUTPUT;       // Chargin pin as output
  73.                         REFERENCE_PIN_3 = TO_VDD;                                       // and logic high.
  74.                         break;
  75. //              case CVD_CH_4:
  76. //                      REFERENCE_TRIS_PIN_4 = AS_OUTPUT;       // Chargin pin as output
  77. //                      REFERENCE_PIN_4 = TO_VDD;                                       // and logic high.
  78. //                      break;
  79.                 case CVD_CH_5:
  80.                         REFERENCE_TRIS_PIN_5 = AS_OUTPUT;       // Chargin pin as output
  81.                         REFERENCE_PIN_5 = TO_VDD;                                       // and logic high.
  82.                         break;
  83.                        
  84.                 default:
  85.                         break;
  86.                 }      
  87.         }      
  88.  
  89.        
  90. /********* Configure the CVD Touch Sensor to use ********************/
  91. void SetUpCVDTouchSensor ( unsigned char CVDSensorNumber, unsigned int Threshold,
  92.                                                         unsigned char Trip, unsigned char Hysteresis,
  93.                                                         unsigned char ChargingPin, unsigned char Tris, unsigned char Port )
  94. {
  95.         CVD_TOUCH_SENSOR* ptrSensor;
  96.         ptrSensor = ( CVD_TOUCH_SENSOR* ) cvd_sensors + CVDSensorNumber;        // Pointing to the Touch Sensor
  97.                                                                                                                                         // to be Set it.
  98.         ptrSensor -> Threshold = Threshold;                                                             // Pasing the values to
  99.         ptrSensor -> Trip = Trip;                                                                                       // the Sensors
  100.         ptrSensor -> Hysteresis = Hysteresis;
  101.         ptrSensor -> PinRef = ChargingPin;
  102.         ptrSensor -> Tris = Tris;
  103.         ptrSensor -> Port = Port;
  104.         }      
  105.  
  106. /********* Decode the Touch Sensor Selsected; verified if it is Pressed or not ********************/
  107. int DecodeCVDTouchSensor ( unsigned char CVDTouchSensorNumber )
  108. {
  109.         CVD_TOUCH_SENSOR* ptrSensor;
  110.         ptrSensor = ( CVD_TOUCH_SENSOR* ) cvd_sensors +         // Pointing to the Touch Sensor
  111.                                 CVDTouchSensorNumber;                                           // to be Decode it.
  112.                                                                                                                                                        
  113.  
  114. #if     defined ( _PIC18F26K80_H_ ) || defined ( _PIC18F45K22_H_ )
  115.         ADCON0 &= 0b10000011;                                           // Cleaning up the previous channel.
  116. #elif   defined ( _PIC16F887_H_ ) || defined ( _PIC16F886_H_ )
  117.         ADCON0 &= 0b11000011;                                           // Cleaning up the previous channel.
  118. #elif defined   ( _PIC12F683_H_ )
  119.         ADCON0 &= 0b11110011;                                           // Cleaning up the previous channel.
  120. #endif
  121.         ADCON0 |= ptrSensor -> PinRef << 2 ;                    // Setting the AD channel to read
  122.                                                                                                 // without changing the ADCON0 value.
  123.         __delay_us ( 20 );
  124.  
  125.         switch ( CVDTouchSensorNumber )
  126.         {
  127.                 case CVD_CH_0:
  128.                         CVD_SENSOR_TRIS_0 = AS_OUTPUT;          // Set Sensing pin as output
  129.                         CVD_SENSOR_PORT_0 = TO_GND;                     // and logic low (discharging it).
  130.                
  131.                         CVD_SENSOR_TRIS_0 = AS_INPUT;           // Sensing pin as input.
  132.                         break;
  133.                 case CVD_CH_1:
  134.                         CVD_SENSOR_TRIS_1 = AS_OUTPUT;          // Set Sensing pin as output
  135.                         CVD_SENSOR_PORT_1 = TO_GND;                     // and logic low (discharging it).
  136.                
  137.                         CVD_SENSOR_TRIS_1 = AS_INPUT;           // Sensing pin as input.
  138.                         break;
  139.                 case CVD_CH_2:
  140.                         CVD_SENSOR_TRIS_2 = AS_OUTPUT;          // Set Sensing pin as output
  141.                         CVD_SENSOR_PORT_2 = TO_GND;                     // and logic low (discharging it).
  142.                
  143.                         CVD_SENSOR_TRIS_2 = AS_INPUT;           // Sensing pin as input.
  144.                         break;
  145.                 case CVD_CH_3:
  146.                         CVD_SENSOR_TRIS_3 = AS_OUTPUT;          // Set Sensing pin as output
  147.                         CVD_SENSOR_PORT_3 = TO_GND;                     // and logic low (discharging it).
  148.                
  149.                         CVD_SENSOR_TRIS_3 = AS_INPUT;           // Sensing pin as input.
  150.                         break;
  151. //              case CVD_CH_4:
  152. //                      CVD_SENSOR_TRIS_4 = AS_OUTPUT;          // Set Sensing pin as output
  153. //                      CVD_SENSOR_PORT_4 = TO_GND;                     // and logic low (discharging it).
  154. //             
  155. //                      CVD_SENSOR_TRIS_4 = AS_INPUT;           // Sensing pin as input.
  156. //                      break;
  157.                 case CVD_CH_5:
  158.                         CVD_SENSOR_TRIS_5 = AS_OUTPUT;          // Set Sensing pin as output
  159.                         CVD_SENSOR_PORT_5 = TO_GND;                     // and logic low (discharging it).
  160.                
  161.                         CVD_SENSOR_TRIS_5 = AS_INPUT;           // Sensing pin as input.
  162.                         break;
  163.                        
  164.                 default:
  165.                         break;
  166.                 }      
  167.  
  168. //      ADCON0 = 0b00000101;                                                    // imediatly pointing ADC to Sense pin.
  169. //      SetADCChannel ( CH_AN2 );
  170. #if     defined ( _PIC18F26K80_H_ ) || defined ( _PIC18F45K22_H_ )
  171.         ADCON0 &= 0b10000011;                           // Cleaning up the previous channel.
  172. #elif   defined ( _PIC16F887_H_ ) || defined ( _PIC16F886_H_ )
  173.         ADCON0 &= 0b11000011;                           // Cleaning up the previous channel.
  174. #elif defined   ( _PIC12F683_H_ )
  175.         ADCON0 &= 0b11110011;                           // Cleaning up the previous channel.
  176. #endif
  177.         ADCON0 |= CVDTouchSensorNumber << 2;    // Setting the AD channel to read
  178.                                                                                 // without changing the ADCON0 value.
  179.  
  180.         ADCON0bits . GO = 0x01;                                                                         // Starts the reading of the capacitive sensor.                        
  181.         while ( ADCON0bits . GO );                                                                              // Wait until convertion is done.
  182.         ptrSensor -> SensorRead = ( ( ( unsigned int ) ADRESH ) << 8 ) |        
  183.                         ( ADRESL );                                                                                             // Return the value from two Bytes.
  184.  
  185.         if ( ptrSensor -> SensorRead < DEFAULT_CVD_THRESHOLD - DEFAULT_CVD_TRIP )
  186.         {
  187.                 ptrSensor -> SensorState = PRESSED;
  188.                 }      
  189.  
  190.         else if ( ptrSensor -> SensorRead > DEFAULT_CVD_THRESHOLD - DEFAULT_CVD_TRIP + \
  191.                         DEFAULT_CVD_HYST )
  192.         {
  193.                 ptrSensor -> SensorState = UNPRESSED;
  194.                 }      
  195.  
  196.         return ptrSensor -> SensorState;
  197.         }
  198.        
  199. /********* Debug the CVD touch Sensor; debug propouse ********************/
  200. void DebbugCVDTouchSensor ( unsigned char TouchSensorNumber0, unsigned char TouchSensorNumber1 )
  201. {
  202.         CVD_TOUCH_SENSOR* ptrSensor0;
  203.         ptrSensor0 = ( CVD_TOUCH_SENSOR* ) cvd_sensors + TouchSensorNumber0;            // Pointing to the Touch Sensor
  204.                                                                                                                                                         // to be Decode it.
  205.         CVD_TOUCH_SENSOR* ptrSensor1;
  206.         ptrSensor1 = ( CVD_TOUCH_SENSOR* ) cvd_sensors + TouchSensorNumber1;                    // Pointing to the Touch Sensor
  207.                                                                                                                                                         // to be Decode it.
  208.  
  209.         printf ( "%d,%d\n", ptrSensor0 -> SensorRead    , ptrSensor1 -> SensorRead );   // Printing out the actual value
  210.                                                                                                                                                         // on the sensor selected.
  211.         }

CVD.h
Código: C
  1. /************ CVD.h *********/
  2.  
  3. /********* A/D Port Configuration Control bits ********/
  4. #define CVD_CH_0        0x00            // The same as ADC channels.
  5. #define CVD_CH_1        0x01
  6. #define CVD_CH_2        0x02
  7. #define CVD_CH_3        0x03
  8. #define CVD_CH_4        0x04
  9. #define CVD_CH_5        0x05
  10. #define CVD_CH_6        0x06
  11. #define CVD_CH_7        0x07
  12. #define CVD_CH_8        0x08
  13.  
  14.  
  15. /********* TRISx Port Configuration Control bits ********/
  16. /*********                                                      ADC pins only ********/
  17. /***** Reference Pin, got to be a ADC Pin ******************/
  18. #define REFERENCE_TRIS_PIN_0    TRISAbits . TRISA0
  19. #define REFERENCE_TRIS_PIN_1    TRISAbits . TRISA1
  20. #define REFERENCE_TRIS_PIN_2    TRISAbits . TRISA2
  21. #define REFERENCE_TRIS_PIN_3    TRISAbits . TRISA3
  22. #define REFERENCE_TRIS_PIN_4    TRISAbits . TRISA4
  23. #define REFERENCE_TRIS_PIN_5    TRISAbits . TRISA5
  24.  
  25. #define REFERENCE_PIN_0                 PORTAbits . RA0
  26. #define REFERENCE_PIN_1                 PORTAbits . RA1
  27. #define REFERENCE_PIN_2                 PORTAbits . RA2
  28. #define REFERENCE_PIN_3                 PORTAbits . RA3
  29. #define REFERENCE_PIN_4                 PORTAbits . RA4
  30. #define REFERENCE_PIN_5                 PORTAbits . RA5
  31.  
  32.  
  33. /********* TRISx Port Configuration Control bits ********/
  34. /*********                                                      ADC pins only ********/
  35. /***** Sensors Pin, got to be a ADC Pin ********************/
  36. #define CVD_SENSOR_TRIS_0               TRISAbits . TRISA0
  37. #define CVD_SENSOR_TRIS_1               TRISAbits . TRISA1
  38. #define CVD_SENSOR_TRIS_2               TRISAbits . TRISA2
  39. #define CVD_SENSOR_TRIS_3               TRISAbits . TRISA3
  40. #define CVD_SENSOR_TRIS_4               TRISAbits . TRISA4
  41. #define CVD_SENSOR_TRIS_5               TRISAbits . TRISA5
  42.  
  43. #define CVD_SENSOR_PORT_0               PORTAbits . RA0
  44. #define CVD_SENSOR_PORT_1               PORTAbits . RA1
  45. #define CVD_SENSOR_PORT_2               PORTAbits . RA2
  46. #define CVD_SENSOR_PORT_3               PORTAbits . RA3
  47. #define CVD_SENSOR_PORT_4               PORTAbits . RA4
  48. #define CVD_SENSOR_PORT_5               PORTAbits . RA5
  49.  
  50.  
  51. /********* General Registers ********/
  52. #define PRESSED         0x01
  53. #define UNPRESSED       0x00
  54.  
  55. #define AS_INPUT                0x01
  56. #define AS_OUTPUT       0x00
  57.  
  58. #define TO_VDD          0x01
  59. #define TO_GND          0x00
  60.  
  61.  
  62. /********* Values to Set The Touch Sensors ********/
  63. #define DEFAULT_CVD_THRESHOLD           300             // 3000; Un-pressed switch value.
  64. #define DEFAULT_CVD_TRIP                                70              // 200; Difference between pressed and un-pressed switch.
  65.                                                                                                
  66. #define DEFAULT_CVD_HYST                                5               // 65; Amount to change from pressed to un-pressed.
  67.  
  68.  
  69. #define NUMBER_OF_CVD_SENSORS   0x05            // Number of Sensors to be read in the uC.
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 03 de Septiembre de 2013, 01:15:38
And right here is a example.... with PIC18F26K80

but it is already tested with PIC18F45K22, PIC18F44K22, PIC16F887, PIC16F886, PIC12F683

main.c
Código: C
  1. #include        <xc.h>
  2.  
  3. #define _XTAL_FREQ      FREQ_16MHz
  4.  
  5. #include "SetUp.c"
  6.  
  7. #define RESET_STATE     0x00
  8.  
  9. void main ( void )       //@0x100
  10. {
  11.         SetUp ( );
  12.  
  13.         LED1_OFF;
  14.         LED2_OFF;
  15.  
  16.         printf ( "Application Ready...\n" );   
  17.         printf ( "CVD:\n" );   
  18.  
  19.         while ( TRUE )
  20.         {
  21.                 __delay_ms ( 15 );
  22.                 TOUCH_SENSORS . Button0 = DecodeCVDTouchSensor ( CVD_CH_1 );
  23.                 TOUCH_SENSORS . Button1 = DecodeCVDTouchSensor ( CVD_CH_2 );
  24.                        
  25.                 LED1_OFF;
  26.                 LED2_OFF;
  27.  
  28.                 if ( TOUCH_SENSORS . Button0 )
  29.                 {
  30.                         LED1_ON;
  31.                         }      
  32.                 if ( TOUCH_SENSORS . Button1 )
  33.                 {
  34.                         LED2_ON;
  35.                         }
  36.  
  37.                 if ( !PORTBbits . RB7 )                                 // For debbuging propouses.
  38.                         DebbugCVDTouchSensor ( CVD_CH_1, CVD_CH_2 );
  39.                 }      
  40.         }

SetUp.c
Código: C
  1. /* CONFIG1L ************************/
  2. #pragma config  XINST = OFF                     // Extended Instruction Set.
  3. #pragma config  SOSCSEL = DIG                   // SOSC Power Selection and Mode Configuration.
  4. #pragma config  INTOSCSEL = HIGH        // LF-INTOSC Low-power.
  5. #pragma config  RETEN = OFF                     // VREG Sleep.
  6.  
  7. /* CONFIG1H ************************/
  8. #pragma config  IESO = OFF                              // Internal/External Oscillator Switchover.
  9. #pragma config  FCMEN = OFF                     // Fail-Safe Clock Monitor.
  10. #pragma config  PLLCFG = OFF                    // 4X PLL.
  11. #pragma config  FOSC = INTIO2                   // Oscillator.
  12.  
  13. /* CONFIG2L ************************/
  14. #pragma config  BORPWR = ZPBORMV        // BORMV Power-Level.
  15. #pragma config  BORV = 0x03                     // Brown-out Reset Voltage.
  16. #pragma config  BOREN = SBORDIS         // Brown-out Reset Enable.
  17. #pragma config  PWRTEN = ON                     // Power-up Timer.
  18.  
  19. /* CONFIG2H ************************/
  20. #pragma config  WDTPS = 0x01                    // Watchdog Timer Postscale.
  21. #pragma config  WDTEN = OFF                     // Watchdog Timer Enable.
  22.  
  23. /* CONFIG3H ************************/
  24. #pragma config  MCLRE = ON                      // MCLR Pin Enable.
  25. #pragma config  MSSPMSK = MSK7          // MSSP V3 7-Bit Address Masking Mode.
  26. #pragma config  CANMX = PORTB           // ECAN MUX.
  27.  
  28. /* CONFIG4L ************************/
  29. #pragma config  BBSIZ = BB1K                    // Boot Block Size.
  30. #pragma config  STVREN = ON                     // Stack Full/Underflow Reset.
  31.  
  32. /* CONFIG5L ************************/
  33. #pragma config  CP3 = OFF                               // Code Protection.
  34. #pragma config  CP2 = OFF                               // Code Protection.
  35. #pragma config  CP1 = OFF                               // Code Protection.
  36. #pragma config  CP0 = OFF                               // Code Protection.
  37.  
  38. /* CONFIG5H ************************/
  39. #pragma config  CPD = OFF                               // Data EEPROM Code Protection.
  40. #pragma config  CPB = OFF                               // Boot Block Code Protection.
  41.  
  42. /* CONFIG6L ************************/
  43. #pragma config  WRT3 = OFF                              // Write Protection.
  44. #pragma config  WRT2 = OFF                              // Write Protection.
  45. #pragma config  WRT1 = OFF                                      // Write Protection.
  46. #pragma config  WRT0 = OFF                              // Write Protection.
  47.  
  48. /* CONFIG6H ************************/
  49. #pragma config  WRTD = OFF                              // Data EEPROM Write.
  50. #pragma config  WRTB = OFF                              // Boot Block Write Protection.
  51. #pragma config  WRTC = OFF                              // Configuration Register Write.
  52.  
  53. /* CONFIG7L ************************/
  54. #pragma config  EBTR3 = OFF                             // Table Read Protection.
  55. #pragma config  EBTR2 = OFF                             // Table Read Protection.
  56. #pragma config  EBTR1 = OFF                             // Table Read Protection.
  57. #pragma config  EBTR0 = OFF                             // Table Read Protection.
  58.  
  59. /* CONFIG7H ************************/
  60. #pragma config  EBTRB = OFF                             // Boot Block Table Read Protection.
  61.  
  62.  
  63. #if     defined ( _PIC18F26K80_H_ )
  64.         #define FREQ_64MHz      64000000
  65.         #define FREQ_16MHz      16000000
  66.         #define FREQ_8MHz       8000000
  67.         #define FREQ_4MHz       4000000
  68.         #define FREQ_1MHz               1000000
  69. #endif
  70.  
  71. #define TRUE            0x01
  72. #define FALSE           0x00
  73.  
  74. #include "Oscillator.c"
  75. #include "UART.c"
  76. #include "ADC.c"
  77. #include "PWMs.c"
  78. #include "CVD.c"
  79. #include "PullUps.c"
  80. #include "stdio.h"
  81.  
  82.  
  83. #define LED1_ON         PORTCbits . RC2 = 0x01;
  84. #define LED2_ON         PORTCbits . RC3 = 0x01;
  85.  
  86. #define LED1_OFF                PORTCbits . RC2 = 0x00;
  87. #define LED2_OFF                PORTCbits . RC3 = 0x00;
  88.  
  89. //typedef enum _BOOL { FALSE = 0, TRUE } BOOL;
  90.  
  91. struct  _TOUCH_SENSORS
  92. {
  93.         unsigned char   Button0;
  94.         unsigned        char    Button1;
  95.         unsigned int            Slider0;
  96.         } TOUCH_SENSORS;
  97.  
  98.  
  99. void SetUp ( void )
  100. {
  101.         SetUpOscillator ( OSC_16MHz );
  102.  
  103.         TRISC = 0x00;
  104.  
  105.         TRISB = 0x08;
  106.         EnablePullUps ( WPU7 );
  107.  
  108.         SetUpUART ( BAUD_RATE_57600 );
  109.        
  110.         SetUpADC ( sAN1 | sAN2, RIGHT_JUSTIFIED, VDD_VSS, FOSC_32 );
  111.  
  112.         SetUpCVDTouch ( CVD_CH_3 );
  113.  
  114.         SetUpCVDTouchSensor ( CVD_CH_1, DEFAULT_CVD_THRESHOLD,
  115.                                                         DEFAULT_CVD_TRIP, DEFAULT_CVD_HYST,
  116.                                                         CVD_CH_3, CVD_SENSOR_TRIS_1, CVD_SENSOR_PORT_1 );
  117.         SetUpCVDTouchSensor ( CVD_CH_2, DEFAULT_CVD_THRESHOLD,
  118.                                                         DEFAULT_CVD_TRIP, DEFAULT_CVD_HYST,
  119.                                                         CVD_CH_3, CVD_SENSOR_TRIS_2, CVD_SENSOR_PORT_2 );
  120.                                
  121.         }
Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 04 de Septiembre de 2013, 00:15:37
Here is the code for CVD Touch Sensig

Once again, for those who  program in CCS, here are the libraries and example....

main.c
Código: C
  1. #include "18F26K80.h"
  2. #define _PIC18F26K80_H_
  3.  
  4. #FUSES          INTRC_IO, NOWDT, NOPROTECT, BROWNOUT, PUT, MCLR
  5.  
  6. #USE                    DELAY ( int = 16MHz )
  7.  
  8. #USE                    RS232 ( Baud = 57600, Xmit = PIN_C6, Rcv = PIN_C7 )
  9.  
  10. #include "SetUp.c"
  11.  
  12.  
  13. void main ( )
  14. {
  15.         SetUp ( );
  16.  
  17.         LED1_OFF;
  18.         LED2_OFF;
  19.  
  20.         printf ( "Application Ready...\n" );   
  21.         printf ( "CVD:\n" );   
  22.        
  23.         while ( TRUE )
  24.         {
  25.                 delay_ms ( 15 );
  26.                 TOUCH_SENSORS . Button0 = DecodeCVDTouchSensor ( CVD_CH_1 );
  27.                 TOUCH_SENSORS . Button1 = DecodeCVDTouchSensor ( CVD_CH_2 );
  28.                        
  29.                 LED1_OFF;
  30.                 LED2_OFF;
  31.  
  32.                 if ( TOUCH_SENSORS . Button0 )
  33.                 {
  34.                         LED1_ON;
  35.                         }      
  36.                 if ( TOUCH_SENSORS . Button1 )
  37.                 {
  38.                         LED2_ON;
  39.                         }
  40.  
  41.                 if ( !PORTB . RB7 )                                     // For debbuging propouses.
  42.                         DebbugCVDTouchSensor ( CVD_CH_1, CVD_CH_2 );
  43.                 }
  44. }

SetUp.c
Código: C
  1. #include "CVD.c"
  2. #include "ECANRegisters.h"
  3. #include "InterruptsRegisters.h"
  4. #include "Oscillator.c"
  5. #include "PullUps.c"
  6.  
  7.  
  8. #define LED1_ON         PORTC . RC2 = 0x01;
  9. #define LED2_ON         PORTC . RC3 = 0x01;
  10.  
  11. #define LED1_OFF                PORTC . RC2 = 0x00;
  12. #define LED2_OFF                PORTC . RC3 = 0x00;
  13.  
  14.  
  15. struct  _TOUCH_SENSORS
  16. {
  17.         unsigned char   Button0;
  18.         unsigned        char    Button1;
  19.         unsigned int            Slider0;
  20.         } TOUCH_SENSORS;
  21.  
  22.  
  23.  
  24. void SetUp ( void )
  25. {
  26.         SetUpOscillator ( OSC_16MHz );
  27.  
  28.         TRISC = 0x00;
  29.  
  30.         TRISB = 0x08;
  31.         EnablePullUps ( ALL_WPU );
  32.  
  33.         CANCON = 0;
  34.         CANSTAT = 0;
  35.         ECANCON = 0b10000000;
  36.  
  37.         SetUpADC ( sAN1 | sAN2, RIGHT_JUSTIFIED, VDD_VSS, FOSC_32 );
  38. //      setup_adc(ADC_CLOCK_INTERNAL );
  39. //      setup_adc_ports( sAN1 | sAN2 );
  40.  
  41.         SetUpCVDTouch ( CVD_CH_3 );
  42.  
  43.         SetUpCVDTouchSensor ( CVD_CH_1, DEFAULT_CVD_THRESHOLD,
  44.                                                         DEFAULT_CVD_TRIP, DEFAULT_CVD_HYST,
  45.                                                         CVD_CH_3, CVD_SENSOR_TRIS_1, CVD_SENSOR_PORT_1 );
  46.         SetUpCVDTouchSensor ( CVD_CH_2, DEFAULT_CVD_THRESHOLD,
  47.                                                         DEFAULT_CVD_TRIP, DEFAULT_CVD_HYST,
  48.                                                         CVD_CH_3, CVD_SENSOR_TRIS_2, CVD_SENSOR_PORT_2 );
  49.         }

CVD.c
Código: C
  1. /************ CVD.c *********/
  2.  
  3. #include "CVD.h"
  4. #include "ADC.c"
  5. #include "stdio.h"
  6.  
  7. /** struct where the values for every cvd touch sensor saves its own values **/
  8. typedef struct _CVD_SENSOR
  9. {
  10.         unsigned int16  Threshold;              // Un-pressed Sensor value.
  11.         unsigned char   Trip;                   // Difference between pressed and un-pressed switch.
  12.         unsigned char   Hysteresis;             // Amount to change.
  13.         unsigned char   PinRef;                 // Charging Pin to Reference.
  14.         unsigned char   Tris;                   // SFR Tris Register.
  15.         unsigned char   Port;                   // SFR Port Register.
  16.         unsigned char   SensorState;    // Actual Sensor State.
  17.         unsigned int16  SensorRead;             // ADC value.
  18.         } CVD_TOUCH_SENSOR;
  19.  
  20. volatile CVD_TOUCH_SENSOR cvd_sensors [ NUMBER_OF_CVD_SENSORS ];
  21.  
  22.  
  23. /*******************************************************************/
  24. /*      -SetUpCVDTouch ( ReferencePin )
  25. /*              -ReferencePin
  26. /*              *configures the Pin which is a reference for touch sensors.
  27. /*              should be high (VDD) to charge and pass voltage to the sensors
  28. /*              internally.    
  29. /*
  30. /*      -SetUpCVDTouchSensor ( CVDSensorNumber, Threshold
  31. /*                                                      Trip, Hysteresis,
  32. /*                                                      ChargingPin, Tris, Port )
  33. /*              -TouchSensorNumber
  34. /*              -Threshold
  35. /*              -Trip
  36. /*              -Hysteresis
  37. /*              -ChargingPin    (reference pin)
  38. /*              -Tris
  39. /*              -Port
  40. /*              *sets the Touch Sensor Channel to be read.
  41. /*
  42. /*      -CVDTouchSensorNumber ( CVDTouchSensorNumber )
  43. /*              -CVDTouchSensorNumber
  44. /*              *Returns the value stored in ptrSensor -> SensorState
  45. /*               if pressed = 1; else = 0.
  46. /*
  47. /*      -DebbugCVDTouchSensor ( TouchSensorNumber, TouchSensorNumber )
  48. /*              -TouchSensorNumber
  49. /*              -TouchSensorNumber
  50. /*              *Prints out the value of any two touch sensors, int (16-bit).
  51. /*
  52. /******************************************************************/
  53.  
  54.  
  55. /********* Configure the CVD Touch Pin Reference ********************/
  56. void SetUpCVDTouch ( unsigned char ReferencePin )
  57. {
  58.         switch ( ReferencePin )
  59.         {
  60.                 case CVD_CH_0:
  61.                         REFERENCE_TRIS_PIN_0 = AS_OUTPUT;       // Chargin pin as output
  62.                         REFERENCE_PIN_0 = TO_VDD;                                       // and logic high.
  63.                         break;
  64.                 case CVD_CH_1:
  65.                         REFERENCE_TRIS_PIN_1 = AS_OUTPUT;       // Chargin pin as output
  66.                         REFERENCE_PIN_1 = TO_VDD;                                       // and logic high.
  67.                         break;
  68.                 case CVD_CH_2:
  69.                         REFERENCE_TRIS_PIN_2 = AS_OUTPUT;       // Chargin pin as output
  70.                         REFERENCE_PIN_2 = TO_VDD;                                       // and logic high.
  71.                         break;
  72.                 case CVD_CH_3:
  73.                         REFERENCE_TRIS_PIN_3 = AS_OUTPUT;       // Chargin pin as output
  74.                         REFERENCE_PIN_3 = TO_VDD;                                       // and logic high.
  75.                         break;
  76. //              case CVD_CH_4:
  77. //                      REFERENCE_TRIS_PIN_4 = AS_OUTPUT;       // Chargin pin as output
  78. //                      REFERENCE_PIN_4 = TO_VDD;                                       // and logic high.
  79. //                      break;
  80.                 case CVD_CH_5:
  81.                         REFERENCE_TRIS_PIN_5 = AS_OUTPUT;       // Chargin pin as output
  82.                         REFERENCE_PIN_5 = TO_VDD;                                       // and logic high.
  83.                         break;
  84.                        
  85.                 default:
  86.                         break;
  87.                 }      
  88.         }      
  89.  
  90.        
  91. /********* Configure the CVD Touch Sensor to use ********************/
  92. void SetUpCVDTouchSensor ( unsigned char CVDSensorNumber, unsigned int16 Threshold,
  93.                                                         unsigned char Trip, unsigned char Hysteresis,
  94.                                                         unsigned char ChargingPin, unsigned char Tris, unsigned char Port )
  95. {
  96.         CVD_TOUCH_SENSOR* ptrSensor;
  97.         ptrSensor = ( CVD_TOUCH_SENSOR* ) cvd_sensors + CVDSensorNumber;        // Pointing to the Touch Sensor
  98.                                                                                                                                         // to be Set it.
  99.         ptrSensor -> Threshold = Threshold;                                                             // Pasing the values to
  100.         ptrSensor -> Trip = Trip;                                                                                       // the Sensors
  101.         ptrSensor -> Hysteresis = Hysteresis;
  102.         ptrSensor -> PinRef = ChargingPin;
  103.         ptrSensor -> Tris = Tris;
  104.         ptrSensor -> Port = Port;
  105.         }      
  106.  
  107. /********* Decode the Touch Sensor Selsected; verified if it is Pressed or not ********************/
  108. int DecodeCVDTouchSensor ( unsigned char CVDTouchSensorNumber )
  109. {
  110.         unsigned char Temp;
  111.  
  112.         CVD_TOUCH_SENSOR* ptrSensor;
  113.         ptrSensor = ( CVD_TOUCH_SENSOR* ) cvd_sensors +         // Pointing to the Touch Sensor
  114.                                 CVDTouchSensorNumber;                                           // to be Decode it.
  115.                                                                                                                                                        
  116.  
  117. #if     defined ( _PIC18F26K80_H_ ) || defined ( _PIC18F45K22_H_ )
  118.         Temp = ADCON0;
  119.         Temp &= 0b10000011;                                                     // Cleaning up the previous channel.
  120.         ADCON0 = Temp;
  121. #elif   defined ( _PIC16F887_H_ ) || defined ( _PIC16F886_H_ )
  122.         ADCON0 &= 0b11000011;                                           // Cleaning up the previous channel.
  123. #elif defined   ( _PIC12F683_H_ )
  124.         ADCON0 &= 0b11110011;                                           // Cleaning up the previous channel.
  125. #endif
  126.         Temp = ADCON0;
  127.         Temp |= ptrSensor -> PinRef << 2;                               // Setting the AD channel to read
  128.         ADCON0 = Temp;                                                  // without changing the ADCON0 value.
  129.  
  130.         delay_us ( 20 );
  131.  
  132.         switch ( CVDTouchSensorNumber )
  133.         {
  134.                 case CVD_CH_0:
  135.                         CVD_SENSOR_TRIS_0 = AS_OUTPUT;          // Set Sensing pin as output
  136.                         CVD_SENSOR_PORT_0 = TO_GND;                     // and logic low (discharging it).
  137.                
  138.                         CVD_SENSOR_TRIS_0 = AS_INPUT;           // Sensing pin as input.
  139.                         break;
  140.                 case CVD_CH_1:
  141.                         CVD_SENSOR_TRIS_1 = AS_OUTPUT;          // Set Sensing pin as output
  142.                         CVD_SENSOR_PORT_1 = TO_GND;                     // and logic low (discharging it).
  143.                
  144.                         CVD_SENSOR_TRIS_1 = AS_INPUT;           // Sensing pin as input.
  145.                         break;
  146.                 case CVD_CH_2:
  147.                         CVD_SENSOR_TRIS_2 = AS_OUTPUT;          // Set Sensing pin as output
  148.                         CVD_SENSOR_PORT_2 = TO_GND;                     // and logic low (discharging it).
  149.                
  150.                         CVD_SENSOR_TRIS_2 = AS_INPUT;           // Sensing pin as input.
  151.                         break;
  152.                 case CVD_CH_3:
  153.                         CVD_SENSOR_TRIS_3 = AS_OUTPUT;          // Set Sensing pin as output
  154.                         CVD_SENSOR_PORT_3 = TO_GND;                     // and logic low (discharging it).
  155.                
  156.                         CVD_SENSOR_TRIS_3 = AS_INPUT;           // Sensing pin as input.
  157.                         break;
  158. //              case CVD_CH_4:
  159. //                      CVD_SENSOR_TRIS_4 = AS_OUTPUT;          // Set Sensing pin as output
  160. //                      CVD_SENSOR_PORT_4 = TO_GND;                     // and logic low (discharging it).
  161. //             
  162. //                      CVD_SENSOR_TRIS_4 = AS_INPUT;           // Sensing pin as input.
  163. //                      break;
  164.                 case CVD_CH_5:
  165.                         CVD_SENSOR_TRIS_5 = AS_OUTPUT;          // Set Sensing pin as output
  166.                         CVD_SENSOR_PORT_5 = TO_GND;                     // and logic low (discharging it).
  167.                
  168.                         CVD_SENSOR_TRIS_5 = AS_INPUT;           // Sensing pin as input.
  169.                         break;
  170.                        
  171.                 default:
  172.                         break;
  173.                 }      
  174.  
  175. #if     defined ( _PIC18F26K80_H_ ) || defined ( _PIC18F45K22_H_ )
  176.         Temp = ADCON0;
  177.         Temp &= 0b10000011;                                                     // Cleaning up the previous channel.
  178.         ADCON0 = Temp;
  179. #elif   defined ( _PIC16F887_H_ ) || defined ( _PIC16F886_H_ )
  180.         ADCON0 &= 0b11000011;                           // Cleaning up the previous channel.
  181. #elif defined   ( _PIC12F683_H_ )
  182.         ADCON0 &= 0b11110011;                           // Cleaning up the previous channel.
  183. #endif
  184.         Temp = ADCON0;
  185.         Temp |= CVDTouchSensorNumber << 2;      // Setting the AD channel to read
  186.         ADCON0 = Temp;                                  // without changing the ADCON0 value.
  187.  
  188.         ADCON0 . GO = 0x01;                                                                             // Starts the reading of the capacitive sensor.                        
  189.         while ( ADCON0 . GO );                                                                          // Wait until convertion is done.
  190.         ptrSensor -> SensorRead = ( ( ( unsigned int16 ) ADRESH ) << 8 ) |      
  191.                         ( ADRESL );                                                                                             // Return the value from two Bytes.
  192.  
  193.         if ( ptrSensor -> SensorRead < DEFAULT_CVD_THRESHOLD - DEFAULT_CVD_TRIP )
  194.         {
  195.                 ptrSensor -> SensorState = PRESSED;
  196.                 }      
  197.  
  198.         else if ( ptrSensor -> SensorRead > DEFAULT_CVD_THRESHOLD - DEFAULT_CVD_TRIP + \
  199.                         DEFAULT_CVD_HYST )
  200.         {
  201.                 ptrSensor -> SensorState = UNPRESSED;
  202.                 }      
  203.  
  204.         return ptrSensor -> SensorState;
  205.         }
  206.        
  207. /********* Debug the CVD touch Sensor; debug propouse ********************/
  208. void DebbugCVDTouchSensor ( unsigned char TouchSensorNumber0, unsigned char TouchSensorNumber1 )
  209. {
  210.         CVD_TOUCH_SENSOR* ptrSensor0;
  211.         ptrSensor0 = ( CVD_TOUCH_SENSOR* ) cvd_sensors + TouchSensorNumber0;            // Pointing to the Touch Sensor
  212.                                                                                                                                                         // to be Decode it.
  213.         CVD_TOUCH_SENSOR* ptrSensor1;
  214.         ptrSensor1 = ( CVD_TOUCH_SENSOR* ) cvd_sensors + TouchSensorNumber1;                    // Pointing to the Touch Sensor
  215.                                                                                                                                                         // to be Decode it.
  216.  
  217.         printf ( "\n%ld,%ld", ptrSensor0 -> SensorRead  , ptrSensor1 -> SensorRead );   // Printing out the actual value
  218.                                                                                                                                                         // on the sensor selected.
  219.         }

CVD.h
Código: C
  1. /************ CVD.h *********/
  2.  
  3. #include "PORTsRegisters.h"
  4.  
  5. /********* A/D Port Configuration Control bits ********/
  6. #define CVD_CH_0        0x00            // The same as ADC channels.
  7. #define CVD_CH_1        0x01
  8. #define CVD_CH_2        0x02
  9. #define CVD_CH_3        0x03
  10. #define CVD_CH_4        0x04
  11. #define CVD_CH_5        0x05
  12. #define CVD_CH_6        0x06
  13. #define CVD_CH_7        0x07
  14. #define CVD_CH_8        0x08
  15.  
  16.  
  17. /********* TRISx Port Configuration Control bits ********/
  18. /*********                                                      ADC pins only ********/
  19. /***** Reference Pin, got to be a ADC Pin ******************/
  20. #define REFERENCE_TRIS_PIN_0    TRISA . TRISA0
  21. #define REFERENCE_TRIS_PIN_1    TRISA  . TRISA1
  22. #define REFERENCE_TRIS_PIN_2    TRISA  . TRISA2
  23. #define REFERENCE_TRIS_PIN_3    TRISA  . TRISA3
  24. #define REFERENCE_TRIS_PIN_4    TRISA  . TRISA4
  25. #define REFERENCE_TRIS_PIN_5    TRISA  . TRISA5
  26.  
  27. #define REFERENCE_PIN_0                 PORTA  . RA0
  28. #define REFERENCE_PIN_1                 PORTA  . RA1
  29. #define REFERENCE_PIN_2                 PORTA  . RA2
  30. #define REFERENCE_PIN_3                 PORTA  . RA3
  31. #define REFERENCE_PIN_4                 PORTA  . RA4
  32. #define REFERENCE_PIN_5                 PORTA  . RA5
  33.  
  34.  
  35. /********* TRISx Port Configuration Control bits ********/
  36. /*********                                                      ADC pins only ********/
  37. /***** Sensors Pin, got to be a ADC Pin ********************/
  38. #define CVD_SENSOR_TRIS_0               TRISA  . TRISA0
  39. #define CVD_SENSOR_TRIS_1               TRISA  . TRISA1
  40. #define CVD_SENSOR_TRIS_2               TRISA  . TRISA2
  41. #define CVD_SENSOR_TRIS_3               TRISA  . TRISA3
  42. #define CVD_SENSOR_TRIS_4               TRISA  . TRISA4
  43. #define CVD_SENSOR_TRIS_5               TRISA  . TRISA5
  44.  
  45. #define CVD_SENSOR_PORT_0               PORTA  . RA0
  46. #define CVD_SENSOR_PORT_1               PORTA  . RA1
  47. #define CVD_SENSOR_PORT_2               PORTA  . RA2
  48. #define CVD_SENSOR_PORT_3               PORTA  . RA3
  49. #define CVD_SENSOR_PORT_4               PORTA  . RA4
  50. #define CVD_SENSOR_PORT_5               PORTA  . RA5
  51.  
  52.  
  53. /********* General Registers ********/
  54. #define PRESSED         0x01
  55. #define UNPRESSED       0x00
  56.  
  57. #define AS_INPUT                0x01
  58. #define AS_OUTPUT       0x00
  59.  
  60. #define TO_VDD          0x01
  61. #define TO_GND          0x00
  62.  
  63.  
  64. /********* Values to Set The Touch Sensors ********/
  65. #define DEFAULT_CVD_THRESHOLD           3000            // 3000; Un-pressed switch value.
  66. #define DEFAULT_CVD_TRIP                                200             // 200; Difference between pressed and un-pressed switch.
  67.                                                                                                
  68. #define DEFAULT_CVD_HYST                                65              // 65; Amount to change from pressed to un-pressed.
  69.  
  70.  
  71. #define NUMBER_OF_CVD_SENSORS   0x05            // Number of Sensors to be read in the uC.

Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: rotting79 en 24 de Octubre de 2013, 01:09:16
here is a training board for the PIC18F45K22 Training Board, which has ready to use three 10-bits analog inpits with 0.01uF on it, five PWM outputs, the whole PORTD, five CTMU Touch Buttons, four LEDs, RS232 Serial Comminication, 32k Bytes (less the bootloader firmware at the very end of the momory), seven Timers (three 8-bits, four 16-bits), SRLatch,2CCP, 2ECCP, 1ECCP (Full Bridge), Internal FVR and DAC, 1536 Bytes of SRAM, 256 Bytes EEPROM, two SPI and two I2C, two Comparators, 16MHz internal Oscillator, 16-bit instruction Word in a 2"x4" Board.


Título: Re: Explicacion INT_AD y Touch Capacitivo por favor....
Publicado por: delirio en 18 de Mayo de 2015, 09:46:57
Buenos días amigos, los sigo muy de cerca cada vez que puedo poner manos a la obra en algún proyecto, lo mio es solo hobby y últimamente he tenido poco tiempo.
Con respecto a este tema me surgen algunas dudas...

* a que le llaman canal secundario??
* es una entrada del pic que solo se usa para este fin?
* puntualmente en la porción de código que postea Nocturno, en RA0 y RA1 estará mi sensor o sector de cobre del PCB... y en RA2 que hay??

Gracias de antemano

- Fernando