00001 /* CD_PWM.c 00002 PulseWiddthModulated Signals 00003 Angel Perles. June 2009. 00004 00005 used resources 00006 P0.0 00007 00008 dependencies 00009 00010 IMPORTANT: 00011 P2.2 also used for DigitalOutput example 00012 8-bits PWM, could be enhanced with 16-bit PWM mode 00013 00014 */ 00015 00016 #include <C8051F340.h> 00017 #include "CD_Main.h" 00018 00019 sbit Pin_PWM0 = P0^0; /* PWM output pin */ 00020 00021 /****************************************************************************/ 00022 void CD_PWM_Init(void) { 00023 00024 // Configure PCA time base; overflow interrupt disabled 00025 PCA0CN = 0x00; // Stop counter; clear all flags 00026 //PCA0MD = 0x08; // Use SYSCLK as time base 00027 PCA0MD = 0x00; /* SYSCLK/12 as time base (48 MHz/12) */ 00028 00029 PCA0CPM0 = 0x42; // Module 0 = 8-bit PWM mode 00030 00031 00032 // Configure initial PWM duty cycle = 50% 00033 /* PCA0CPH0 = 256 - (256 * 0.5); */ 00034 00035 /* A 0% duty cycle may be generated by clearing the ECOMn bit to ‘0’. */ 00036 XBR1 |= 0x01; // Put CEX0 on Crossbar 00037 CR = 1; // Start PCA Counter 00038 00039 } 00040 00041 00042 /****************************************************************************/ 00043 void CD_PWM(unsigned char *msg) large { 00044 unsigned char subdevice; 00045 //unsigned int ADC_result; 00046 00047 unsigned int val; 00048 00049 00050 /* parse string values */ 00051 if (CD_HexaStrTo_u8(msg, 2, &subdevice)) { 00052 CD_LinkMsgError(CD_Error_DAQBadSubdevice); /* bad subdevice */ 00053 return; 00054 }; 00055 00056 /* test subdevice numbre */ 00057 if (subdevice != 0x30) { 00058 CD_LinkMsgError(CD_Error_DAQBadSubdevice); /* bad subdevice */ 00059 return; 00060 }; 00061 00062 /* duty-cycle, from 100.0 to 0.0 without comma (tenths of percent) */ 00063 if (CD_DecStrTo_u16(msg+2, 4, &val)) { 00064 CD_LinkMsgError(CD_Error_BadValue); /* bad value */ 00065 return; 00066 }; 00067 00068 val /= 10; /* should be enhanced on next versions */ 00069 00070 if (val == 0) { /* 0% */ 00071 PCA0CPM0 &= ~0x40; /* ECOM0=0 to stop generation */ 00072 } else { 00073 PCA0CPH0 = 256 - (256 * val)/100; 00074 PCA0CPM0 |= 0x40; /* ECOM0=1 to enable output */ 00075 } 00076 00077 CD_LinkMsgOK(); 00078 }