我写了一个msp430f149的程序 但当我打开串口是用pwm控制的电机就不能工作了,但关闭串口又能工作 了
哪位大神帮帮我看看
#include<msp430x14x.h>
typedef unsigned char uchar;
typedef unsigned int uint;
uint gPID ;
uchar gPIDflag;
int speed,iError, iIncpid;
typedef struct PID //PID数据结构
{
int SetPoint; // 设定目标 Desired Value
long SumError; //误差累计
float Propor
tion; // 比例常数 Proportional Const
float Integral; // 积分常数 Integral Const
float Derivative; // 微分常数 Derivative Const
int LastError; //Error[-1]
int PrevError; //Error[-2]
} PID;
static PID sPID;
static PID *sptr=&sPID;
void init_PID()
{
sptr->SetPoint=150; // 设定目标 Desired Value
sptr->SumError=0; //误差累计
sptr->Proportion=1; // 比例常数 Proportional Const
sptr->Integral=0; // 积分常数 Integral Const
sptr->Derivative=0; // 微分常数 Derivative Const
}
int dtIncPIDCalc(int NextPoint) //增量式PID算法
{
// register int iError, iIncpid; //当前误差
iError = sptr->SetPoint - NextPoint; //增量计算
iIncpid=sptr->Proportion*iError //E[k] 项
- sptr->Integral*sptr->LastError //E[k-1]项
+ sptr->Derivative*sptr->PrevError; //E[k-2]项
//存储误差,用于下次计算
sptr->PrevError = sptr->LastError;
sptr->LastError = iError;
return(iIncpid);//返回增量值
}
void Delays(void)
{
uchar i=20;
uint j;
while(i--)
{
j=200;
while(j--);
}
}
// 波特率9600
void USART0int()
{
P3SEL|= 0x30; // P3.4,5选择为UART收发端口
ME1|=UTXE0 + URXE0; // 使能USART0收发
UCTL0|=CHAR; // 8-bit character
UTCTL0|=SSEL0; // UCLK = ACLK
UBR00=0x03; // 32k/2400 - 13.65
UBR10=0x00; //
UMCTL0=0x4A; // Modulation
UCTL0&=~SWRST; // 初始化UART0状态机
IE1 |= URXIE0; // 使能接收中断
}
void send_to_pc(uint value )
{
while (!(IFG1 & UTXIFG0));
TXBUF0 = value;
// while (!(IFG1 & UTXIFG0));
// TXBUF0 = '
';
Delays();
}
void timerBint()
{
TBCTL=TBSSEL_1+ID_0+MC_1; //TBSSEL_1时钟源选择32.768khz//8khz,ID_3是1,2,4,8分频 ,MC_1计数/计时模式为加
TB0CCTL0=CCIE; //开timerB的中断
TBCCR0=39; //32768/8=4096;4096/2=2048 定时5ms
}
void pwmright(int speed1 )
{
P1DIR|=0x04;
P1SEL|=0x04;
CCR0=255;
CCTL1=OUTMOD_7;
CCR1=speed;
TACTL=TASSEL_1+MC_1;
}
void pwmleft(int speed2 )
{
P1DIR|=0x08;
P1SEL|=0x08;
CCR0=255;
CCTL2=OUTMOD_7;
CCR2=speed;
TACTL=TASSEL_1+MC_1;
}
void pwmstop()
{
P1DIR|=0x0C;
P1SEL|=0x0C;
CCR0=255;
CCTL1=OUTMOD_7;
CCR1=255;
CCTL2=OUTMOD_7;
CCR2=255;
TACTL=TASSEL_1+MC_1;
}
void _EINT();
void main( )
{
WDTCTL = WDTPW + WDTHOLD;
speed=100; //speed越da速度越大
P2IES=0X02;
P2IE=0X02;
P2OUT=0Xff;
USART0int(); //串口初始化
timerBint();
pwmleft(speed);
_EINT();
while(1)
{
// send_to_pc(speed);
send_to_pc(gPID);
// send_to_pc(iIncpid );
}
}
#pragma vector=PORT1_VECTOR
__interrupt void PORT1_ISR()
{
gPID++;
if(gPIDflag==1)
{
gPID=0;
gPIDflag=0;
}
}
/*
#pragma vector=TIMERB0_VECTOR //Timer0_B中断
__interrupt void Timer0_B()
{
dtIncPIDCalc(gPID);
speed+=iIncpid;
gPIDflag=1;
if(speed>255) speed=255;
if(speed>0) speed=0;
}*/
一周热门 更多>