参考一下吧
430单片机
#include <msp430x16x.h>
int n=0;
int flag = 1;
int spwm[256]=
{
1 , 5 , 9 , 13 , 17 ,21 , 24 , 28 ,
32 , 36 , 40 , 43 , 47 , 51 , 55, 58 , 62,
66 , 70 , 73 , 77 , 81, 85 , 88 , 92 , 96,
99 , 103, 106 , 110 , 114 ,117, 121, 124,
128 , 131 , 135 , 138, 141 , 145 ,148 ,152 , 155 ,
158 , 162 ,165 , 168 , 171 , 174, 178 , 181,
184 ,187 , 190, 193, 196, 199 , 202 , 205 , 208 ,
210 ,213 , 216, 219, 221 , 224 , 227 , 229,
232 ,234 , 237 , 239 , 242 , 244 , 247 , 249 , 251 ,
253 , 256 , 258 , 260 , 262 , 264 , 266 , 268,
270 , 272 , 274 , 276 , 277 , 279 , 281 , 282 ,
284 , 285 , 287 , 288 , 290, 291, 293 ,294, 295,
296 , 297 ,299, 300, 301 , 302, 303 , 303 , 304 ,
305 , 306 , 307 , 307 , 308 , 308 , 309, 309,
310 , 310 , 311 , 311 , 311 , 311 , 311, 311,
311 , 311 , 311 , 311 ,311 , 311 , 311 , 311 , 310,
310 , 309 , 309, 308 , 308 , 307, 307, 306,
305 ,304 , 304 , 303 , 302 , 301 , 300, 299 , 298,
296 , 295 , 294 ,293 , 291 ,290 , 289, 287 ,286 ,
284 ,282 , 281 ,279 , 277 , 276, 274 , 272,
270 , 268 , 266 , 264 , 262 , 260 , 258 , 256,
254 , 251, 249 , 247 , 244 , 242 , 240, 237 , 235,
232 , 229, 227 , 224 ,222 , 219, 216 ,213, 211 ,
208 ,205 , 202, 199, 196 , 193 , 190 ,187,
184 , 181 , 178 , 175 ,171 , 168 , 165 , 162 , 158,
155 , 152 ,148 , 145 , 142, 138 , 135 , 131,
128 ,124, 121 , 117 , 114, 110 , 107 , 103, 99 ,
96 ,92 , 88 , 85 , 81 , 77 , 74, 70,
66 , 62 , 59 , 55 , 51 , 47 , 44 , 40 , 36,
32 , 28 , 25 , 21, 17 , 13 , 9 , 5, 2
};
void TimerB_Init()
{
P4SEL |= BIT2; // Set for Timer A1
P4DIR |= BIT2;
P4SEL |= BIT1; // Set for Timer A1
P4DIR |= BIT1;
TACCR0 = 312;
TBCCR0 = 312; // Init TACCR0 w/ sample prd=CCR0+1
TBCCR1 = 0;
TBCCR2 = 0;
TBCCTL1 = OUTMOD_7; // Set/reset
TBCCTL2 = OUTMOD_7; // Set/reset
CCTL0= CCIE;
TBCTL = TBCLR + MC_1 + TBSSEL_2; // clear TAR, up mode*/
TACTL = TACLR + MC_1 + TASSEL_2; // clear TAR, up mode*/
}
void ini_sys(void)
{
BCSCTL1 &= ~XT2OFF; // XT2on
do
{
IFG1 &= ~OFIFG; // Clear OSCFault flag
for (char i = 0xFF; i > 0; i--); // Time for flag to set
}
while ((IFG1 & OFIFG)); // OSCFault flag still set?
BCSCTL2=SELM_2+SELS;
}
void main()
{
WDTCTL=WDTPW+WDTHOLD;
ini_sys();
TimerB_Init();
_EINT();
while(1)
{
if( flag == 1)
{
TBCCR2 = 0;
TBCCR1=spwm[n];
}
else
{
TBCCR1 = 0;
TBCCR2 = spwm[n%256];
}
}
}
#pragma vector=TIMERA0_VECTOR
__interrupt void TimerA(void)
{
n++;
if((n%256) == 0)
{
flag = 1- flag;
}
if(n == 512)
{
n = 0;
}
} |