Autor Tema: control the light of LED from the PWM Module on 18F4550  (Leído 16557 veces)

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

adbensi

  • Visitante
control the light of LED from the PWM Module on 18F4550
« en: 09 de Abril de 2006, 09:07:34 »
I need help..   :D

I would like to control the light of
LED (10%, 20%, 50%, 70%, 100% of bright)
from the PWM Module on 18F4550, in RC2 pin. 


I read the 18F4550 Manual
and put this is in main.c:

#include "io.h"
//P1M1 P1M0 DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0
// 0 0 0 0 1 1 0 0
CCP1CON=0b00001100; // PWM: Single CCP CCP1
//RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON
// 0 0 0 0 1 0 0 1
T3CON=0b00001001;
mInitPWM();

and put this in io.h
#define mInitPWM() TRISCbits.TRISC2=0;

And.. I doesn´t know how to do to control the LED now   :lol:

Then, I read the CSS Manual
and put this is in main.c:
long duty;
duty = 520;
setup_ccp1(CCP_PWM);
set_pwm1_duty(duty);

Then, the MPLAB7.31+C18 3.2 write to me:
Error [1105] symbol 'CCP_PWM' has not been defined 


Why? The CCP_PWM is a constant, what is wrong?   :?
I doesn´t change the 18F4550.h.

Please, help me how to build PWM in CSS. 
Thanks!! Saluto!
« Última modificación: 12 de Abril de 2006, 16:34:44 por adbensi »

Desconectado Nocturno

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 18286
    • MicroPIC
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #1 en: 10 de Abril de 2006, 02:03:54 »
Esto está en 18F452.H
Código: [Seleccionar]
#define CCP_PWM                         0xC
Si te da ese error puede ser porque has modificado el 18F452.H, aunque ya dices que no lo has hecho, o bien porque no lo has incluido en tu programa:
Código: [Seleccionar]
#include <18F452.h>
Pero no te comas el coco, prueba el ejemplo que trae CCS que seguro que funciona, y desarrolla tu programa a partir de modificaciones de ese:
Código: [Seleccionar]
/////////////////////////////////////////////////////////////////////////
////                           EX_PWM.C                              ////
////                                                                 ////
////  This program will show how to use the built in PIC PWM.        ////
////  The program takes an analog input and uses the digital         ////
////  value to set the duty cycle.  The frequency is set by          ////
////  the user over the RS-232.                                      ////
////                                                                 ////
////  Configure the CCS prototype card as follows:                   ////
////      Connect a scope to pin C2                                  ////
////      Connect pin A0 to output of the POT                        ////
////                                                                 ////
////  Jumpers:                                                       ////
////     PCM,PCH    pin C7 to RS232 RX, pin C6 to RS232 TX           ////
////                                                                 ////
////  This example will work with the PCM and PCH compilers.  The    ////
////  following conditional compilation lines are used to include a  ////
////  valid device for each compiler.  Change the device, clock and  ////
////  RS232 pins for your hardware if needed.                        ////
/////////////////////////////////////////////////////////////////////////
////        (C) Copyright 1996,2003 Custom Computer Services         ////
//// This source code may only be used by licensed users of the CCS  ////
//// C compiler.  This source code may only be distributed to other  ////
//// licensed users of the CCS C compiler.  No other use,            ////
//// reproduction or distribution is permitted without written       ////
//// permission.  Derivative programs created using this software    ////
//// in object code form are not restricted in any way.              ////
/////////////////////////////////////////////////////////////////////////


#if defined(__PCM__)
#include <16F877.h>
#fuses HS,NOWDT,NOPROTECT,NOLVP
#use delay(clock=10000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, BRGH1OK)

#elif defined(__PCH__)
#include <18F452.h>
#fuses HS,NOWDT,NOPROTECT,NOLVP
#use delay(clock=10000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, BRGH1OK)
#endif


void main() {
   char selection;
   byte value;


   printf("\r\nFrequency:\r\n");
   printf("    1) 19.5 khz\r\n");
   printf("    2) 4.9 khz\r\n");
   printf("    3) 1.2 khz\r\n");

   do {
     selection=getc();
   } while((selection<'1')||(selection>'3'));


   setup_ccp1(CCP_PWM);   // Configure CCP1 as a PWM

          //   The cycle time will be (1/clock)*4*t2div*(period+1)
       //   In this program clock=10000000 and period=127 (below)
          //   For the three possible selections the cycle time is:
    //     (1/10000000)*4*1*128 =  51.2 us or 19.5 khz
    //     (1/10000000)*4*4*128 = 204.8 us or 4.9 khz
    //     (1/10000000)*4*16*128= 819.2 us or 1.2 khz

   switch(selection) {
     case '1' : setup_timer_2(T2_DIV_BY_1, 127, 1);
                break;
     case '2' : setup_timer_2(T2_DIV_BY_4, 127, 1);
                break;
     case '3' : setup_timer_2(T2_DIV_BY_16, 127, 1);
                break;
   }



  setup_port_a(ALL_ANALOG);
  setup_adc(adc_clock_internal);
  set_adc_channel( 0 );
  printf("%c\r\n",selection);

  while( TRUE ) {
    value=read_adc();

    printf("%2X\r",value);

    set_pwm1_duty(value);          // This sets the time the pulse is
                                   // high each cycle.  We use the A/D
                                   // input to make a easy demo.
                                   // the high time will be:
                                   //  if value is LONG INT:
                                   //    value*(1/clock)*t2div
                                   //  if value is INT:
                                   //    value*4*(1/clock)*t2div
                                   // for example a value of 30 and t2div
                                   // of 1 the high time is 12us
                                   // WARNING:  A value too high or low will
                                   //           prevent the output from
                                   //           changing.
  }

}

adbensi

  • Visitante
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #2 en: 11 de Abril de 2006, 00:37:06 »
Thanks nocturno66,  :D
I tried but doesn´t can to solve the error whith set_pwm1_duty.  :(

I put this is in main.c:

/** PWM IO.H ********************************************************/
#include <p18f4550.h>
#include "io.h"
MORE CODE HERE

void main(void)
{   
    mInitPWM();

    long duty;
    duty = 520;
    setup_ccp1(CCP_PWM);
    set_pwm1_duty(duty);

}//end main

MORE CODE HERE
/** END opcode main.h ***********************************************/

and put this in io.h

/** PWM opcode IO.H **************************************************/
MORE CODE HERE
#define mInitPWM()  TRISCbits.TRISC2=0; CCP1CON=0b00001100; T3CON=0b10001001;

// Timer 3
#define T3_DISABLED         0
#define T3_DIV_BY_1         0
#define T3_DIV_BY_2         0x10
#define T3_DIV_BY_4         0x20
#define T3_DIV_BY_8         0x30

//P1M1 P1M0 DC1B1 DC1B0 CCP1M3 CCP1M2 CCP1M1 CCP1M0
//   0    0     0     0      1      1      0      0
// PWM: Single CCP CCP1 = 0Ch
// CCP Functions: SETUP_CCP, SET_PWM_DUTY
#define CCP_OFF            0
#define CCP_PWM            0xC
#define CCP_PWM_PLUS_1      0x1c
#define CCP_PWM_PLUS_2      0x2c
#define CCP_PWM_PLUS_3      0x3c

//RD16 T3CCP2 T3CKPS1 T3CKPS0 T3CCP1 T3SYNC TMR3CS TMR3ON
//   1      0       0       0      1      0      0      1
#define CCP_USE_TIMER3      0x100
#define T3_CCP1_TO_5      0x48
#define T3_CCP2_TO_5      0x8
#define T3_CCP3_TO_5      0x40
MORE CODE HERE
/** END io.h ******************************************************/

Then, the MPLAB7.31+C18 3.2 write to me:

Error - could not find definition of symbol 'set_pwm1_duty' in file 'main.o'.
Errors    : 1

what is wrong? I need more anythink in code to work the function set_pwm1_duty ?

Thanks a lot!! Saluto!   :D
« Última modificación: 12 de Abril de 2006, 16:35:32 por adbensi »

Desconectado migsantiago

  • Colaborador
  • DsPIC33
  • *****
  • Mensajes: 8257
    • Sitio de MigSantiago
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #3 en: 11 de Abril de 2006, 00:54:40 »
Hello abdensi

I have never programmed any PIC18, I just noticed something in your message:

Error - could not find definition of symbol 'set_pwm1_duty' in file 'main.o'.
Errors    : 1


It makes reference to a main.O file, I think it should be main.C.

If the program is compiled correctly, you'd better remove any code you didn't need to use that may already be included in main.c.

Good luck
« Última modificación: 11 de Abril de 2006, 01:56:43 por migsantiago »

Desconectado maxluis

  • Colaborador
  • PIC16
  • *****
  • Mensajes: 129
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #4 en: 11 de Abril de 2006, 01:01:44 »
Estimado adbensi:
Tratare de adjuntar archivo c. de un proyecto para un instrumento que pueda medir la intensidad de recepcion (de una barrera infrarojo), mientras hago variable por ancho de pulso la emision.......a los que mas saben de ccs...les pìdo que me simplifiquen el programa....pienso que esta muy.....redundante......no capto mucho.....tratare de adjuntar tambien la simulacion en proteus....si lo encuentran interesante le seguimos dando...HE TRATADO DE COLGAR LOS ARCHIVOS ¡ Y DICE QUE SON MUY GRANDES??? COMO SE HACE???
saludos.
maxluis.

Desconectado maxluis

  • Colaborador
  • PIC16
  • *****
  • Mensajes: 129
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #5 en: 11 de Abril de 2006, 01:05:35 »
COLGANDO UN ARCHIVO.

Desconectado maxluis

  • Colaborador
  • PIC16
  • *****
  • Mensajes: 129
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #6 en: 11 de Abril de 2006, 01:23:56 »
EL ARCHIVO PARA SIMULAR EN PROTEUS
SALUDOS.
MAXLUIS.

Desconectado Nocturno

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 18286
    • MicroPIC
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #7 en: 11 de Abril de 2006, 01:57:20 »
Adbensi, ¿eso es CCS o es otro lenguaje C?

Desconectado migsantiago

  • Colaborador
  • DsPIC33
  • *****
  • Mensajes: 8257
    • Sitio de MigSantiago
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #8 en: 11 de Abril de 2006, 01:58:26 »
Me parece que hay un compilador de C para pic18 de parte de Microchip... talvez sea ese.

adbensi

  • Visitante
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #9 en: 11 de Abril de 2006, 07:33:12 »
Hi,  :D

 I can't find declaration of this function 'set_pwm1_duty' or macro.  :?

 I found different PWM related function in C18 2.40 manual. Put "SetDCPWM1" as searching phrase
in google, and find some examples for C18,
http://www.informatik.fh-wiesbaden.de/~linn/vpdv05/aufzug/download/prog1/main.c

For sample:
 #include <pwm.h>
 OpenPWM1(0xff);
 OpenTimer2(T2_PS_1_4 & T2_POST_1_1 & TIMER_INT_OFF);
 SetDCPWM1(820);

 I use the version of Mplab 7.31, C18 3.02 and MPLINK 4.02 ?
 On make, reports:

Executing: "C:\MCC18\bin\mcc18.exe" -p=18F4550  /i"D:\MCHPFSUSB\Cdc_4550" "usbctrltrf.c" -fo="D:\MCHPFS~1\Cdc_4550\_output\usbctrltrf.o" -k -Oi -Ou- -Ot- -Ob- -Op- -Or- -Od- -Opa-

MPLAB C18 v3.02 (demo) Copyright 1999-2005 Microchip Technology Inc.
Days remaining until demo becomes feature limited:  50

D:\MCHPFSUSB\Cdc_4550\user\user.c:222:Warning [2058] call of function without prototype (setup_ccp1(CCP_PWM);)  :?
D:\MCHPFSUSB\Cdc_4550\user\user.c:223:Warning [2058] call of function without prototype (set_pwm1_duty(duty);)  :?

Executing: "C:\MCC18\bin\mplink.exe" /l"c:\mcc18\lib" /k"D:\MCHPFSUSB\Cdc_4550" "D:\MCHPFSUSB\Cdc_4550\rm18f4550.lkr" "D:\MCHPFSUSB\Cdc_4550\_output\main.o" "D:\MCHPFSUSB\Cdc_4550\_output\usbmmap.o" "D:\MCHPFSUSB\Cdc_4550\_output\usbdrv.o" "D:\MCHPFSUSB\Cdc_4550\_output\usb9.o" "D:\MCHPFSUSB\Cdc_4550\_output\usbdsc.o" "D:\MCHPFSUSB\Cdc_4550\_output\usbctrltrf.o" "D:\MCHPFSUSB\Cdc_4550\_output\user.o" "D:\MCHPFSUSB\Cdc_4550\_output\cdc.o" /m"D:\MCHPFS~1\Cdc_4550\_output\SAQUSB.map" /w /o"SAQUSB.cof"
MPLINK 4.02, Linker
Copyright (c) 2006 Microchip Technology Inc.
Error - could not find definition of symbol 'set_pwm1_duty' in file 'D:\MCHPFSUSB\Cdc_4550\_output\main.o'.  :x
Errors    : 1

BUILD FAILED: Tue Apr 11 07:12:01 2006

I don´t understand because the Mplink report this error: definition of symbol 'set_pwm1_duty', if set_pwm1_duty was constant in compiler.

I replace somethinks.. and BUILD SUCCEEDED :D
I didn´t know if work, but now build sucessufull.

I try and report, ok.

The new io.h
/** PWM ***********************************************************/
#define mInitPWM()  TRISCbits.TRISC2=0; CCP1CON=0b00001100; T3CON=0b10001001;

The new main.c
/** MAIN ***********************************************************/
void main(void)
{   
    mInitPWM();
    SetDCPWM1(820);

Ps: Maxluis, proteus is fantastic, very nice :D Thanks!

Todopic, Thanks a lot..
Alexandre.
« Última modificación: 12 de Abril de 2006, 09:13:39 por adbensi »

Desconectado Nocturno

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 18286
    • MicroPIC
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #10 en: 12 de Abril de 2006, 02:24:10 »
Me alegro que finalmente lo solucionaste, aunque ahora entiendo porqué no te servía nuestra ayuda. Los ejemplos que te poníamos eran CCS y tú estabas usando C18. :?

adbensi

  • Visitante
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #11 en: 12 de Abril de 2006, 03:18:08 »
Hola!!

 Tienes razon, no fui claro a esso, desculpa.
 
 Os exemplos ajudaram muito!! Aprendi mais com os problemas, faz poucos meses que estou utilizando C, e tenho muito que aprender. Estou terminando meu trabalho de conclusão de curso, e não encontrei em nenhum outro lugar um forum tão amistoso como todopic;

 E por falar no forum, parabéns pelo layout! Esta muito bom!! Gracias :D

 Infelizmente não consegui controlar a intensidade do LED na porta PWM como esperava, a resposta do LED ao trem de pulsos é muito rápida, e não consigo um controle linear fazendo a média entre VCC e 0.

 Não imagino como aproveitar o PWM para controlar a intensidade de um LED tomando como base a tensão media de um trem de pulsos.

 Talvez me falte algum conceito para aplicar o processo nesse sentido,

DATA = (0 a F pela serial, caracter por caracter)

/** PWM ***********************************************************/

// pwm_PR1[0]=(DATA & 0x0F); // ex:DATA =
// pwm_PR1[1]=(DATA & 0x0F); // ex:DATA =
// pwm_PR2[0]=(DATA & 0x0F); // ex:DATA =
// pwm_PR2[1]=(DATA & 0x0F); // ex:DATA =
pwm_PER[0]=(DATA & 0x0F); // ex:DATA = 3
pwm_PER[1]=(DATA & 0x0F); // ex:DATA = 2
pwm_DCY[0]=(DATA & 0x0F); // ex:DATA = 1
pwm_DCY[1]=(DATA & 0x0F); // ex:DATA = F
pwm_DCY[2]=(DATA & 0x0F); // ex:DATA = F

TRISCbits.TRISC2=0;         // Pass 1 - C2 is out
// PR2 = ((byte*)pwm_PR2);      // Pass 2 - Period by PR2 Register 0 - FF
// CCPR1L = ((byte*)pwm_PR1);   // Pass 5 - PWM Duty cycle 0 - FF
OpenTimer2( TIMER_INT_OFF & T2_PS_1_1 & T2_POST_1_1);   // Pass 9
OpenPWM1((byte*)pwm_PER);   // char periodo : [(period ) + 1] x 4 x TOSC xTMR2 prescaler. 0 - FF
SetDCPWM1((byte*)pwm_DCY);  // unsigned int dutycycle 0 - 3FF
CCP1CON=0b00001100;         // Pass 4 - PWM: Single CCP CCP1

// DEBUG
// void OpenPWM1(unsigned char period)
// {
//  CCPR1L = 0x00; // Power on reset(POR) for duty cycle
//  CCP1CON = 0x0F; // PWM for CCP1
//  PR2 = period; // Set period
//  TRISC.CCP1 = 0; // Set ouput
// }
// void SetDCPWM1(unsigned long duty_cycle)
// {
//  CCPR1L = duty_cycle >> 2; // Place 8 MSbs in CCPR1L
//  duty_cycle = (duty_cycle << 4) & 0x30; // Place 2 LSbs in CCP1CON
//  CCP1CON = CCP1CON | duty_cycle;
// }

 No tieno pinas libre en PIC, senão uno conversor DA seria bueno.
 Una duda, PWM és capaz de controla una salida linearmente (0 a 5vcc)? :?

Saludo!
« Última modificación: 12 de Abril de 2006, 21:57:27 por adbensi »

Desconectado megajhonny

  • PIC10
  • *
  • Mensajes: 1
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #12 en: 13 de Abril de 2006, 12:24:28 »
Hi  8), look, i alredy finalize my carrer at the UTT, here at Mexico, and i do something related with the PWM, i did the control for a DC Motor, and i use the PWM "creating it", not using the PWM of the PIC, Why?, ok, i used PIC BASIC PRO :P, it is more easy to use but it is not usefull to you, but maybe my explanation can help ya, ok?

Lets see, the PWM is a work frequency that is composed by High time and Low time, the work time of the PWM is changeable cuz not all the dispositives like leds or motor are the same, we need to play with the WT (work time) ok.

So, the first thing thet we need to do is search the WT, i used for a motor and for one led 1000Hz = 1000us ok, it makes the led brigth and you can see the diference of birghtness, but how to do the PWM manually? it's easy.

I use a pot (variable resistance) and make the sentence like this:

                            WT=HighT-LowT
                           
then:

                             WT=1000us

then i got the sentence for HighT, because i use the ADC from the PIC, so the pot use 255 bits, then is like an if, if the pot is at 255 then the led is completely bright, if not, if the pot is 0 the led is off, so, lets check, at the pin1 of port A i pluged the pot 1 and make the next sentence:

                             HighT=(WT*Pin1)/255

and the led will bright at 100%, cuz if the pot is 255 the HighT is 1000us, so the line of the graphic is like this:

        |   HighT                                                    |    HighT                  HighT
    5V|++++++                                            5V  |++++++++++ ++++++++++
        |            +                                                 |                     ++
        |            +                  ------------>              |                     ++
        |            +                                                 |                     ++
        |            +   LowT                                       |                     ++ LowT
    0v|_______++++++__                              0v |____________++____________
        |<-------WT------>|                                     |<----WT------>||<------WT----->|

         Normal PWM                                                     New PWM, letting at maximum the HighT  :o

ok, so, how to get the LowT, simply, its the difference bettween WT and HighT:

             LowT= WT-HighT

If the the HighT is 1000us and the WT 1000us, the LowT is null.

In PBP the sentence is like this:

          ADCIN 1, B0
          WT=1000
          HIGHT = (WT*B0)/255
          LOWT=WT-HIGHT

          HIGH PORTB.1
          PAUSEUS HIGHT
          LOW PORTB.1
          PAUSEUS LOWT

          END

For the users of PBP, it needs also the DEFINE sentences for the adc, but it is a piece of cake, and for adbensi, the pwm makes that, a linear signal for any dispositive, or u can see it as linear, cuz the analog frequency is so faster that your eyes can't see it. For a motor, u need a H bridge.

Search Duty Cycle, i need to go, but in next time maybe i could help you more, SEE YA FELLAS

Si necesitan traduccion al español, nomas diganme y nos ponemos en contacto  :D

adbensi

  • Visitante
Re: control the light of LED from the PWM Module on 18F4550
« Respuesta #13 en: 18 de Abril de 2006, 22:59:39 »
Gracias megajhonny,
Excelente documentacion!

Estoy lendo MPLAB_C18_Libraries para entender las funções del C18. Tieno problemas en PWM.

PIC BASIC PRO és mui interessante :D
Con su explicacion, vou tentar algunas modificações :D
Gracias! Envio los resultados en forum.

Saludos!